JavaScript Interview Questions for 5 Years Experience
As a developer with 5 years of experience in JavaScript, you are expected to have a deep understanding of not just the syntax, but also the intricacies of the language, advanced concepts, and practical problem-solving skills. The following article provides a detailed guide to the kinds of JavaScript interview questions you might face with 5 years of experience.
1. What are Closures in JavaScript?
A closure is a function that retains access to variables from its outer (enclosing) function even after the outer function has finished executing. Closures allow for powerful patterns like data encapsulation and private variables.
Example:
functionouterFunction() {
let outerVariable = "I am an outer variable";
returnfunctioninnerFunction() {
console.log(outerVariable); // Accessing the outer function's variable
};
}
const closureExample = outerFunction();
closureExample(); // Output: I am an outer variable
Explanation:
Here, innerFunction
is a closure because it "remembers" the scope of outerFunction
, allowing it to access outerVariable
even after outerFunction
has executed.
2. Explain the difference between null
and undefined
.
null
is an assignment value. It is explicitly assigned to a variable to indicate that it has no value.undefined
means that a variable has been declared but has not yet been assigned a value.
Example:
let a;
console.log(a); // Output: undefined
let b = null;
console.log(b); // Output: null
Key Differences:
null
is an object, whileundefined
is its own primitive type.undefined
is automatically assigned when a variable is declared without a value, whereasnull
is explicitly assigned.
3. What is the Event Loop in JavaScript?
The Event Loop is a fundamental concept in JavaScript that allows asynchronous behavior. It continuously checks the call stack for functions to execute. If the stack is empty, it checks the message queue to execute pending callback functions.
Example:
console.log("Start");
setTimeout(function() {
console.log("This is delayed");
}, 2000);
console.log("End");
Output:
Start
End
This is delayed
Explanation:
In this example:
Start
is logged immediately.setTimeout
is asynchronous, so it is added to the message queue after 2 seconds.End
is logged next.- After 2 seconds, the callback function inside
setTimeout
is executed, logging "This is delayed".
4. What is Prototypal Inheritance in JavaScript?
In JavaScript, objects can inherit properties and methods from other objects. This is called prototypal inheritance. Every JavaScript object has an internal property called [[Prototype]]
, which refers to another object.
Example:
functionPerson(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
const john = newPerson("John");
john.greet(); // Output: Hello, my name is John
Explanation:
Here, Person
is a constructor function. Person.prototype
is used to add methods to the Person
class, which can be accessed by all instances of Person
.
5. What is the this
keyword in JavaScript?
The this
keyword refers to the object it is a method of. Its value depends on the context in which it is used:
- In global scope,
this
refers to the global object (window
in browsers). - In object methods,
this
refers to the object calling the method. - In event handlers,
this
refers to the element that triggered the event.
Example:
const person = {
name: "John",
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
person.greet(); // Output: Hello, my name is John
functionshowThis() {
console.log(this); // `this` refers to the global object (window in browsers)
}
showThis();
6. Explain let
, const
, and var
in JavaScript.
var
: Declares a variable with function scope or globally if declared outside a function. It is hoisted to the top of the scope and can be re-declared and updated.let
: Declares a block-scoped variable that cannot be re-declared but can be updated.const
: Declares a block-scoped variable that cannot be re-declared or updated. The value is immutable (for primitive values), but objects declared withconst
can still have their properties modified.
Example:
var x = 10;
let y = 20;
const z = 30;
x = 15; // valid
y = 25; // valid
z = 35; // TypeError: Assignment to constant variable.
7. What is the difference between ==
and ===
in JavaScript?
==
performs type coercion before comparison, meaning it converts the operands to the same type.===
checks for both value and type equality, without performing type coercion.
Example:
console.log(5 == "5"); // Output: true
console.log(5 === "5"); // Output: false
8. What is the bind
method in JavaScript?
The bind
method creates a new function that, when called, has its this
keyword set to the provided value. It also allows for partial function application.
Example:
const person = {
name: "John",
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
const greetJohn = person.greet.bind(person);
greetJohn(); // Output: Hello, my name is John
9. What are Promises in JavaScript?
A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation. It has three states:
- Pending: The operation is ongoing.
- Resolved (Fulfilled): The operation completed successfully.
- Rejected: The operation failed.
Example:
const myPromise = newPromise((resolve, reject) => {
let success = true;
if (success) {
resolve("Promise resolved successfully");
} else {
reject("Promise failed");
}
});
myPromise
.then(result =>console.log(result)) // Output: Promise resolved successfully
.catch(error =>console.log(error));
10. What is the difference between synchronous and asynchronous code?
- Synchronous code executes one operation after another, blocking further execution until the current operation finishes.
- Asynchronous code allows other operations to continue executing while waiting for the completion of time-consuming tasks (like I/O operations).
Example:
// Synchronous code
console.log("Start");
console.log("End"); // Logs after "Start"
// Asynchronous code
console.log("Start");
setTimeout(() => {
console.log("Delayed");
}, 1000);
console.log("End"); // Logs before "Delayed"
Output:
Start
End
Start
End
Delayed
11. What are Arrow Functions and how do they differ from Regular Functions?
Arrow functions provide a shorter syntax for writing functions in JavaScript and also differ in how they handle this
binding.
Example:
// Regular function
functiongreet() {
console.log(this); // Refers to global object or undefined in strict mode
}
// Arrow function
constgreetArrow = () => {
console.log(this); // Inherits `this` from the surrounding lexical context
};
greet(); // Refers to global object (window in browsers)
greetArrow(); // Refers to the enclosing context of where it was defined
Key Differences:
- Arrow functions do not have their own
this
; they inheritthis
from the enclosing scope. - They have a more concise syntax (no
function
keyword).
12. What is the setTimeout
and setInterval
methods in JavaScript?
setTimeout
allows you to run a function after a specified delay.setInterval
allows you to run a function repeatedly at a specified interval.
Example:
// setTimeout
setTimeout(() => {
console.log("This will run after 2 seconds");
}, 2000);
// setInterval
let count = 0;
const interval = setInterval(() => {
console.log(`This runs every 1 second: ${++count}`);
if (count === 5) clearInterval(interval); // Stop after 5 iterations
}, 1000);
Explanation:
setTimeout
only runs once after the specified time.setInterval
runs indefinitely at the specified interval untilclearInterval
is called.
13. What is the spread operator and rest parameter in JavaScript?
- Spread operator: Used to expand elements of an iterable (e.g., arrays, objects).
- Rest parameter: Used to collect multiple arguments into an array.
Example:
// Spread operator
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // Output: [1, 2, 3, 4, 5]
// Rest parameter
functionsum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10
14. Explain the new
keyword in JavaScript.
The new
keyword is used to create an instance of an object that has a constructor function. It allocates memory and returns the newly created object.
Example:
functionPerson(name, age) {
this.name = name;
this.age = age;
}
const john = newPerson("John", 30);
console.log(john); // Output: Person { name: 'John', age: 30 }
Explanation:
- When the
new
keyword is used, it creates a new object and bindsthis
to that object inside the constructor function. - It also sets up inheritance by linking the object's prototype to the constructor's prototype.
15. What is a Debounce function and why is it used?
A debounce function limits the rate at which a function is executed. It ensures that the function is only called once, even if it is triggered multiple times in a short time frame.
Example:
functiondebounce(fn, delay) {
let timeout;
returnfunction(...args) {
clearTimeout(timeout);
timeout = setTimeout(() =>fn(...args), delay);
};
}
constlog = () => console.log("Button clicked");
const debouncedLog = debounce(log, 300);
document.querySelector("button").addEventListener("click", debouncedLog);
Explanation:
- In the example,
log
will only be called once 300 milliseconds after the last click, no matter how many times the button is clicked within that time.
16. What is the difference between call
, apply
, and bind
in JavaScript?
call()
andapply()
are used to invoke a function with a specifiedthis
value and arguments. The main difference is in how arguments are passed:call()
takes individual arguments.apply()
takes an array of arguments.
bind()
returns a new function with a specificthis
value and can accept initial arguments.
Example:
const person = {
name: "John",
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
const anotherPerson = { name: "Jane" };
person.greet.call(anotherPerson); // Output: Hello, my name is Jane
person.greet.apply(anotherPerson); // Output: Hello, my name is Jane
const boundGreet = person.greet.bind(anotherPerson);
boundGreet(); // Output: Hello, my name is Jane
17. Explain how Object.create()
works in JavaScript.
The Object.create()
method creates a new object, using the specified prototype object and properties. It allows you to set up inheritance.
Example:
const animal = {
speak: function() {
console.log("Animal speaking");
}
};
const dog = Object.create(animal);
dog.speak(); // Output: Animal speaking
Explanation:
Object.create()
allowsdog
to inherit fromanimal
. Thedog
object does not directly have thespeak
method, but it inherits it fromanimal
.
18. What is the purpose of the setImmediate
method in JavaScript?
setImmediate
is used to execute a function immediately after the current event loop cycle, similar to setTimeout(fn, 0)
. It is part of Node.js and not available in browsers.
Example:
console.log("Before");
setImmediate(() => {
console.log("Executed immediately after current event loop");
});
console.log("After");
Output:
mathematicaBefore
After
Executedimmediatelyaftercurrenteventloop
Explanation:
- The
setImmediate
function is executed after the I/O events of the current event loop cycle.
19. What are WeakMap
and WeakSet
in JavaScript?
- A
WeakMap
is a collection of key-value pairs where the keys are objects and the values can be any arbitrary value. It does not prevent garbage collection of the keys. - A
WeakSet
is a collection of objects where the objects are held weakly, meaning they can be garbage collected when there are no other references to them.
Example:
let obj1 = {};
let obj2 = {};
const weakMap = newWeakMap();
weakMap.set(obj1, "value1");
weakMap.set(obj2, "value2");
console.log(weakMap.get(obj1)); // Output: value1
obj1 = null; // obj1 can now be garbage collected
20. What is the difference between set
and map
in JavaScript?
- A
Set
is a collection of unique values. - A
Map
is a collection of key-value pairs, where the keys can be of any type.
Example:
// Set
const uniqueValues = newSet([1, 2, 2, 3]);
console.log(uniqueValues); // Output: Set { 1, 2, 3 }
// Map
const map = newMap();
map.set("name", "John");
map.set("age", 30);
console.log(map); // Output: Map { 'name' => 'John', 'age' => 30 }
Conclusion
These JavaScript interview questions cover key areas that will test your in-depth knowledge of the language, from closures to async operations, prototypal inheritance, and ES6+ features like let
, const
, and Promise
. A deep understanding of these concepts, along with experience writing clean and efficient code, will help you stand out as a JavaScript developer with 5 years of experience.
Comments
Post a Comment