Javascript Top Interview Questions:
Basic Questions
- What is JavaScript?
- Answer: JavaScript is a high-level, dynamic, untyped, and interpreted programming language that is widely used for web development to create interactive and dynamic web pages.
- How do you declare a variable in JavaScript?
- Answer: You can declare a variable using
var
,let
, orconst
keywords. Example:var name = 'John';
let age = 30;
const isStudent = true;
- Answer: You can declare a variable using
- What are the differences between
var
,let
, andconst
?- Answer:
var
has function scope and can be redeclared and updated.let
has block scope and can be updated but not redeclared.const
has block scope and cannot be updated or redeclared.
- Answer:
- What is a function in JavaScript?
- Answer: A function is a block of code designed to perform a particular task. It is executed when something calls it. Example:
function greet(name) {
return 'Hello ' + name;
}
- Answer: A function is a block of code designed to perform a particular task. It is executed when something calls it. Example:
- What is an arrow function?
- Answer: Arrow functions are a shorthand for writing functions using the
=>
syntax. Example:const add = (a, b) => a + b;
- Answer: Arrow functions are a shorthand for writing functions using the
- What is an object in JavaScript?
- Answer: An object is a collection of properties, where each property has a key-value pair. Example:
const person = {
name: 'John',
age: 30,
greet: function() { return 'Hello'; }
};
- Answer: An object is a collection of properties, where each property has a key-value pair. Example:
- How do you create an array in JavaScript?
- Answer: An array can be created using square brackets
[]
. Example:const numbers = [1, 2, 3, 4, 5];
- Answer: An array can be created using square brackets
- What is a callback function?
- Answer: A callback function is a function passed into another function as an argument and is executed after some operation has been completed. Example:
function fetchData(callback) {
// simulating fetching data
callback('data');
}
fetchData(function(data) {
console.log(data);
});
- Answer: A callback function is a function passed into another function as an argument and is executed after some operation has been completed. Example:
- Explain the concept of promises in JavaScript.
- Answer: Promises are used to handle asynchronous operations. They represent a value that may be available now, or in the future, or never. Example:
const promise = new Promise((resolve, reject) => {
if (success) resolve('Success');
else reject('Error');
});
- Answer: Promises are used to handle asynchronous operations. They represent a value that may be available now, or in the future, or never. Example:
- What is the use of
this
keyword?- Answer: The
this
keyword refers to the object it belongs to. It has different values depending on where it is used:- In a method,
this
refers to the owner object. - Alone,
this
refers to the global object. - In a function,
this
refers to the global object. - In an event,
this
refers to the element that received the event.
- In a method,
- Answer: The
Intermediate Questions
- What is hoisting in JavaScript?
- Answer: Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. This means you can use variables and functions before declaring them.
- What is the difference between
==
and===
?- Answer:
==
checks for value equality with type coercion, whereas===
checks for both value and type equality without type coercion.
- Answer:
- Explain event delegation.
- Answer: Event delegation is a technique of using a single event listener to manage all similar events by taking advantage of event bubbling. This improves performance and simplifies code. Example:
document.getElementById('parent').addEventListener('click', function(event) {
if (event.target.classList.contains('child')) {
console.log('Child element clicked');
}
});
- Answer: Event delegation is a technique of using a single event listener to manage all similar events by taking advantage of event bubbling. This improves performance and simplifies code. Example:
- What are closures in JavaScript?
- Answer: Closures are functions that have access to their own scope, the outer function’s scope, and the global scope. They are created every time a function is created. Example:
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
counter(); // 1
counter(); // 2
- Answer: Closures are functions that have access to their own scope, the outer function’s scope, and the global scope. They are created every time a function is created. Example:
- What is the
fetch
API?- Answer: The
fetch
API is used to make asynchronous network requests similar toXMLHttpRequest
. It returns a promise that resolves to the response object. Example:fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
- Answer: The
- What is the difference between
null
andundefined
?- Answer:
null
is an assignment value that represents no value, whereasundefined
means a variable has been declared but has not yet been assigned a value.
- Answer:
- What are template literals in JavaScript?
- Answer: Template literals are enclosed by backticks (`) and allow embedded expressions. They can contain placeholders using
${expression}
. Example:const name = 'John';
const greeting = `Hello, ${name}`;
- Answer: Template literals are enclosed by backticks (`) and allow embedded expressions. They can contain placeholders using
- Explain the concept of the event loop in JavaScript.
- Answer: The event loop is a mechanism that handles asynchronous callbacks in JavaScript. It allows non-blocking operations by pushing tasks to a queue, and the loop continuously checks the queue to execute tasks when the call stack is empty.
- What is a higher-order function?
- Answer: A higher-order function is a function that takes another function as an argument, or returns a function as a result. Example:
function higherOrder(fn) {
return function() {
return fn() + ' world';
};
}
const sayHello = () => 'Hello';
const newFunction = higherOrder(sayHello);
newFunction(); // Hello world
- Answer: A higher-order function is a function that takes another function as an argument, or returns a function as a result. Example:
- What are default parameters in functions?
- Answer: Default parameters allow you to initialize named parameters with default values if no value or
undefined
is passed. Example:function greet(name = 'Guest') {
return `Hello, ${name}`;
}
greet(); // Hello, Guest
- Answer: Default parameters allow you to initialize named parameters with default values if no value or
Advanced Questions
- What is destructuring assignment?
- Answer: Destructuring assignment is a syntax that allows you to unpack values from arrays, or properties from objects, into distinct variables. Example:
const [a, b] = [1, 2];
const {name, age} = {name: 'John', age: 30};
- Answer: Destructuring assignment is a syntax that allows you to unpack values from arrays, or properties from objects, into distinct variables. Example:
- What is the difference between
map
andforEach
?- Answer:
map
creates a new array with the results of calling a provided function on every element, whileforEach
executes a provided function once for each array element but does not return a new array.
- Answer:
- What are the different ways to create objects in JavaScript?
- Answer:
- Object literals:
const obj = { key: 'value' };
- Constructor functions:
function Person(name) { this.name = name; }
Object.create
:const obj = Object.create(proto);
- Classes:
class Person { constructor(name) { this.name = name; } }
- Object literals:
- Answer:
- Explain
async
andawait
.- Answer:
async
functions return a promise, andawait
is used to pause execution until the promise is resolved. It makes asynchronous code look and behave like synchronous code. Example:async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();
- Answer:
- What is a generator function?
- Answer: A generator function is a function that can be paused and resumed, and it can yield multiple values. It is defined using the
function*
syntax. Example:function* generator() {
yield 1;
yield 2;
yield 3;
}
const gen = generator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
- Answer: A generator function is a function that can be paused and resumed, and it can yield multiple values. It is defined using the
- What is the purpose of the
symbol
type?- Answer:
symbol
is a primitive data type used to create unique and immutable identifiers, often used for object property keys to avoid name collisions. Example:const sym = Symbol('description');
const obj = { [sym]: 'value' };
- Answer:
- Explain the difference between shallow copy and deep copy.
- Answer: A shallow copy copies an object’s properties without copying nested objects. A deep copy creates a copy of an object and all objects nested within it.
- How does
Object.assign
work?- Answer:
Object.assign
copies all enumerable own properties from one or more source objects to a target object. Example:const target = { a: 1 };
const source = { b: 2 };
const result = Object.assign(target, source);
console.log(result); // { a: 1, b: 2 }
- Answer:
- What is the purpose of
Proxy
in JavaScript?- Answer:
Proxy
allows you to create an object with custom behavior for fundamental operations (e.g., property lookup, assignment). Example:const handler = {
get: function(obj, prop) {
return prop in obj ? obj[prop] : 'default';
}
};
const proxy = new Proxy({}, handler);
console.log(proxy.nonExistent); // 'default'
- Answer:
- What are modules in JavaScript?
- Answer: Modules are a way to organize and encapsulate code into separate files and namespaces. They allow for better code reuse and maintainability. Example using ES6 modules:
// main.js// module.js
export const name = 'John';
export function greet() { return 'Hello'; }
import { name, greet } from ‘./module’;
console.log(name); // John
console.log(greet()); // Hello
- Answer: Modules are a way to organize and encapsulate code into separate files and namespaces. They allow for better code reuse and maintainability. Example using ES6 modules:
Practical Questions
- How do you handle errors in JavaScript?
- Answer: Errors can be handled using
try
,catch
, andfinally
blocks. Example:try {
throw new Error('An error occurred');
} catch (error) {
console.error(error.message);
} finally {
console.log('Execution finished');
}
- Answer: Errors can be handled using
- How do you perform AJAX requests using JavaScript?
- Answer: AJAX requests can be performed using
XMLHttpRequest
or thefetch
API. Example usingfetch
:fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
- Answer: AJAX requests can be performed using
- How can you manipulate the DOM using JavaScript?
- Answer: DOM manipulation can be done using methods like
getElementById
,querySelector
,createElement
,appendChild
, etc. Example:const element = document.createElement('div');
element.textContent = 'Hello, World!';
document.body.appendChild(element);
- Answer: DOM manipulation can be done using methods like
- Explain the concept of
strict mode
.- Answer:
strict mode
is a way to opt into a restricted variant of JavaScript, which catches common coding errors and prevents the use of certain features. It is declared at the beginning of a script or a function. Example:
;
x = 3.14; // This will throw an error because x is not declared
- Answer:
- What is event bubbling and event capturing?
- Answer: Event bubbling is the process where an event starts at the target element and bubbles up to the root. Event capturing is the opposite, where the event starts from the root and propagates down to the target. Example:
document.getElementById('child').addEventListener('click', function(event) {
console.log('Child clicked');
}, true); // true for capturing phase
- Answer: Event bubbling is the process where an event starts at the target element and bubbles up to the root. Event capturing is the opposite, where the event starts from the root and propagates down to the target. Example:
- What is the purpose of the
bind
method?- Answer: The
bind
method creates a new function that, when called, has itsthis
keyword set to the provided value, with a given sequence of arguments. Example:const obj = { x: 42 };
function getX() {
return this.x;
}
const boundGetX = getX.bind(obj);
console.log(boundGetX()); // 42
- Answer: The
- What is the use of
apply
andcall
methods?- Answer: Both
apply
andcall
are used to call a function with a giventhis
value and arguments.call
accepts arguments individually, whileapply
accepts arguments as an array. Example:function greet(greeting, punctuation) {
return greeting + ', ' + this.name + punctuation;
}
const obj = { name: 'John' };
console.log(greet.call(obj, 'Hello', '!')); // Hello, John!
console.log(greet.apply(obj, ['Hi', '.'])); // Hi, John.
- Answer: Both
- How do you prevent event bubbling?
- Answer: Event bubbling can be prevented using
event.stopPropagation()
. Example:document.getElementById('child').addEventListener('click', function(event) {
event.stopPropagation();
console.log('Child clicked');
});
- Answer: Event bubbling can be prevented using
- What is the difference between synchronous and asynchronous code?
- Answer: Synchronous code is executed sequentially, blocking further execution until the current task is completed. Asynchronous code allows other tasks to run while waiting for an operation to complete, thus not blocking execution.
- How do you make a deep copy of an object?
- Answer: A deep copy can be made using
JSON.parse
andJSON.stringify
, or by using a custom function to recursively copy properties. Example:const obj = { a: 1, b: { c: 2 } };
const deepCopy = JSON.parse(JSON.stringify(obj));
- Answer: A deep copy can be made using
Coding Challenges
- Write a function to reverse a string.
- Answer:
function reverseString(str) {
return str.split('').reverse().join('');
}
console.log(reverseString('hello')); // 'olleh'
- Answer:
- Write a function to check if a number is prime.
- Answer:
function isPrime(num) {
if (num <= 1) return false;
for (let i = 2; i < num; i++) {
if (num % i === 0) return false;
}
return true;
}
console.log(isPrime(7)); // true
- Answer:
- Write a function to find the maximum value in an array.
- Answer:
function findMax(arr) {
return Math.max(...arr);
}
console.log(findMax([1, 2, 3, 4, 5])); // 5
- Answer:
- Write a function to remove duplicates from an array.
- Answer:
function removeDuplicates(arr) {
return [...new Set(arr)];
}
console.log(removeDuplicates([1, 2, 2, 3, 4, 4])); // [1, 2, 3, 4]
- Answer:
- Write a function to merge two sorted arrays into one sorted array.
- Answer:
function mergeSortedArrays(arr1, arr2) {
let merged = [];
let i = 0, j = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
merged.push(arr1[i]);
i++;
} else {
merged.push(arr2[j]);
j++;
}
}
return merged.concat(arr1.slice(i)).concat(arr2.slice(j));
}
console.log(mergeSortedArrays([1, 3, 5], [2, 4, 6])); // [1, 2, 3, 4, 5, 6]
- Answer:
- Write a function to flatten a nested array.
- Answer:
function flattenArray(arr) {
return arr.reduce((flat, toFlatten) => {
return flat.concat(Array.isArray(toFlatten) ? flattenArray(toFlatten) : toFlatten);
}, []);
}
console.log(flattenArray([1, [2, [3, 4], 5]])); // [1, 2, 3, 4, 5]
- Answer:
- Write a function to find the factorial of a number.
- Answer:
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
- Answer:
- Write a function to check if a string is a palindrome.
- Answer:
function isPalindrome(str) {
const reversed = str.split('').reverse().join('');
return str === reversed;
}
console.log(isPalindrome('racecar')); // true
- Answer:
- Write a function to find the intersection of two arrays.
- Answer:
function arrayIntersection(arr1, arr2) {
return arr1.filter(value => arr2.includes(value));
}
console.log(arrayIntersection([1, 2, 3], [2, 3, 4])); // [2, 3]
- Answer:
- Write a function to implement binary search.
- Answer:
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
console.log(binarySearch([1, 2, 3, 4, 5], 3)); // 2
- Answer: