A comprehensive list of JavaScript Interview questions & solutions with code examples:
1. What is a variable in JavaScript?
Explanation: A variable in JavaScript is used to store data values.
Solution:
let name = 'John';
const age = 30;
2. How do you declare a function in JavaScript?
Explanation: Functions are declared using the function
keyword.
Solution:
function greet() {
console.log('Hello, world!');
}
3. How do you call a function in JavaScript?
Explanation: You call a function by using its name followed by parentheses.
Solution:
greet(); // Calls the function 'greet'
4. What is a JavaScript object?
Explanation: An object is a collection of key-value pairs where keys are strings and values can be any data type.
Solution:
const person = {
name: 'John',
age: 30,
greet: function() {
console.log('Hello!');
}
};
5. How do you access a property of an object?
Explanation: You can access object properties using dot notation or bracket notation.
Solution:
console.log(person.name); // Using dot notation
console.log(person['age']); // Using bracket notation
6. How do you add a new property to an object?
Explanation: You can add new properties using dot notation or bracket notation.
Solution:
person.email = '[email protected]'; // Using dot notation
person['address'] = '123 Main St'; // Using bracket notation
7. How do you create an array in JavaScript?
Explanation: Arrays are created using square brackets.
Solution:
const fruits = ['apple', 'banana', 'cherry'];
8. How do you access an element in an array?
Explanation: Array elements are accessed using their index, starting from 0.
Solution:
console.log(fruits[0]); // Output: 'apple'
9. How do you add an element to an array?
Explanation: Use the push
method to add elements to the end of an array.
Solution:
fruits.push('orange');
10. How do you remove the last element from an array?
Explanation: Use the pop
method to remove the last element from an array.
Solution:
fruits.pop();
11. How do you iterate over an array in JavaScript?
Explanation: You can use a for
loop or forEach
method to iterate over an array.
Solution:
fruits.forEach(function(fruit) {
console.log(fruit);
});
12. What is a JavaScript function expression?
Explanation: A function expression is a way to define a function using a variable.
Solution:
const greet = function() {
console.log('Hello!');
};
13. What is an arrow function?
Explanation: An arrow function is a shorter syntax for writing functions.
Solution:
const greet = () => {
console.log('Hello!');
};
14. How do you handle errors in JavaScript?
Explanation: Use try...catch
blocks to handle errors.
Solution:
try {
let result = riskyFunction();
} catch (error) {
console.error(error);
}
15. What is the difference between let
, const
, and var
?
Explanation: let
and const
have block scope, while var
has function scope. const
cannot be reassigned.
Solution:
let x = 10;
const y = 20;
var z = 30;
x = 15; // Valid
// y = 25; // Error: Assignment to constant variable
16. What is a closure in JavaScript?
Explanation: A closure is a function that retains access to its lexical scope, even after the function has returned.
Solution:
function makeCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = makeCounter();
console.log(counter()); // Output: 1
console.log(counter()); // Output: 2
17. What is the this
keyword in JavaScript?
Explanation: The this
keyword refers to the object that is executing the current function.
Solution:
const person = {
name: 'John',
greet: function() {
console.log('Hello, ' + this.name);
}
};
person.greet(); // Output: 'Hello, John'
18. How do you define a class in JavaScript?
Explanation: Classes are defined using the class
keyword.
Solution:
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log('Hello, ' + this.name);
}
}
const john = new Person('John');
john.greet(); // Output: 'Hello, John'
19. How do you extend a class in JavaScript?
Explanation: Use the extends
keyword to create a subclass.
Solution:
class Employee extends Person {
constructor(name, job) {
super(name);
this.job = job;
}
work() {
console.log(this.name + ' is working as a ' + this.job);
}
}
const jane = new Employee('Jane', 'Developer');
jane.work(); // Output: 'Jane is working as a Developer'
20. What is the map
method in JavaScript arrays?
Explanation: The map
method creates a new array with the results of calling a function on every element of the array.
Solution:
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(x => x * 2);
console.log(doubled); // Output: [2, 4, 6, 8]
21. What is the filter
method in JavaScript arrays?
Explanation: The filter
method creates a new array with all elements that pass the test implemented by the provided function.
Solution:
const numbers = [1, 2, 3, 4];
const evenNumbers = numbers.filter(x => x % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
22. What is the reduce
method in JavaScript arrays?
Explanation: The reduce
method executes a reducer function on each element of the array, resulting in a single output value.
Solution:
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, current) => acc + current, 0);
console.log(sum); // Output: 10
23. How do you create an asynchronous function in JavaScript?
Explanation: Use the async
keyword before a function to make it asynchronous.
Solution:
async function fetchData() {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
}
fetchData();
24. What is a promise in JavaScript?
Explanation: A promise represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
Solution:
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Data fetched'), 2000);
});
promise.then(data => console.log(data)); // Output: 'Data fetched'
25. How do you handle multiple promises in JavaScript?
Explanation: Use Promise.all
to handle multiple promises.
Solution:
const promise1 = Promise.resolve('First');
const promise2 = Promise.resolve('Second');
Promise.all([promise1, promise2])
.then(values => console.log(values)); // Output: ['First', 'Second']
26. How do you convert a JavaScript object to JSON?
Explanation: Use JSON.stringify
to convert an object to a JSON string.
Solution:
const person = { name: 'John', age: 30 };
const jsonString = JSON.stringify(person);
console.log(jsonString); // Output: '{"name":"John","age":30}'
27. How do you parse JSON into a JavaScript object?
Explanation: Use JSON.parse
to convert a JSON string into a JavaScript object.
Solution:
const jsonString = '{"name":"John","age":30}';
const person = JSON.parse(jsonString);
console.log(person.name); // Output: 'John'
28. What is event delegation in JavaScript?
Explanation: Event delegation is a technique where you attach a single event listener to a parent element instead of individual child elements.
Solution:
document.querySelector('#parent').addEventListener('click', function(event) {
if (event.target && event.target.matches('button')) {
console.log('Button clicked:', event.target.textContent);
}
});
29. How do you prevent a form from submitting in JavaScript?
Explanation: Use the preventDefault
method on the form submission event.
Solution:
document.querySelector('form').addEventListener('submit', function(event) {
event.preventDefault();
console.log('Form submission prevented');
});
30. How do you add an event listener to an element?
Explanation: Use the addEventListener
method to attach an event listener to an element.
Solution:
document.querySelector('button').addEventListener('click', () => {
console.log('Button clicked');
});
31. How do you remove an event listener from an element?
Explanation: Use the removeEventListener
method to remove an event listener.
Solution:
const handleClick = () => console.log('Button clicked');
const button = document.querySelector('button');
button.addEventListener('click', handleClick);
button.removeEventListener('click', handleClick);
32. What is the difference between ==
and ===
in JavaScript?
Explanation: ==
performs type coercion, while ===
checks for equality without type conversion.
Solution:
console.log(5 == '5'); // Output: true
console.log(5 === '5'); // Output: false
33. How do you check if a variable is an array in JavaScript?
Explanation: Use the Array.isArray
method to check if a variable is an array.
Solution:
const fruits = ['apple', 'banana'];
console.log(Array.isArray(fruits)); // Output: true
34. How do you find the length of a string in JavaScript?
Explanation: Use the length
property to get the length of a string.
Solution:
const str = 'Hello, world!';
console.log(str.length); // Output: 13
35. How do you convert a string to a number in JavaScript?
Explanation: Use parseInt
or parseFloat
to convert a string to an integer or floating-point number, respectively.
Solution:
const str = '123';
const num = parseInt(str);
console.log(num); // Output: 123
36. How do you check if a number is an integer in JavaScript?
Explanation: Use the Number.isInteger
method to check if a number is an integer.
Solution:
console.log(Number.isInteger(123)); // Output: true
console.log(Number.isInteger(123.45)); // Output: false
37. How do you round a number to the nearest integer in JavaScript?
Explanation: Use the Math.round
method to round a number to the nearest integer.
Solution:
const num = 5.67;
console.log(Math.round(num)); // Output: 6
38. How do you generate a random number in JavaScript?
Explanation: Use Math.random
to generate a random number between 0 and 1.
Solution:
const randomNumber = Math.random();
console.log(randomNumber); // Output: Random number between 0 and 1
39. How do you get the current date and time in JavaScript?
Explanation: Use the Date
object to get the current date and time.
Solution:
const now = new Date();
console.log(now); // Output: Current date and time
40. How do you format a date in JavaScript?
Explanation: Use Date
methods to format a date.
Solution:
const now = new Date();
console.log(now.toDateString()); // Output: 'Mon Sep 10 2024'
41. How do you set a timeout in JavaScript?
Explanation: Use setTimeout
to execute a function after a delay.
Solution:
setTimeout(() => {
console.log('Executed after 2 seconds');
}, 2000);
42. How do you clear a timeout in JavaScript?
Explanation: Use clearTimeout
to cancel a timeout.
Solution:
const timeoutId = setTimeout(() => {
console.log('This will not be executed');
}, 2000);
clearTimeout(timeoutId);
43. How do you create a promise that resolves immediately in JavaScript?
Explanation: Use Promise.resolve
to create a promise that resolves immediately.
Solution:
const promise = Promise.resolve('Immediate resolution');
promise.then(value => console.log(value)); // Output: 'Immediate resolution'
44. How do you create a promise that rejects immediately in JavaScript?
Explanation: Use Promise.reject
to create a promise that rejects immediately.
Solution:
const promise = Promise.reject('Immediate rejection');
promise.catch(reason => console.log(reason)); // Output: 'Immediate rejection'
45. How do you chain multiple .then
calls on a promise?
Explanation: You can chain multiple .then
calls to handle sequential asynchronous operations.
Solution:
const promise = Promise.resolve(5);
promise
.then(value => value * 2)
.then(value => value + 1)
.then(result => console.log(result)); // Output: 11
46. How do you handle promise rejections with .catch
?
Explanation: Use .catch
to handle errors in a promise chain.
Solution:
const promise = Promise.reject('Error occurred');
promise
.catch(error => console.log(error)); // Output: 'Error occurred'
47. How do you make an HTTP request in JavaScript?
Explanation: Use the fetch
API to make HTTP requests.
Solution:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
48. How do you create a new DOM element using JavaScript?
Explanation: Use document.createElement
to create a new DOM element.
Solution:
const newDiv = document.createElement('div');
newDiv.textContent = 'Hello, world!';
document.body.appendChild(newDiv);
49. How do you add a class to an HTML element?
Explanation: Use the classList.add
method to add a class.
Solution:
const element = document.querySelector('div');
element.classList.add('new-class');
50. How do you remove a class from an HTML element?
Explanation: Use the classList.remove
method to remove a class.
Solution:
const element = document.querySelector('div');
element.classList.remove('old-class');
51. How do you toggle a class on an HTML element?
Explanation: Use the classList.toggle
method to add or remove a class.
Solution:
const element = document.querySelector('div');
element.classList.toggle('active');
52. How do you get the value of an input field in JavaScript?
Explanation: Use the value
property to get the value of an input field.
Solution:
const input = document.querySelector('input');
console.log(input.value);
53. How do you set the value of an input field in JavaScript?
Explanation: Use the value
property to set the value of an input field.
Solution:
const input = document.querySelector('input');
input.value = 'New value';
54. How do you listen for changes in an input field?
Explanation: Use the input
event to listen for changes in an input field.
Solution:
const input = document.querySelector('input');
input.addEventListener('input', () => {
console.log('Input changed');
});
55. How do you prevent the default action of an event?
Explanation: Use event.preventDefault
to prevent the default action.
Solution:
document.querySelector('form').addEventListener('submit', event => {
event.preventDefault();
console.log('Form submission prevented');
});
56. How do you check if a string contains a substring in JavaScript?
Explanation: Use the includes
method to check if a string contains a substring.
Solution:
const str = 'Hello, world!';
console.log(str.includes('world')); // Output: true
57. How do you replace a substring in a string in JavaScript?
Explanation: Use the replace
method to replace a substring.
Solution:
const str = 'Hello, world!';
const newStr = str.replace('world', 'everyone');
console.log(newStr); // Output: 'Hello, everyone!'
58. How do you split a string into an array in JavaScript?
Explanation: Use the split
method to split a string into an array.
Solution:
const str = 'apple,banana,cherry';
const arr = str.split(',');
console.log(arr); // Output: ['apple', 'banana', 'cherry']
59. How do you join an array into a string in JavaScript?
Explanation: Use the join
method to join an array into a string.
Solution:
const arr = ['apple', 'banana', 'cherry'];
const str = arr.join(',');
console.log(str); // Output: 'apple,banana,cherry'
60. How do you check if a number is NaN in JavaScript?
Explanation: Use Number.isNaN
to check if a value is NaN.
Solution:
console.log(Number.isNaN(NaN)); // Output: true
console.log(Number.isNaN(123)); // Output: false
61. How do you convert a number to a string in JavaScript?
Explanation: Use the toString
method or template literals to convert a number to a string.
Solution:
const num = 123;
const str = num.toString();
console.log(str); // Output: '123'
const str2 = `${num}`;
console.log(str2); // Output: '123'
62. How do you remove whitespace from the beginning and end of a string?
Explanation: Use the trim
method to remove whitespace from both ends of a string.
Solution:
const str = ' Hello, world! ';
const trimmed = str.trim();
console.log(trimmed); // Output: 'Hello, world!'
63. How do you get the character at a specific index in a string?
Explanation: Use the charAt
method to get the character at a specific index.
Solution:
const str = 'Hello';
console.log(str.charAt(1)); // Output: 'e'
64. How do you get the index of a substring in a string?
Explanation: Use the indexOf
method to get the index of a substring.
Solution:
const str = 'Hello, world!';
console.log(str.indexOf('world')); // Output: 7
65. How do you sort an array in JavaScript?
Explanation: Use the sort
method to sort an array.
Solution:
const arr = [3, 1, 4, 1, 5, 9];
arr.sort((a, b) => a - b);
console.log(arr); // Output: [1, 1, 3, 4, 5, 9]
66. How do you reverse an array in JavaScript?
Explanation: Use the reverse
method to reverse the order of an array.
Solution:
const arr = [1, 2, 3];
arr.reverse();
console.log(arr); // Output: [3, 2, 1]
67. How do you find the maximum value in an array?
Explanation: Use Math.max
with the spread operator to find the maximum value in an array.
Solution:
const numbers = [1, 2, 3, 4];
const max = Math.max(...numbers);
console.log(max); // Output: 4
68. How do you find the minimum value in an array?
Explanation: Use Math.min
with the spread operator to find the minimum value in an array.
Solution:
const numbers = [1, 2, 3, 4];
const min = Math.min(...numbers);
console.log(min); // Output: 1
69. How do you concatenate two arrays in JavaScript?
Explanation: Use the concat
method to concatenate two arrays.
Solution:
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = arr1.concat(arr2);
console.log(combined); // Output: [1, 2, 3, 4]
70. How do you check if an array contains a specific element?
Explanation: Use the includes
method to check if an array contains an element.
Solution:
const arr = [1, 2, 3];
console.log(arr.includes(2)); // Output: true
71. How do you find the index of an element in an array?
Explanation: Use the indexOf
method to find the index of an element.
Solution:
const arr = [1, 2, 3];
console.log(arr.indexOf(2)); // Output: 1
72. How do you remove duplicates from an array?
Explanation: Use a Set
to remove duplicates from an array.
Solution:
const arr = [1, 2, 2, 3, 4, 4];
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // Output: [1, 2, 3, 4]
73. How do you convert an array to a string with a separator?
Explanation: Use the join
method to convert an array to a string with a separator.
Solution:
const arr = ['apple', 'banana', 'cherry'];
const str = arr.join(', ');
console.log(str); // Output: 'apple, banana, cherry'
74. How do you create a new array from a subset of an existing array?
Explanation: Use the slice
method to create a new array from a subset.
Solution:
const arr = [1, 2, 3, 4, 5];
const subset = arr.slice(1, 4);
console.log(subset); // Output: [2, 3, 4]
75. How do you execute code after a certain delay in JavaScript?
Explanation: Use setTimeout
to execute code after a delay.
Solution:
setTimeout(() => {
console.log('Executed after 2 seconds');
}, 2000);
76. How do you repeatedly execute code at regular intervals?
Explanation: Use setInterval
to repeatedly execute code at regular intervals.
Solution:
const intervalId = setInterval(() => {
console.log('Executed every 2 seconds');
}, 2000);
// To stop the interval:
clearInterval(intervalId);
77. How do you check if a variable is an object in JavaScript?
Explanation: Use typeof
and additional checks to verify if a variable is an object.
Solution:
const obj = {};
console.log(typeof obj === 'object' && obj !== null); // Output: true
78. How do you check if a variable is a function in JavaScript?
Explanation: Use typeof
to check if a variable is a function.
Solution:
const func = () => {};
console.log(typeof func === 'function'); // Output: true
79. How do you create a new object with a prototype in JavaScript?
Explanation: Use Object.create
to create a new object with a specific prototype.
Solution:
const proto = { greet: function() { console.log('Hello'); } };
const obj = Object.create(proto);
obj.greet(); // Output: 'Hello'
80. How do you get the keys of an object in JavaScript?
Explanation: Use Object.keys
to get an array of an object’s keys.
Solution:
const obj = { name: 'John', age: 30 };
console.log(Object.keys(obj)); // Output: ['name', 'age']
81. How do you get the values of an object in JavaScript?
Explanation: Use Object.values
to get an array of an object’s values.
Solution:
const obj = { name: 'John', age: 30 };
console.log(Object.values(obj)); // Output: ['John', 30]
82. How do you check if an object has a specific property?
Explanation: Use Object.prototype.hasOwnProperty
to check if an object has a specific property.
Solution:
const obj = { name: 'John' };
console.log(obj.hasOwnProperty('name')); // Output: true
83. How do you create a new array from the values of an object?
Explanation: Use Object.values
to create a new array from an object’s values.
Solution:
const obj = { name: 'John', age: 30 };
const values = Object.values(obj);
console.log(values); // Output: ['John', 30]
84. How do you create a new object from an array of key-value pairs?
Explanation: Use Object.fromEntries
to create
an object from an array of key-value pairs.
Solution:
const entries = [['name', 'John'], ['age', 30]];
const obj = Object.fromEntries(entries);
console.log(obj); // Output: { name: 'John', age: 30 }
85. How do you find the index of an element in an array of objects?
Explanation: Use the findIndex
method to find the index of an element in an array of objects.
Solution:
const arr = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
const index = arr.findIndex(obj => obj.id === 2);
console.log(index); // Output: 1
86. How do you filter an array based on a condition?
Explanation: Use the filter
method to create a new array with elements that meet a condition.
Solution:
const arr = [1, 2, 3, 4, 5];
const filtered = arr.filter(num => num > 2);
console.log(filtered); // Output: [3, 4, 5]
87. How do you map an array to a new array?
Explanation: Use the map
method to create a new array by applying a function to each element.
Solution:
const arr = [1, 2, 3];
const doubled = arr.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6]
88. How do you reduce an array to a single value?
Explanation: Use the reduce
method to reduce an array to a single value by applying a function.
Solution:
const arr = [1, 2, 3];
const sum = arr.reduce((total, num) => total + num, 0);
console.log(sum); // Output: 6
89. How do you find the first element in an array that meets a condition?
Explanation: Use the find
method to get the first element that meets a condition.
Solution:
const arr = [1, 2, 3, 4];
const firstEven = arr.find(num => num % 2 === 0);
console.log(firstEven); // Output: 2
90. How do you remove an element from an array by index?
Explanation: Use the splice
method to remove an element from an array by index.
Solution:
const arr = [1, 2, 3];
arr.splice(1, 1);
console.log(arr); // Output: [1, 3]
91. How do you check if a value is an array in JavaScript?
Explanation: Use Array.isArray
to check if a value is an array.
Solution:
const arr = [1, 2, 3];
console.log(Array.isArray(arr)); // Output: true
92. How do you create a copy of an array in JavaScript?
Explanation: Use the spread operator or slice
method to create a copy of an array.
Solution:
const arr = [1, 2, 3];
const copy = [...arr];
console.log(copy); // Output: [1, 2, 3]
// or
const copy2 = arr.slice();
console.log(copy2); // Output: [1, 2, 3]
93. How do you check if a string starts with a specific substring?
Explanation: Use the startsWith
method to check if a string starts with a specific substring.
Solution:
const str = 'Hello, world!';
console.log(str.startsWith('Hello')); // Output: true
94. How do you check if a string ends with a specific substring?
Explanation: Use the endsWith
method to check if a string ends with a specific substring.
Solution:
const str = 'Hello, world!';
console.log(str.endsWith('world!')); // Output: true
95. How do you convert a string to lowercase?
Explanation: Use the toLowerCase
method to convert a string to lowercase.
Solution:
const str = 'Hello, WORLD!';
const lowerStr = str.toLowerCase();
console.log(lowerStr); // Output: 'hello, world!'
96. How do you convert a string to uppercase?
Explanation: Use the toUpperCase
method to convert a string to uppercase.
Solution:
const str = 'Hello, world!';
const upperStr = str.toUpperCase();
console.log(upperStr); // Output: 'HELLO, WORLD!'
97. How do you find the length of an array in JavaScript?
Explanation: Use the length
property to get the length of an array.
Solution:
const arr = [1, 2, 3];
console.log(arr.length); // Output: 3
98. How do you create a new array from an existing array with modified elements?
Explanation: Use the map
method to create a new array with modified elements.
Solution:
const arr = [1, 2, 3];
const modified = arr.map(num => num * 2);
console.log(modified); // Output: [2, 4, 6]
99. How do you check if an array is empty?
Explanation: Check if the length
property of the array is zero.
Solution:
const arr = [];
console.log(arr.length === 0); // Output: true
100. How do you find the sum of all elements in an array?
Explanation: Use the reduce
method to find the sum of all elements in an array.
Solution:
const arr = [1, 2, 3, 4];
const sum = arr.reduce((total, num) => total + num, 0);
console.log(sum); // Output: 10
These questions and answers cover a broad range of fundamental JavaScript concepts.