Top JavaScript Interview Questions and Answers
This section provides answers to frequently asked JavaScript interview questions, suitable for both beginners and experienced professionals.
What is JavaScript?
JavaScript is a lightweight, interpreted, object-based scripting language commonly used for making web pages interactive. It's different from Java. A JavaScript interpreter (built into web browsers) executes the code.
Key Features of JavaScript
- Lightweight
- Interpreted
- Network-centric
- Works well with Java and HTML
- Open-source
- Cross-platform
Creator and Original Name of JavaScript
Brendan Eich (a Netscape programmer) created JavaScript in just ten days in September 1995. It was initially called Mocha, then LiveScript, before finally becoming JavaScript.
Advantages of JavaScript
- Reduced server interaction
- Immediate feedback to users
- High interactivity
- Rich user interfaces
Disadvantages of JavaScript
- No built-in multithreading or multiprocessing
- Limited file system access
- Security limitations (client-side code can be manipulated)
Named Functions
A named function has a name specified during its definition.
Example
function myFunction() {
// ... function body ...
}
Types of JavaScript Functions
JavaScript has two main function types:
- Named functions: Functions with a name (defined using the
function
keyword). - Anonymous functions: Functions without a name (often created using function expressions).
Anonymous Functions
Anonymous functions are functions without names, often defined using function expressions. They are dynamically created at runtime.
Example
let myFunc = function() {
// ... function body ...
};
Assigning Anonymous Functions to Variables
Yes, anonymous functions can be assigned to variables, making them reusable and enabling functional programming techniques.
The arguments
Object
The arguments
object (available inside functions) provides access to the arguments passed to the function, even if they weren't explicitly declared as parameters.
Closures
A closure occurs when an inner function accesses variables from its surrounding (enclosing) function's scope, even after the outer function has finished executing.
Example: Closure
function outer() {
let x = 10;
function inner() {
console.log(x); // inner() has access to x from outer()
}
return inner;
}
let myClosure = outer();
myClosure(); // Output: 10
charAt()
Method
The charAt(index)
method retrieves the character at a specified index within a string.
JavaScript vs. JScript
JavaScript (Netscape) and JScript (Microsoft) are essentially the same language; Microsoft's version was renamed to avoid trademark issues.
Hello World in JavaScript
Example
<script>
alert("Hello, world!");
</script>
More details on the Hello World example
Case Sensitivity in JavaScript
Yes, JavaScript is case-sensitive.
Browser Object Model (BOM)
The BOM provides ways to interact with the browser window (e.g., opening new windows, accessing browser history).
More details on the Browser Object Model
Document Object Model (DOM)
The DOM represents the HTML document as a tree of objects. You can use it to access and manipulate HTML elements.
More details on the Document Object Model
The window
Object
The window
object represents the browser window. It provides methods for creating dialog boxes (alert()
, confirm()
, prompt()
), opening and closing windows, setting timeouts (setTimeout()
), and more.
More details on the window object
The history
Object
The history
object allows you to navigate through the browser's history using methods like back()
, forward()
, and go(number)
.
More details on the history object
Comments in JavaScript
- Single-line comments:
// ...comment...
- Multi-line comments:
/* ...comment... */
Creating Functions in JavaScript
Function Syntax
function myFunction() {
// Function body
}
More details on creating functions
Data Types in JavaScript
JavaScript has two main categories of data types:
- Primitive data types:
string
,number
,boolean
,bigint
,undefined
,null
,symbol
- Non-primitive (object) data types: Objects, arrays, functions
What is JavaScript?
JavaScript is a lightweight, interpreted, object-based scripting language primarily used to add interactivity to web pages. It's distinct from Java. Web browsers contain JavaScript interpreters that execute the code.
Features of JavaScript
- Lightweight
- Interpreted
- Suitable for network-centric applications
- Complements Java and HTML
- Open-source
- Cross-platform
JavaScript's Origin and Names
Brendan Eich (a Netscape programmer) created JavaScript in just ten days during September 1995. It was initially known as Mocha, then LiveScript, before the name JavaScript was adopted.
Advantages of JavaScript
- Reduced server load
- Fast user feedback
- Highly interactive user interfaces
- Rich user experiences
Disadvantages of JavaScript
- Limited built-in multithreading/multiprocessing capabilities.
- Client-side security vulnerabilities.
- Browser inconsistencies can lead to cross-browser compatibility issues.
Named Functions
A named function has a name defined in its declaration.
Example
function myFunction() {
// Function code
}
Types of Functions
- Named Functions: Have a name in their declaration.
- Anonymous Functions: Don't have a name; often defined using function expressions.
Anonymous Functions
Anonymous functions are declared without a name. They are often used as function expressions or callbacks.
Example
let myFunc = function() {
// Function code
};
Assigning Functions to Variables
Yes, functions (both named and anonymous) can be assigned to variables, enabling functional programming techniques.
The arguments
Object
The arguments
object (inside a function) provides access to all arguments passed to that function, regardless of whether they were explicitly declared as parameters.
Closures
A closure is when a function has access to variables from its surrounding scope(s), even after those outer functions have finished execution.
charAt()
Method
The charAt(index)
method returns the character at a specified index (position) in a string (index starts at 0).
JavaScript vs. JScript
JScript is Microsoft's version of JavaScript. They are functionally very similar.
Hello World in JavaScript
Example
<script>
console.log("Hello, world!");
</script>
Case Sensitivity
JavaScript is case-sensitive (myVariable
and MyVariable
are different).
Browser Object Model (BOM)
The BOM provides objects and methods for interacting with the browser window and its environment.
Document Object Model (DOM)
The DOM represents the HTML document as a tree structure of objects, making it easy to access and manipulate web page elements.
The window
Object
The window
object represents the browser window. It provides methods like alert()
, confirm()
, prompt()
, open()
, close()
, and setTimeout()
.
More details on the window object
The history
Object
The history
object allows you to navigate the browser's history (back()
, forward()
, go()
).
More details on the history object
Comments in JavaScript
- Single-line:
// ...comment...
- Multi-line:
/* ...comment... */
More details on JavaScript comments
Creating Functions
Function Declaration
function myFunction(param1, param2) {
// Function body
return result;
}
More details on creating functions
Data Types in JavaScript
JavaScript has primitive and non-primitive (object) data types.
- Primitive:
string
,number
,boolean
,bigint
,undefined
,null
,symbol
- Non-primitive (Objects): Objects, arrays, functions
undefined
undefined
is a value assigned to a variable that has been declared but not yet given a value.
null
null
represents the intentional absence of a value.
Symbol
Symbol()
creates a unique and anonymous value.
The typeof
Operator
The typeof
operator returns a string indicating the type of an operand (number
, string
, boolean
, object
, function
, undefined
, symbol
, bigint
).
Non-Primitive Data Types
Non-primitive types can store complex data structures.
Objects
Objects are collections of key-value pairs.
Example: Object Literal
let myObject = { name: "John", age: 30 };
Arrays
Arrays store ordered collections of items.
Example: Array Literal
let myArray = [1, 2, 3, "hello"];
==
vs. ===
==
checks for loose equality (values only, type coercion may occur). ===
checks for strict equality (values and types must match).
Dynamically Adding HTML
Use innerHTML
to dynamically add or modify HTML content within an element.
Example
document.getElementById("myElement").innerHTML = "<p>New text</p>";
Dynamically Adding Text
Use innerText
to add or change plain text content within an element (innerHTML would include HTML tags).
Example
document.getElementById("myElement").innerText = "New text";
Creating Objects in JavaScript
Three ways to create objects:
- Object literal:
{ key: value, ... }
new Object()
: Creates an empty object.- Constructor functions: Define a function that acts as a blueprint for creating objects.
More details on creating objects
Creating Arrays in JavaScript
Three ways to create arrays:
- Array literal:
[item1, item2, ...]
new Array()
: Creates an empty array or an array of a specified size.- Using the
Array
constructor: More flexible but less common for simple array creation.
More details on creating arrays
isNaN()
Function
The isNaN()
function checks if a value is *Not-a-Number* (NaN
).
String Concatenation and Numeric Operators
In JavaScript, the +
operator performs both arithmetic addition and string concatenation. The context determines which operation occurs.
10 + 20 + "30"
results in"3030"
(string concatenation after the numeric addition)."10" + 20 + 30
results in"102030"
(string concatenation).
Client-Side vs. Server-Side JavaScript
Client-side JavaScript: Runs in the user's web browser. Server-side JavaScript (Node.js): Runs on a server.
Cookie Storage Location
The location of cookies varies depending on the operating system and web browser.
event.preventDefault()
vs. event.stopPropagation()
event.preventDefault()
prevents the default action associated with an event. event.stopPropagation()
stops the event from bubbling up the DOM tree.
JavaScript's Original Name
The original name of JavaScript was Mocha.
Checking event.preventDefault()
Usage
event.defaultPrevented
is a boolean property that indicates whether event.preventDefault()
has been called for that event.
undefined
vs. null
undefined
means a variable has been declared but not assigned a value. null
is an assignment that represents the intentional absence of a value.
Setting the Wait Cursor
[Explain how to change the mouse cursor to a wait cursor using JavaScript. This typically involves setting the CSS `cursor` property of an element.]
Three-Dimensional Arrays
var myArray = [[[]]];
declares a 3D array.
Java vs. JavaScript
Java and JavaScript are distinct languages. Java is a general-purpose, object-oriented language, while JavaScript is primarily a scripting language for web browsers.
Negative Infinity
Dividing a negative number by zero results in -Infinity
in JavaScript.
View State vs. Session State
View state: Data specific to a single page within a user's session. Session state: Data associated with a user's session, accessible across multiple pages.
JavaScript Popup Boxes
JavaScript provides alert()
, confirm()
, and prompt()
for creating various types of popup dialog boxes.
Detecting the Client's Operating System
You can get some OS information using navigator.appVersion
and navigator.userAgent
, but this is not always perfectly reliable.
Submitting a Form with a Link
[Include JavaScript code to submit a form using a link click.]
JavaScript vs. ASP Script Speed
JavaScript is generally faster because it executes in the user's browser without needing server-side processing.
Changing Background Color
[Include JavaScript code to change the background color of an HTML document.]
Exception Handling in JavaScript
Use try...catch...finally
blocks to handle errors in JavaScript.
Form Validation
[Include a brief explanation of how to perform form validation in JavaScript. This would involve adding event listeners to form elements and checking if the input is valid.]
Learn More about JavaScript Form Validation
Email Validation
[Include a brief explanation of how to perform email validation in JavaScript. This involves regular expressions to check if the email format is correct.]
Learn More about JavaScript Email Validation
The this
Keyword
The this
keyword refers to the current object within a method or function.
JavaScript Debugging
Use your browser's developer tools (console, debugger) to debug JavaScript code.
The debugger
Keyword
The debugger
keyword inserts a breakpoint into your JavaScript code. When the code execution reaches this line, it pauses, allowing you to use your browser's developer tools to step through the code, inspect variables, and diagnose problems.
Example
function myFunction() {
let x = 10;
debugger; // Breakpoint here
let y = x + 5;
console.log(y);
}
Strict Mode in JavaScript
Strict mode ("use strict") is enabled by placing the string "use strict";
as the first statement in a script or function. It enforces stricter parsing and error handling, helping to catch common coding mistakes that might otherwise go unnoticed.
Example
"use strict";
x = 10; // This will throw an error in strict mode (x is not declared)
The Math
Object
The Math
object provides mathematical constants (like Math.PI
) and functions (Math.random()
, Math.sin()
, Math.cos()
, etc.). It doesn't have a constructor.
Example
let randomNumber = Math.random(); // Generates a random number between 0 and 1
The Date
Object
The Date
object is used to work with dates and times. You can get the current date and time, and perform various date and time calculations.
Example
let currentDate = new Date();
let year = currentDate.getFullYear();
The Number
Object
The Number
object represents numeric values (integers and floating-point numbers). It follows the IEEE 754 standard for floating-point representation.
Example
let myNumber = new Number(123);
The Boolean
Object
The Boolean
object represents boolean values (true
or false
).
Example
let myBoolean = new Boolean(true);
The TypedArray
Object
TypedArray
objects provide array-like views of binary data buffers. They are used for efficient manipulation of raw binary data.
Example
let myArray = new Uint8Array([1, 2, 3]); // Uint8Array is one type of TypedArray
The Set
Object
A Set
stores unique values of any type (primitives or object references).
Example
let mySet = new Set([1, 2, 2, 3]); // mySet will contain [1, 2, 3]
The WeakSet
Object
A WeakSet
is similar to a Set
, but its elements are weakly held (the garbage collector can remove them if no other references exist). It only stores objects, not primitive types.
The Map
Object
A Map
stores key-value pairs. Keys must be unique; values can be of any type.
Example
let myMap = new Map([["name", "John"], ["age", 30]]);
The WeakMap
Object
Similar to Map
, but keys are weakly referenced (allowing garbage collection if no other references exist). Keys must be objects; values can be any type.
Falsy Values
Falsy values are those that evaluate to false
in a Boolean context: ""
(empty string), 0
, -0
, 0n
(BigInt zero), null
, undefined
, NaN
, and false
. You can use the Boolean function or the double NOT operator (!!
) to check if a value is falsy.
Hoisting
Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their scope (global or local) during compilation. This can lead to unexpected behavior if not understood.
JavaScript Multiple Choice Questions (MCQs)
-
Which event will NOT cancel the default behavior if preventDefault() is called?
Answer: KeyPress. The `keypress` event is deprecated and does not reliably support `preventDefault()` in modern browsers.
-
What is the primary difference between JavaScript and Java?
Answer: Java is compiled, JavaScript is interpreted. JavaScript runs in browsers and interpreters, while Java compiles into bytecode.
-
Which syntax correctly creates a RegExp object?
Answer: Both of the above. Regular expressions can be created using either literal notation or the constructor.
-
What is the purpose of prototype inheritance in JavaScript?
Answer: To extend class functionality. Prototypes allow inheritance of methods and properties in JavaScript.
-
What is the correct syntax to change the text of a paragraph element?
Answer: Both of the above. Both `innerHTML` and `textContent` can modify the text of a paragraph element.
-
How do you define instance-specific behavior in JavaScript classes?
Answer: Using instance methods. These methods are unique to each instance and can access instance-specific properties.
-
How do you parse a JSON string into a JavaScript object?
Answer:
JSON.parse()
. This method converts a JSON string into a JavaScript object. -
What keyword is used to call a superclass constructor in a subclass?
Answer:
super
. It is used to call the constructor of a superclass in JavaScript classes. -
What is the correct syntax for the
eval()
function?Answer: Both of the above. The
eval()
function can execute code or evaluate expressions passed as a string. -
What does the
Object.assign()
method do?Answer: Copies properties from one or more objects to a target object. It is commonly used for cloning or merging objects.