
Top 20 Javascript Interview Questions 2024
JavaScript, the dynamic scripting language that powers the interactive elements of virtually every modern website, has become an integral skill for developers. Aspiring and seasoned developers alike often find themselves navigating through JavaScript-centric interviews, where a thorough understanding of the language can make all the difference. In this article, we delve into the top 20 most asked JavaScript interview questions, uncovering the intricacies of the language and offering insights that will not only sharpen your interview skills but also deepen your comprehension of JavaScript's nuances. Whether you're a seasoned developer preparing for a career move or a budding coder venturing into the vast world of JavaScript, these questions will serve as a compass, guiding you through the essential concepts and scenarios that frequently surface during interviews. So, let's embark on this journey to unravel the mysteries of JavaScript and equip ourselves with the knowledge needed to ace those critical interviews.
- What is a prototype chain?
Prototype chaining is used to build new types of objects based on existing ones. It is similar to inheritance in a class based language.
The prototype on object instance is available through Object.getPrototypeOf(object) or _proto_ property whereas prototype on constructors function is available through Object.prototype.
-
What is the difference between Call, Apply and Bind?
The difference between Call, Apply and Bind can be explained with below examples,
Call: The call() method invokes a function with a given
this
value and arguments provided one by onevar employee1 = { firstName: "John", lastName: "Rodson" }; var employee2 = { firstName: "Jimmy", lastName: "Baily" }; function invite(greeting1, greeting2) { console.log( greeting1 + " " + this.firstName + " " + this.lastName + ", " + greeting2 ); } invite.call(employee1, "Hello", "How are you?"); // Hello John Rodson, How are you? invite.call(employee2, "Hello", "How are you?"); // Hello Jimmy Baily, How are you?
Apply: Invokes the function with a given
this
value and allows you to pass in arguments as an arrayvar employee1 = { firstName: "John", lastName: "Rodson" }; var employee2 = { firstName: "Jimmy", lastName: "Baily" }; function invite(greeting1, greeting2) { console.log( greeting1 + " " + this.firstName + " " + this.lastName + ", " + greeting2 ); } invite.apply(employee1, ["Hello", "How are you?"]); // Hello John Rodson, How are you? invite.apply(employee2, ["Hello", "How are you?"]); // Hello Jimmy Baily, How are you?
Bind: returns a new function, allowing you to pass any number of arguments
var employee1 = { firstName: "John", lastName: "Rodson" }; var employee2 = { firstName: "Jimmy", lastName: "Baily" }; function invite(greeting1, greeting2) { console.log( greeting1 + " " + this.firstName + " " + this.lastName + ", " + greeting2 ); } var inviteEmployee1 = invite.bind(employee1); var inviteEmployee2 = invite.bind(employee2); inviteEmployee1("Hello", "How are you?"); // Hello John Rodson, How are you? inviteEmployee2("Hello", "How are you?"); // Hello Jimmy Baily, How are you?
Call and Apply are pretty much interchangeable. Both execute the current function immediately. You need to decide whether it’s easier to send in an array or a comma separated list of arguments. You can remember by treating Call is for comma (separated list) and Apply is for Array.
Bind creates a new function that will have
this
set to the first parameter passed to bind(). -
How do you compare Object and Map?
Objects are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Due to this reason, Objects have been used as Maps historically. But there are important differences that make using a Map preferable in certain cases:
- The keys of an Object can be Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive.
- The keys in a Map are ordered while keys added to Object are not. Thus, when iterating over it, a Map object returns keys in the order of insertion.
- You can get the size of a Map easily with the size property, while the number of properties in an Object must be determined manually.
- A Map is an iterable and can thus be directly iterated, whereas iterating over an Object requires obtaining its keys in some fashion and iterating over them.
- An Object has a prototype, so there are default keys in an object that could collide with your keys if you're not careful. As of ES5 this can be bypassed by creating an object(which can be called a map) using
Object.create(null)
, but this practice is seldom done. - A Map may perform better in scenarios involving frequent addition and removal of key pairs.
-
What is the difference between == and === operators?
JavaScript provides both strict(===, !==) and type-converting(==, !=) equality comparison. The strict operators take type of variable in consideration, while non-strict operators make type correction/conversion based upon values of variables. The strict operators follow the below conditions for different types,
- Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
- Two numbers are strictly equal when they are numerically equal, i.e., having the same number value. There are two special cases in this,
- NaN is not equal to anything, including NaN.
- Positive and negative zeros are equal to one another.
- Two Boolean operands are strictly equal if both are true or both are false.
- Two objects are strictly equal if they refer to the same Object.
- Null and Undefined types are not equal with ===, but equal with ==, i.e, null===undefined --> false, but null==undefined --> true
Some of the example which covers the above cases:
0 == false // true 0 === false // false 1 == "1" // true 1 === "1" // false null == undefined // true null === undefined // false '0' == false // true '0' === false // false []==[] or []===[] //false, refer different objects in memory {}=={} or {}==={} //false, refer different objects in memory
-
What are lambda or arrow functions?
An arrow function is a shorter syntax for a function expression and does not have its own this, arguments, super, or new.target. These functions are best suited for non-method functions, and they cannot be used as constructors.
-
What is a higher order function?
A higher-order function is a function that accepts another function as an argument or returns a function as a return value or both.
const firstOrderFunc = () => console.log("Hello, I am a First order function"); const higherOrder = (ReturnFirstOrderFunc) => ReturnFirstOrderFunc(); higherOrder(firstOrderFunc);
-
What is the currying function?
Currying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument. Currying is named after a mathematician Haskell Curry. By applying currying, an n-ary function turns into a unary function.
Let's take an example of n-ary function and how it turns into a currying function,
const multiArgFunction = (a, b, c) => a + b + c; console.log(multiArgFunction(1, 2, 3)); // 6 const curryUnaryFunction = (a) => (b) => (c) => a + b + c; curryUnaryFunction(1); // returns a function: b => c => 1 + b + c curryUnaryFunction(1)(2); // returns a function: c => 3 + c curryUnaryFunction(1)(2)(3); // returns the number 6
Curried functions are great to improve code reusability and functional composition.
-
What is a pure function?
A Pure function is a function where the return value is only determined by its arguments without any side effects. i.e, If you call a function with the same arguments 'n' number of times and 'n' number of places in the application then it will always return the same value.
Let's take an example to see the difference between pure and impure functions,
//Impure let numberArray = []; const impureAddNumber = (number) => numberArray.push(number); //Pure const pureAddNumber = (number) => (argNumberArray) => argNumberArray.concat([number]); //Display the results console.log(impureAddNumber(6)); // returns 1 console.log(numberArray); // returns [6] console.log(pureAddNumber(7)(numberArray)); // returns [6, 7] console.log(numberArray); // returns [6] As per the above code snippets, the **Push** function is impure itself by altering the array and returning a push number index independent of the parameter value, whereas **Concat** on the other hand takes the array and concatenates it with the other array producing a whole new array without side effects. Also, the return value is a concatenation of the previous array. Remember that Pure functions are important as they simplify unit testing without any side effects and no need for dependency injection. They also avoid tight coupling and make it harder to break your application by not having any side effects. These principles are coming together with the **Immutability** concept of ES6: giving preference to **const** over **let** usage.
-
What is the Temporal Dead Zone?
The Temporal Dead Zone is a behavior in JavaScript that occurs when declaring a variable with the let and const keywords, but not with var. In ECMAScript 6, accessing a
let
orconst
variable before its declaration (within its scope) causes a ReferenceError. The time span when that happens, between the creation of a variable’s binding and its declaration, is called the temporal dead zone.Let's see this behavior with an example,
function somemethod() { console.log(counter1); // undefined console.log(counter2); // ReferenceError var counter1 = 1; let counter2 = 2; }
-
What is an IIFE (Immediately Invoked Function Expression)?
IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The signature of it would be as below,
```javascript
(function () {
// logic here
})();
The primary reason to use an IIFE is to obtain data privacy because any variables declared within the IIFE cannot be accessed by the outside world. i.e, If you try to access variables from the IIFE then it throws an error as below,
(function () {
var message = "IIFE";
console.log(message);
})();
console.log(message); //Error: message is not defined
1. **What is memoization?**
Memoization is a functional programming technique which attempts to increase a function’s performance by caching its previously computed results. Each time a memoized function is called, its parameters are used to index the cache. If the data is present, then it can be returned, without executing the entire function. Otherwise the function is executed and then the result is added to the cache. Let's take an example of adding function with memoization,
```javascript
const memoizAddition = () => {
let cache = {};
return (value) => {
if (value in cache) {
console.log("Fetching from cache");
return cache[value]; // Here, cache.value cannot be used as property name starts with the number which is not a valid JavaScript identifier. Hence, can only be accessed using the square bracket notation.
} else {
console.log("Calculating result");
let result = value + 20;
cache[value] = result;
return result;
}
};
};
// returned function from memoizAddition
const addition = memoizAddition();
console.log(addition(20)); //output: 40 calculated
console.log(addition(20)); //output: 40 cached
- What is Hoisting?
Hoisting is a JavaScript mechanism where variables, function declarations and classes are moved to the top of their scope before code execution. Remember that JavaScript only hoists declarations, not initialisation.
Let's take a simple example of variable hoisting,
```javascript
console.log(message); //output : undefined
var message = "The variable Has been hoisted";
The above code looks like as below to the interpreter,
var message;
console.log(message);
message = "The variable Has been hoisted";
In the same fashion, function declarations are hoisted too
message("Good morning"); //Good morning
function message(name) {
console.log(name);
}
This hoisting makes functions to be safely used in code before they are declared.
- What are closures ?
A closure is the combination of a function and the lexical environment within which that function was declared. i.e, It is an inner function that has access to the outer or enclosing function’s variables. The closure has three scope chains
- Own scope where variables defined between its curly brackets
- Outer function’s variables
- Global variables
Let's take an example of closure concept,
function Welcome(name) {
var greetingInfo = function (message) {
console.log(message + " " + name);
};
return greetingInfo;
}
var myFunction = Welcome("John");
myFunction("Welcome "); //Output: Welcome John
myFunction("Hello Mr."); //output: Hello Mr.John
As per the above code, the inner function(i.e, greetingInfo) has access to the variables in the outer function scope(i.e, Welcome) even after the outer function has returned.
- What are classes in ES6?
In ES6, Javascript classes are primarily syntactic sugar over JavaScript’s existing prototype-based inheritance. For example, the prototype based inheritance written in function expression as below,
function Bike(model, color) {
this.model = model;
this.color = color;
}
Bike.prototype.getDetails = function () {
return this.model + " bike has" + this.color + " color";
};
Whereas ES6 classes can be defined as an alternative
class Bike {
constructor(color, model) {
this.color = color;
this.model = model;
}
getDetails() {
return this.model + " bike has" + this.color + " color";
}
}
- What are the differences between cookie, local storage and session storage?
Below are some of the differences between cookie, local storage and session storage,
Feature Cookie Local storage Session storage Accessed on client or server side Both server-side & client-side client-side only client-side only Lifetime As configured using Expires option until deleted until tab is closed SSL support Supported Not supported Not supported Maximum data size 4KB 5 MB 5MB
- What is a promise?
A promise is an object that may produce a single value some time in the future with either a resolved value or a reason that it’s not resolved(for example, network error). It will be in one of the 3 possible states: fulfilled, rejected, or pending.
The syntax of Promise creation looks like below,
const promise = new Promise(function (resolve, reject) {
// promise description
});
The usage of a promise would be as below,
const promise = new Promise(
(resolve) => {
setTimeout(() => {
resolve("I'm a Promise!");
}, 5000);
},
(reject) => {}
);
promise.then((value) => console.log(value));
The action flow of a promise will be as below,
- What are the three states of promise?
Promises have three states:
-
Pending: This is an initial state of the Promise before an operation begins
-
Fulfilled: This state indicates that the specified operation was completed.
-
Rejected: This state indicates that the operation did not complete. In this case an error value will be thrown.
-
What is a callback function
A callback function is a function passed into another function as an argument. This function is invoked inside the outer function to complete an action. Let's take a simple example of how to use callback function
function callbackFunction(name) { console.log("Hello " + name); } function outerFunction(callback) { let name = prompt("Please enter your name."); callback(name); } outerFunction(callbackFunction);
- What is a callback hell ?
Callback Hell is an anti-pattern with multiple nested callbacks which makes code hard to read and debug when dealing with asynchronous logic. The callback hell looks like below,
async1(function(){
async2(function(){
async3(function(){
async4(function(){
....
});
});
});
});
- What is same-origin policy?
The same-origin policy is a policy that prevents JavaScript from making requests across domain boundaries. An origin is defined as a combination of URI scheme, hostname, and port number. If you enable this policy then it prevents a malicious script on one page from obtaining access to sensitive data on another web page using Document Object Model(DOM).
- Why is JavaScript treated as Single threaded?
JavaScript is treated as single-threaded primarily because of its origins in web development. It was designed to run in browsers, which are single-threaded environments to ensure responsive user interfaces. While there are mechanisms for handling asynchronous tasks, the main execution thread remains single-threaded to avoid conflicts and simplify development.
Mastering JavaScript interview questions opens doors to exciting opportunities. These insights not only enhance your interview performance but deepen your grasp of JavaScript's intricacies. Armed with this knowledge, you're well-prepared to navigate the challenges of interviews and excel in your ongoing journey as a JavaScript developer. Keep coding, stay curious, and embrace the dynamic world of JavaScript. Best of luck in all your endeavors!