- What is JavaScript?
JavaScript is a lightweight, interpreted programming language used to create dynamic web content.
- What are JavaScript data types?
Primitive: String, Number, Boolean, Undefined, Null, Symbol, BigInt
Non-Primitive: Object, Array, Function
Example:
let str = "Hello"; // String let num = 42; // Number let bool = true; // Boolean
- Explain var, let, and const.
var: Function-scoped, can be re-declared.
let: Block-scoped, cannot be re-declared.
const: Block-scoped, must be initialized and cannot be reassigned.
Example:
var a = 10; let b = 20; const c = 30;
- What is hoisting?
Hoisting allows function and variable declarations to be moved to the top of their scope during compile time.
Example:
console.log(x); // undefined var x = 10;
- Difference between == and ===.
\==: Abstract equality, checks value.
\===: Strict equality, checks value and type.
Example:
console.log(5 == '5'); // true console.log(5 === '5'); // false
- What are closures in JavaScript?
Closures allow a function to access variables from its outer scope.
Example:
function outer() { let count = 0; return function inner() { count++; return count; }; } const increment = outer(); console.log(increment()); // 1 console.log(increment()); // 2
- What is the DOM?
DOM (Document Object Model) is an API that represents HTML as a tree structure.
- Explain event delegation.
Event delegation uses a parent to handle events for its child elements.
Example:
document.getElementById('parent').addEventListener('click', (e) => { console.log('Clicked on', e.target); });
- What are promises?
Promises handle asynchronous operations and can be in states: pending, fulfilled, or rejected.
Example:
const promise = new Promise((resolve, reject) => { resolve("Success"); }); promise.then((res) => console.log(res));
- Explain async/await.
async/await is a cleaner way to handle promises.
Example:
async function fetchData() { let data = await fetch('https://api.example.com'); console.log(data); } fetchData();
- What are arrow functions?
Arrow functions are a shorter syntax for functions.
Example:
const add = (a, b) => a + b; console.log(add(5, 3)); // 8
- What is the spread operator?
The spread operator (...) expands an array or object.
Example:
let arr = [1, 2, 3]; let newArr = [...arr, 4]; console.log(newArr); // [1, 2, 3, 4]
- Difference between undefined and null.
undefined: Variable declared but not initialized.
null: Explicitly set to no value.
- What is this in JavaScript?
this refers to the context in which the function is executed.
- Explain call, apply, and bind.
call: Invokes a function with arguments as a list.
apply: Invokes a function with arguments as an array.
bind: Returns a new function bound to a context.
Example:
function greet(greeting) { console.log(${greeting}, ${
this.name
}
); } const user = { name: "John" }; greet.call(user, "Hello");
- Explain prototypes in JavaScript.
Prototypes are the mechanism by which objects inherit features.
Example:
function Person(name) { this.name = name; } Person.prototype.greet = function () { return Hello, ${
this.name
}
; }; const john = new Person('John'); console.log(john.greet());
- What are IIFEs?
Immediately Invoked Function Expressions execute immediately after definition.
Example:
(function () { console.log("IIFE called"); })();
- Difference between map, filter, and reduce.
map: Transforms elements.
filter: Filters elements.
reduce: Reduces to a single value.
Example:
let arr = [1, 2, 3]; let doubled = arr.map(x => x * 2); // [2, 4, 6]
- What is an event loop?
The event loop manages the execution of asynchronous code in JavaScript.
- What are modules in JavaScript?
Modules allow code reuse using export and import.
Example:
// module.js export const greet = () => console.log("Hello");
// main.js import { greet } from './module.js'; greet();
21. What is destructuring in JavaScript?
Destructuring extracts values from arrays or properties from objects.
Example:
const obj = { name: "John", age: 30 };
const { name, age } = obj;
console.log(name, age); // John, 30
---
22. What is a callback function?
A callback function is passed as an argument to another function and executed later.
Example:
function greet(name, callback) {
callback(`Hello, ${name}`);
}
greet("John", (message) => console.log(message)); // Hello, John
---
23. What is a higher-order function?
A function that takes another function as an argument or returns a function.
Example:
function higherOrder(fn) {
return function () {
fn();
};
}
---
24. Explain debounce and throttle.
Debounce: Limits a function's execution after a delay.
Throttle: Ensures a function executes once per time interval.
Example of Debounce:
function debounce(func, delay) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func(...args), delay);
};
}
---
25. What is the difference between slice and splice?
slice: Returns a portion of an array without modifying it.
splice: Modifies the original array.
Example:
let arr = [1, 2, 3, 4];
console.log(arr.slice(1, 3)); // [2, 3]
arr.splice(1, 2);
console.log(arr); // [1, 4]
---
26. What is the difference between forEach and map?
forEach: Iterates through an array, does not return a new array.
map: Returns a new array after applying a function.
Example:
let arr = [1, 2, 3];
arr.forEach(x => console.log(x)); // 1, 2, 3
let doubled = arr.map(x => x * 2); // [2, 4, 6]
---
27. Explain the fetch API.
The fetch API is used to make network requests.
Example:
fetch('api.example.com')
.then(res => res.json())
.then(data => console.log(data));
---
28. What is setTimeout and setInterval?
setTimeout: Executes code after a delay.
setInterval: Repeats code execution at regular intervals.
Example:
setTimeout(() => console.log("Hello"), 1000);
setInterval(() => console.log("Repeating"), 1000);
---
29. Explain the typeof operator.
The typeof operator checks the data type of a value.
Example:
console.log(typeof "hello"); // string
console.log(typeof 42); // number
---
30. What is Object.assign()?
It copies properties from one or more objects to a target object.
Example:
const target = { a: 1 };
const source = { b: 2 };
Object.assign(target, source);
console.log(target); // { a: 1, b: 2 }
---
31. What are generators in JavaScript?
Generators are functions that can be paused and resumed.
Example:
function* generator() {
yield 1;
yield 2;
}
const gen = generator();
console.log(gen.next()); // { value: 1, done: false }
---
32. Explain immutability in JavaScript.
Immutability means not modifying the original object or array.
Example:
const arr = [1, 2, 3];
const newArr = [...arr, 4];
console.log(newArr); // [1, 2, 3, 4]
---
33. What is the new keyword in JavaScript?
The new keyword creates an instance of a user-defined object.
Example:
function Person(name) {
this.name = name;
}
const john = new Person("John");
---
34. What are the differences between synchronous and asynchronous code?
Synchronous: Blocks further execution until the current task completes.
Asynchronous: Executes without blocking other operations.
Example:
console.log("Sync");
setTimeout(() => console.log("Async"), 0);
console.log("End");
---
35. Explain the concept of currying.
Currying transforms a function with multiple arguments into a series of functions.
Example:
function curry(a) {
return function (b) {
return a + b;
};
}
console.log(curry(2)(3)); // 5
---
36. What is the difference between Array.forEach and Array.reduce?
forEach: Performs an action for each element.
reduce: Aggregates array elements into a single value.
---
37. Explain try...catch in JavaScript.
Handles exceptions and provides error handling.
Example:
try {
throw new Error("Something went wrong");
} catch (err) {
console.log(err.message);
}
---
38. What is the event.target in JavaScript?
The event.target property returns the element that triggered the event.
---
39. Explain the concept of memoization.
Memoization is an optimization technique to cache results of expensive function calls.
Example:
function memoize(fn) {
const cache = {};
return function (n) {
if (n in cache) return cache[n];
return (cache[n] = fn(n));
};
}
40. What are WeakMap and WeakSet?
WeakMap: Holds key-value pairs,
where keys are weakly referenced.
WeakSet: Stores weakly referenced objects.
Example:
let weakMap = new WeakMap();
let obj = {};
weakMap.set(obj, "value");