Here are some JavaScript interview questions with concise answers which is asking frequently::
1. What is JavaScript?
- JavaScript is a high-level, interpreted scripting language primarily used for adding interactivity and behavior to web pages.
2. What are the data types in JavaScript?
- JavaScript has six primitive data types:
number
,string
,boolean
,null
,undefined
, andsymbol
(added in ES6). It also has one complex data type:object
.
3. How do you declare a variable in JavaScript?
- Variables are declared using
var
,let
, orconst
followed by a variable name. Example:let x;
4. What’s the difference between let
, const
, and var
in variable declaration?
let
andconst
are block-scoped and cannot be redeclared in the same scope, whilevar
is function-scoped and can be redeclared.
5. What are template literals, and how are they used?
- Template literals are string literals allowing embedded expressions. They are enclosed in backticks (`) and allow interpolation of variables and expressions.
6. Explain hoisting in JavaScript.
- Hoisting is the behavior where variable and function declarations are moved to the top of their containing scope during compilation. Variables declared with
let
andconst
are also hoisted but not initialized.
7. What is the difference between null
and undefined
?
null
is an explicitly assigned value representing the absence of an object, whileundefined
is a default value assigned to variables that have not been initialized.
8. How do you check the type of a variable in JavaScript?
- You can use the
typeof
operator. Example:typeof x;
9. What are JavaScript closures?
- Closures are functions that have access to their outer (enclosing) function’s variables. They “remember” the environment in which they were created.
10. What is a callback function in JavaScript?
– A callback function is a function passed as an argument to another function, which is executed after the completion of an asynchronous operation or at a specified time.
11. Explain the difference between ==
and ===
in JavaScript.
– ==
is used for loose equality comparison and converts operands to the same type before comparing. ===
is used for strict equality comparison and checks both value and type.
12. How can you iterate over object properties in JavaScript?
– You can use a for...in
loop or the Object.keys()
, Object.values()
, or Object.entries()
methods.
13. What is the “prototype” in JavaScript?
– The “prototype” is an object from which other objects inherit properties and methods. It’s used for inheritance in JavaScript.
14. Explain the purpose of the this
keyword in JavaScript.
– this
refers to the current execution context, which depends on how a function is called. In the global context, it refers to the global object (e.g., window
in a browser).
15. What is a JavaScript promise?
– A promise is an object representing the eventual completion or failure of an asynchronous operation. It has methods like then()
and catch()
to handle results or errors.
16. What are arrow functions in JavaScript?
– Arrow functions provide a more concise syntax for defining functions. They have a shorter syntax and automatically bind to the surrounding context for this
.
17. What is the event loop in JavaScript?
– The event loop is a mechanism that allows non-blocking, asynchronous execution of code. It handles I/O operations, callbacks, and events.
18. How can you prevent the default behavior of an HTML form submission?
– You can use the event.preventDefault()
method within an event handler to prevent the default behavior of form submission.
19. What is the purpose of the addEventListener
method in JavaScript?
– addEventListener
is used to attach event handlers to HTML elements, enabling them to respond to events such as clicks or keypresses.
20. Explain the concept of closures with an example.
– Closures allow functions to “remember” their outer scope’s variables even after the outer function has finished executing. Example:js function outer() { let x = 10; return function inner() { console.log(x); }; } const closureFn = outer(); closureFn(); // Output: 10
21. How can you create a new object in JavaScript?
– You can create a new object using object literal notation ({}
), the Object
constructor (new Object()
), or by using a constructor function.
22. What is the “async/await” feature in JavaScript, and how does it work?
– async/await
is a feature for handling asynchronous code more synchronously. The async
keyword is used to declare an asynchronous function, and await
is used inside the function to wait for a Promise to resolve before proceeding.
23. What is the difference between null
and undefined
in JavaScript?
– null
is an explicitly assigned value representing the absence of an object, while undefined
is a default value assigned to variables that have not been initialized or properties that do not exist.
**24. What is the “
prototype chain” in JavaScript, and how does it work?**
– The prototype chain is a mechanism for object inheritance in JavaScript. Objects inherit properties and methods from their prototype object, and this chain continues up to the Object.prototype
at the top.
25. What is destructuring in JavaScript?
– Destructuring allows you to extract values from objects and arrays into variables using a concise syntax. Example: const { name, age } = person;
26. What is the spread/rest operator in JavaScript, and how is it used?
– The spread (...
) operator is used to spread elements of an iterable (e.g., an array) into another array, object, or function argument list. The rest operator is used in function parameters to collect arguments into an array.
27. Explain the concept of promises with a practical example.
– Promises are used for handling asynchronous operations. Example using fetch
:js fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
28. How can you clone an object in JavaScript?
– You can clone an object using the spread operator ({...}
), Object.assign()
, or by creating a new object and copying properties manually.
29. What is the difference between the nullish coalescing operator (??)
and the logical OR operator (||)
in JavaScript?
– The nullish coalescing operator (??
) returns the right-hand operand when the left-hand operand is null
or undefined
. The logical OR operator (||
) returns the right-hand operand when the left-hand operand is falsy (including null
, undefined
, 0
, false
, and ''
).
30. What is a JavaScript callback function, and when would you use it?
– A callback function is a function passed as an argument to another function and is executed after the completion of an asynchronous operation or at a specified time. Callbacks are used for handling asynchronous code, such as reading files or making HTTP requests.
31. How do you add an element to the beginning and end of an array in JavaScript?
– You can use the unshift()
method to add an element to the beginning and the push()
method to add an element to the end of an array.
32. What is the difference between localStorage
and sessionStorage
in JavaScript?
– Both localStorage
and sessionStorage
are used to store data in the browser, but localStorage
persists data until explicitly cleared, while sessionStorage
is cleared when the session ends (e.g., when the browser is closed).
33. Explain the concept of event delegation in JavaScript.
– Event delegation is a technique where a single event listener is attached to a common ancestor of multiple elements. This allows handling events for all descendant elements efficiently.
34. How can you convert a string to a number in JavaScript?
– You can use parseInt()
, parseFloat()
, or the unary plus operator (+
) to convert a string to a number.
35. What is a JavaScript closure, and why is it useful?
– A closure is a function that has access to its outer (enclosing) function’s variables. Closures are useful for maintaining data privacy, creating private variables, and implementing module patterns.
36. How do you reverse an array in JavaScript?
– You can use the reverse()
method to reverse the elements of an array in place.
37. Explain the event loop in JavaScript and how it works.
– The event loop is a core concept in JavaScript that manages the execution of code, handling asynchronous tasks, and events. It continuously checks the call stack, message queue, and callback queue to execute tasks.
38. How can you prevent event propagation in JavaScript?
– You can use event.stopPropagation()
to stop the propagation of an event through the DOM tree. This prevents parent elements from receiving the event.
39. What are the differences between null
and undefined
in JavaScript?
– null
is an explicitly assigned value representing the absence of an object, while undefined
is a default value assigned to variables that have not been initialized or properties that do not exist.
40. How do you deep-clone an object in JavaScript?
– Deep cloning an object can be achieved using libraries like Lodash, the JSON.parse(JSON.stringify(obj))
method, or recursive custom functions.
41. Explain the concept of memoization in JavaScript.
– Memoization is a technique used to optimize function performance by caching the results of expensive function calls based on their inputs. This avoids recomputation for the same inputs.
42. What is a higher-order function in JavaScript?
– A higher-order function is a function that takes one or more functions as arguments or returns a function as its result. Common examples are map()
, filter()
, and reduce()
.
43. How do you compare two objects for equality in JavaScript?
– Comparing objects for equality in JavaScript can be tricky. You can use deep comparison techniques or libraries like Lodash’s isEqual()
.
44. What is the purpose of the arguments
object in JavaScript?
– The arguments
object is an array-like object available within a function that contains all the arguments passed to the function, regardless of the number of parameters defined.
45. How can you remove duplicates from an array in JavaScript?
– You can remove duplicates from an array using the Set
object, the filter()
method, or by iterating and creating a new array.
46. Explain the “this” keyword in JavaScript and how its value is determined.
– this
refers to the current execution context, which depends on how a function is called. It can refer to the global object (window
in a browser), an object to which a method belongs, or explicitly bound using functions like call()
or apply()
.
47. What is the difference between a shallow copy and a deep copy of an object in JavaScript?
– A shallow copy of an object copies the top-level properties and references nested objects. A deep copy copies all properties and recursively creates new objects and arrays for nested objects.
48. How do you create a new array by filtering elements from an existing array in JavaScript?
– You can use the filter()
method to create a new array with elements that satisfy a given condition.
49. Explain the “prototype chain” in JavaScript and how it facilitates inheritance.
– The prototype chain is a mechanism in JavaScript where objects inherit properties and methods from their prototype object. This allows for a form of inheritance, where objects can access properties and methods defined in their prototype chain.
50. What is the purpose of the “async/await” syntax in JavaScript, and how does it work?
– async/await
is used to write asynchronous code in a more synchronous style. The async
keyword is used to declare an asynchronous function, and await
is used within the function to pause execution until a Promise is resolved. This makes asynchronous code easier to read and maintain.
**51. How can you create
a new object in JavaScript?**
– You can create a new object using object literal notation ({}
), the Object
constructor (new Object()
), or by using a constructor function.
52. What is the “async/await” feature in JavaScript, and how does it work?
– async/await
is a feature for handling asynchronous code more synchronously. The async
keyword is used to declare an asynchronous function, and await
is used inside the function to wait for a Promise to resolve before proceeding.
53. What is the difference between null
and undefined
in JavaScript?
– null
is an explicitly assigned value representing the absence of an object, while undefined
is a default value assigned to variables that have not been initialized or properties that do not exist.
54. What is the “prototype chain” in JavaScript, and how does it work?
– The prototype chain is a mechanism for object inheritance in JavaScript. Objects inherit properties and methods from their prototype object, and this chain continues up to the Object.prototype
at the top.
55. What is destructuring in JavaScript?
– Destructuring allows you to extract values from objects and arrays into variables using a concise syntax. Example: const { name, age } = person;
56. What is the spread/rest operator in JavaScript, and how is it used?
– The spread (...
) operator is used to spread elements of an iterable (e.g., an array) into another array, object, or function argument list. The rest operator is used in function parameters to collect arguments into an array.
57. Explain the concept of promises with a practical example.
– Promises are used for handling asynchronous operations. Example using fetch
:js fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
58. How can you clone an object in JavaScript?
– You can clone an object using the spread operator ({...}
), Object.assign()
, or by creating a new object and copying properties manually.
59. What is the difference between the nullish coalescing operator (??)
and the logical OR operator (||)
in JavaScript?
– The nullish coalescing operator (??
) returns the right-hand operand when the left-hand operand is null
or undefined
. The logical OR operator (||
) returns the right-hand operand when the left-hand operand is falsy (including null
, undefined
, 0
, false
, and ''
).
60. What is a JavaScript callback function, and when would you use it?
– A callback function is a function passed as an argument to another function and is executed after the completion of an asynchronous operation or at a specified time. Callbacks are used for handling asynchronous code, such as reading files or making HTTP requests.
61. How do you add an element to the beginning and end of an array in JavaScript?
– You can use the unshift()
method to add an element to the beginning and the push()
method to add an element to the end of an array.
62. What is the difference between localStorage
and sessionStorage
in JavaScript?
– Both localStorage
and sessionStorage
are used to store data in the browser, but localStorage
persists data until explicitly cleared, while sessionStorage
is cleared when the session ends (e.g., when the browser is closed).
63. Explain the concept of event delegation in JavaScript.
– Event delegation is a technique where a single event listener is attached to a common ancestor of multiple elements. This allows handling events for all descendant elements efficiently.
64. How can you convert a string to a number in JavaScript?
– You can use parseInt()
, parseFloat()
, or the unary plus operator (+
) to convert a string to a number.
65. What is a JavaScript closure, and why is it useful?
– A closure is a function that has access to its outer (enclosing) function’s variables. Closures are useful for maintaining data privacy, creating private variables, and implementing module patterns.
66. How do you reverse an array in JavaScript?
– You can use the reverse()
method to reverse the elements of an array in place.
67. Explain the event loop in JavaScript and how it works.
– The event loop is a core concept in JavaScript that manages the execution of code, handling asynchronous tasks, and events. It continuously checks the call stack, message queue, and callback queue to execute tasks.
68. How can you prevent event propagation in JavaScript?
– You can use event.stopPropagation()
to stop the propagation of an event through the DOM tree. This prevents parent elements from receiving the event.
69. What are the differences between null
and undefined
in JavaScript?
– null
is an explicitly assigned value representing the absence of an object, while undefined
is a default value assigned to variables that have not been initialized or properties that do not exist.
70. How do you deep-clone an object in JavaScript?
– Deep cloning an object can be achieved using libraries like Lodash, the JSON.parse(JSON.stringify(obj))
method, or recursive custom functions.
71. Explain the concept of memoization in JavaScript.
– Memoization is a technique used to optimize function performance by caching the results of expensive function calls based on their inputs. This avoids recomputation for the same inputs.
72. What is a higher-order function in JavaScript?
– A higher-order function is a function that takes one or more functions as arguments or returns a function as its result. Common examples are map()
, filter()
, and reduce()
.
73. How do you compare two objects for equality in JavaScript?
– Comparing objects for equality in JavaScript can be tricky. You can use deep comparison techniques or libraries like Lodash’s isEqual()
.
74. What is the purpose of the arguments
object in JavaScript?
– The arguments
object is an array-like object available within a function that contains all the arguments passed to the function, regardless of the number of parameters defined.
75. How can you remove duplicates from an array in JavaScript?
– You can remove duplicates from an array using the Set
object, the filter()
method, or by iterating and creating a new array.
76. Explain the “this” keyword in JavaScript and how its value is determined.
– this
refers to the current execution context, which depends on how a function is called. It can refer to the global object (window
in a browser), an object to which a method belongs, or explicitly bound using functions like call()
or apply()
.
77. What is the difference between a shallow copy and a deep copy of an object in JavaScript?
– A shallow copy of an object copies the top-level properties and references nested objects. A deep copy copies all properties and recursively creates new objects and arrays for nested objects.
78. How do you create a new array by filtering elements from an existing array in JavaScript?
- You can use the `filter()` method to create a new array with elements that satisfy a given condition.
79. Explain the “prototype chain” in JavaScript and how it facilitates inheritance.
– The prototype chain is a mechanism in JavaScript where objects inherit properties and methods from their prototype object. This allows for a form of inheritance, where objects can access properties and methods defined in their prototype chain.
80. What is the purpose of the “async/await” syntax in JavaScript, and how does it work?
– async/await
is used to write asynchronous code in a more synchronous style. The async
keyword is used to declare an asynchronous function, and await
is used within the function to pause execution until a Promise is resolved. This makes asynchronous code easier to read and maintain.
81. How can you create a new object in JavaScript?
– You can create a new object using object literal notation ({}
), the Object
constructor (new Object()
), or by using a constructor function.
82. What is the “async/await” feature in JavaScript, and how does it work?
– async/await
is a feature for handling asynchronous code more synchronously. The async
keyword is used to declare an asynchronous function, and await
is used inside the function to wait for a Promise to resolve before proceeding.
83. What is the difference between null
and undefined
in JavaScript?
– null
is an explicitly assigned value representing the absence of an object, while undefined
is a default value assigned to variables that have not been initialized or properties that do not exist.
84. What is the “prototype chain” in JavaScript, and how does it work?
– The prototype chain is a mechanism for object inheritance in JavaScript. Objects inherit properties and methods from their prototype object, and this chain continues up to the Object.prototype
at the top.
85. What is destructuring in JavaScript?
– Destructuring allows you to extract values from objects and arrays into variables using a concise syntax. Example: const { name, age } = person;
86. What is the spread/rest operator in JavaScript, and how is it used?
– The spread (...
) operator is used to spread elements of an iterable (e.g., an array) into another array, object, or function argument list. The rest operator is used in function parameters to collect arguments into an array.
87. Explain the concept of promises with a practical example.
– Promises are used for handling asynchronous operations. Example using fetch
:js fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
88. How can you clone an object in JavaScript?
– You can clone an object using the spread operator ({...}
), Object.assign()
, or by creating a new object and copying properties manually.
89. What is the difference between the nullish coalescing operator (??)
and the logical OR operator (||)
in JavaScript?
– The nullish coalescing operator (??
) returns the right-hand operand when the left-hand operand is null
or undefined
. The logical OR operator (||
) returns the right-hand operand when the left-hand operand is falsy (including null
, undefined
, 0
, false
, and ''
).
90. What is a JavaScript callback function, and when would you use it?
– A callback function is a function passed as an argument to another function and is executed after the completion of an asynchronous operation or at a specified time. Callbacks are used for handling asynchronous code, such as reading files or making HTTP requests.
91. How do you add an element to the beginning and end of an array in JavaScript?
– You can use the unshift()
method to add an element to the beginning and the push()
method to add an element to the end of an array.
92. What is the difference between localStorage
and sessionStorage
in JavaScript?
– Both localStorage
and sessionStorage
are used to store data in the browser, but localStorage
persists data until explicitly cleared, while sessionStorage
is cleared when the session ends (e.g., when the browser is closed).
93. Explain the concept of event delegation in JavaScript.
– Event delegation is a technique where a single event listener is attached to a common ancestor of multiple elements. This allows handling events for all descendant elements efficiently.
94. How can you convert a string to a number in JavaScript?
– You can use parseInt()
, parseFloat()
, or the unary plus operator (+
) to convert a string to a number.
95. What is a JavaScript closure, and why is it useful?
– A closure is a function that has access to its outer (enclosing) function’s variables. Closures are useful for maintaining data privacy, creating private variables, and implementing module patterns.
96. How do you reverse an array in JavaScript?
– You can use the reverse()
method to reverse the elements of an array in place.
97. Explain the event loop in JavaScript and how it works.
– The event loop is a core concept in JavaScript that manages the execution of code, handling asynchronous tasks, and events. It continuously checks the call stack, message queue, and callback queue to execute tasks.
98. How can you prevent event propagation in JavaScript?
– You can use event.stopPropagation()
to stop the propagation of an event through the DOM tree. This prevents parent elements from receiving the event.
99. What are the differences between null
and undefined
in JavaScript?
– null
is an explicitly assigned value representing the absence of an object, while undefined
is a default value assigned to variables that have not been initialized or properties that do not exist.
100. How do you deep-clone an object in JavaScript?
– Deep cloning an object can be achieved using libraries like Lodash, the JSON.parse(JSON.stringify(obj))
method, or recursive custom functions.
Some Confusing Programs
console.log(1 + + "2"+"2") // resulting in `"32"`
1. `"2"` is a string.
2. The unary `+` operator before `"2"` tries to convert it into a number. Since `"2"` can be successfully converted to a number, it becomes `2`.
3. `1 + 2` results in the number `3`.
----------------------------------------
----------------------------------------
console.log(typeof typeof 1); //string
----------------------------------------
----------------------------------------
console.log(typeof(NaN)); //number
----------------------------------------
----------------------------------------
const test = ({ a, b, c }) => {
console.log(a, b, c);
};
test(0, 1, 2);
//output : undefined undefined undefined
----------------------------------------
----------------------------------------
function test(...args) {
console.log(typeof args);
}
test(12); //object
----------------------------------------
----------------------------------------
var myObject = {
name: "Robert",
test: function() {
var self = this;
console.log("outer log 1 "+this.name); //outer log 1 Robert
console.log("outer log 2 "+self.name); //outer log 2 Robert
(function() {
console.log("inner log 1 "+this.name); //undefined
console.log("inner log 2 "+self.name); //Robert
}());
}
};
myObject.test();
----------------------------------------
----------------------------------------
function job() {
return new Promise(function(resolve, reject) {
reject();
});
}
let promise = job();
promise
.then(function() {
console.log('Success 1');
})
.then(function() {
console.log('Success 2');
})
.then(function() {
console.log('Success 3');
})
.catch(function() {
console.log('Error 1');
})
.then(function() {
console.log('Success 4');
});
// Error 1
// Success 4
----------------------------------------
----------------------------------------