JavaScript has become one of the most popular programming languages in the world, powering everything from web applications to server-side development. As a JavaScript developer, understanding key concepts is essential not only for building applications but also for acing interviews. In this blog, we will cover 25 important JavaScript interview questions along with examples to illustrate their application.
1. What is the difference between var
, let
, and const
?
-
var
is function-scoped and can be redeclared. -
let
is block-scoped and cannot be redeclared in the same block. -
const
is also block-scoped but cannot be reassigned.
var a = 1;
let b = 2;
const c = 3;
if (true) {
var a = 4; // Same variable
let b = 5; // Scoped to block
// const c = 6; // Error: variable c is already declared
}
console.log(a); // 4
console.log(b); // 2
// console.log(c); // Error: c is not defined
2. What is hoisting?
Hoisting is the behavior in JavaScript where variable declarations are moved to the top of their scope during compilation. Only the declarations are hoisted, not the initializations.
console.log(x); // undefined
var x = 5;
3. Explain closures.
A closure is a function that remembers its lexical scope even when the function is executed outside that scope. Closures allow for data encapsulation.
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const increment = outer();
console.log(increment()); // 1
console.log(increment()); // 2
4. What are promises?
A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Done!");
}, 1000);
});
myPromise.then(result => console.log(result)); // "Done!" after 1 second
5. What is async/await?
Async/await is syntactic sugar built on top of Promises. The async
function returns a promise, and await
pauses the execution of the function until the promise is resolved.
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}
6. What are arrow functions?
Arrow functions allow for a more concise syntax when writing function expressions. They also lexically bind the this
value.
const add = (x, y) => x + y;
console.log(add(2, 3)); // 5
7. Explain the this
keyword.
The value of this
indicates the object that is executing the current function. Its value can vary based on how the function is called.
const obj = {
value: 10,
getValue: function() {
return this.value;
}
};
console.log(obj.getValue()); // 10
8. What is the event loop?
The event loop handles asynchronous calls in JavaScript, allowing non-blocking execution of code. It continuously checks the call stack and the message queue.
console.log("1");
setTimeout(() => console.log("2"), 0);
console.log("3");
// Output: 1, 3, 2
9. What is the difference between ==
and ===
?
==
is a loose equality operator that checks for equality after performing type coercion. ===
is a strict equality operator that checks for equality without type coercion.
console.log(0 == '0'); // true
console.log(0 === '0'); // false
10. What is the purpose of the bind
method?
bind
creates a new function that, when called, has its this
keyword set to the provided value, allowing you to set the context.
const obj = { value: 42 };
const getValue = function() {
return this.value;
};
const boundGetValue = getValue.bind(obj);
console.log(boundGetValue()); // 42
11. Explain prototypal inheritance.
Prototypal inheritance is a feature in JavaScript that allows objects to inherit properties and methods from other objects. It's achieved via the prototype
property.
const animal = {
eats: true
};
const rabbit = Object.create(animal);
console.log(rabbit.eats); // true
12. What are modules in JavaScript?
Modules are reusable pieces of code that can be exported from one file and imported into another. They help in organizing and encapsulating code.
// module.js
export const pi = 3.14;
// main.js
import { pi } from './module.js';
console.log(pi); // 3.14
13. What is the spread operator?
The spread operator (...
) allows an iterable, such as an array, to be expanded in places where zero or more arguments or elements are expected.
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // [1, 2, 3, 4, 5]
14. What is destructuring?
Destructuring is a syntax that allows unpacking values from arrays or properties from objects into distinct variables.
const user = { name: 'Alice', age: 25 };
const { name, age } = user;
console.log(name); // Alice
15. What is a higher-order function?
A higher-order function is a function that takes another function as an argument or returns a function as its result.
function greet(fn) {
return fn();
}
greet(() => "Hello!"); // "Hello!"
16. What is the difference between synchronous and asynchronous programming?
Synchronous programming executes tasks sequentially, while asynchronous programming allows tasks to be executed concurrently, improving performance.
console.log("Start");
setTimeout(() => console.log("Async"), 0);
console.log("End");
// Output: Start, End, Async
17. What is a callback function?
A callback function is a function passed into another function as an argument, executed after some operation is complete.
function fetchData(callback) {
setTimeout(() => {
callback("Data received");
}, 1000);
}
fetchData(data => console.log(data)); // "Data received" after 1 second
18. What is the instanceof
operator?
instanceof
is used to check if an object is an instance of a specific constructor or class.
function Person() {}
const person = new Person();
console.log(person instanceof Person); // true
19. What is the purpose of setTimeout
and setInterval
?
-
setTimeout
executes a function after a specified delay. -
setInterval
repeatedly calls a function at specified intervals until cleared.
setTimeout(() => console.log("Executed after 1 second"), 1000);
const intervalId = setInterval(() => console.log("Executed every second"), 1000);
// clearInterval(intervalId); // To stop the interval
20. What are JavaScript data types?
JavaScript has 7 primitive data types: Undefined, Null, Boolean, Number, BigInt, String, and Symbol.
let name = "Alice"; // String
let age = 30; // Number
let isStudent = false; // Boolean
21. What is a template literal?
Template literals are string literals allowing embedded expressions, using backticks for formatting.
const name = 'Alice';
const greeting = `Hello, ${name}!`;
console.log(greeting); // Hello, Alice!
22. What is a wrapper object?
Wrapper objects allow primitive values to be treated as objects. They enable access to methods associated with the primitive data type.
const string = new String("Hello");
console.log(string.length); // 5
23. Explain the difference between slice
and splice
.
-
slice
returns a shallow copy of a portion of an array. -
splice
changes the contents of an array by removing or replacing existing elements.
const arr = [1, 2, 3, 4, 5];
const sliced = arr.slice(1, 4); // [2, 3, 4]
arr.splice(1, 2); // Removes 2 elements starting from index 1
console.log(arr); // [1, 4, 5]
24. What is the difference between synchronous and asynchronous functions?
- Synchronous functions block execution until they complete.
- Asynchronous functions allow other operations to continue during their execution.
function synchronousFunction() {
console.log("Synchronous Execution");
}
async function asynchronousFunction() {
console.log("Asynchronous Execution");
await new Promise(resolve => setTimeout(resolve, 1000));
console.log("Continuing after 1 second");
}
synchronousFunction();
asynchronousFunction();
25. What is JSON?
JSON (JavaScript Object Notation) is a lightweight data interchange format easy for humans to read and write and machines to parse and generate.
const jsonData = '{"name": "Alice", "age": 25}';
const user = JSON.parse(jsonData);
console.log(user.name); // Alice
Conclusion
Mastering these 25 JavaScript concepts will not only prepare you for technical interviews but also help you become a more proficient developer. Keep practicing, and ensure you understand the underlying principles, as these will serve you well in your coding career!