JavaScript Basics
1. What is JavaScript?
○ Answer: JavaScript is a high-level, interpreted scripting language used to make
web pages interactive. It runs in the browser and is also used for server-side
development via environments like Node.js.
2. Explain the difference between var, let, and const.
○ Answer:
■ var: Function-scoped, can be redeclared, and is hoisted.
■ let: Block-scoped, cannot be redeclared within the same block.
■ const: Block-scoped, must be initialized, and cannot be reassigned.
3. What are data types in JavaScript?
○ Answer:
■ Primitive: string, number, boolean, null, undefined, bigint,
symbol
■ Non-primitive: object (arrays, functions, etc.)
4. What is typeof?
Answer: The typeof operator returns the data type of a variable.
javascript
Copy code
console.log(typeof 42); // "number"
console.log(typeof "Hello"); // "string"
○
5. What are truthy and falsy values in JavaScript?
○ Answer:
■ Truthy: Values that evaluate to true in a boolean context ("text", 1,
[], {})
■ Falsy: Values that evaluate to false (0, "", null, undefined, NaN,
false).
Functions and Scope
6. What is the difference between function declarations and function expressions?
○ Answer:
Function Declaration:
javascript
Copy code
function greet() {
console.log("Hello!");
}
Function Expression:
javascript
Copy code
const greet = function () {
console.log("Hello!");
};
■
7. What is a closure in JavaScript?
Answer: A closure is a function that retains access to its outer scope, even after the outer
function has returned.
javascript
Copy code
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const increment = outer();
console.log(increment()); // 1
console.log(increment()); // 2
○
8. What is the difference between synchronous and asynchronous functions?
○ Answer:
■ Synchronous: Executes line by line, blocking further code until the current
task finishes.
■ Asynchronous: Executes non-blocking tasks, allowing the next code to
run while waiting for operations like I/O.
9. What are arrow functions?
Answer: Concise syntax for writing functions. They do not bind their own this.
javascript
Copy code
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
○
10. What is the difference between call(), apply(), and bind()?
○ Answer:
■ call(): Invokes a function, passing arguments individually.
■ apply(): Invokes a function, passing arguments as an array.
■ bind(): Returns a new function with a specific this context.
javascript
Copy code
const obj = { x: 2 };
function multiply(y) {
return this.x * y;
}
console.log(multiply.call(obj, 3)); // 6
console.log(multiply.apply(obj, [3])); // 6
const boundMultiply = multiply.bind(obj);
console.log(boundMultiply(3)); // 6
Objects and Prototypes
11. What are JavaScript objects?
Answer: Collections of key-value pairs.
javascript
Copy code
const person = { name: "John", age: 30 };
○
12. Explain prototypes in JavaScript.
○ Answer: Prototypes are the mechanism by which JavaScript objects inherit
properties and methods.
13. What is the difference between shallow and deep copy?
○ Answer:
■ Shallow copy: Copies the reference, not the actual data.
■ Deep copy: Copies the data itself.
14. How do you create an object in JavaScript?
Answer:
javascript
Copy code
const obj1 = {}; // Object literal
const obj2 = new Object(); // Object constructor
○
15. How can you merge two objects in JavaScript?
Answer:
javascript
Copy code
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const merged = { ...obj1, ...obj2 };
DOM Manipulation
16. What is the DOM?
○ Answer: Document Object Model, a tree representation of HTML elements.
17. How do you select elements in the DOM?
Answer:
javascript
Copy code
document.getElementById("id");
document.querySelector(".class");
○
18. How do you add an element to the DOM?
Answer:
javascript
Copy code
const div = document.createElement("div");
document.body.appendChild(div);
○
19. How do you remove an element from the DOM?
Answer:
javascript
Copy code
const element = document.getElementById("id");
element.remove();
○
20. How can you change the content of an element?
Answer:
javascript
Copy code
const p = document.getElementById("para");
p.textContent = "New text";
ES6 and Beyond
21. What are ES6 features in JavaScript?
○ Answer: Arrow functions, let and const, template literals, destructuring,
modules, Map, Set, etc.
22. What is destructuring?
Answer:
javascript
Copy code
const [a, b] = [1, 2];
const { name, age } = { name: "John", age: 30 };
○
23. What is a promise?
Answer: Represents a value that may be available now, in the future, or never.
javascript
Copy code
const promise = new Promise((resolve, reject) => {
resolve("Success");
});
○
24. What are template literals?
Answer:
javascript
Copy code
const name = "John";
console.log(`Hello, ${name}`);
○
25. What is the difference between == and ===?
○ Answer:
■ ==: Compares values after type coercion.
■ ===: Strict equality, compares both value and type.
26. What is async/await?
● Answer: async/await is syntactic sugar for handling promises in a cleaner and more
readable way.
○ async makes a function return a promise.
○ await pauses the execution of an async function until the promise is resolved
or rejected.
javascript
Copy code
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);
}
}
27. What is event delegation?
Answer: Event delegation is a technique in which a parent element handles events for its child
elements. It leverages event bubbling to capture events at a higher level.
javascript
Copy code
document.getElementById('parent').addEventListener('click', (e) => {
if (e.target && e.target.tagName === 'BUTTON') {
console.log('Button clicked:', e.target.textContent);
}
});
28. What is a module in JavaScript?
Answer: A module is a reusable block of code that can be exported and imported between files.
javascript
Copy code
// file: math.js
export const add = (a, b) => a + b;
// file: main.js
import { add } from './math.js';
console.log(add(2, 3)); // 5
29. What is the event loop?
Answer: The event loop is a mechanism in JavaScript that manages the execution of code,
collects and processes events, and executes queued tasks. It ensures non-blocking behavior by
handling asynchronous tasks via a queue.
javascript
Copy code
console.log('Start');
setTimeout(() => console.log('Timeout'), 0);
console.log('End');
// Output: Start, End, Timeout
●
30. What is hoisting?
Answer: Hoisting is JavaScript's default behavior of moving declarations to the top of their
scope. Only declarations are hoisted, not initializations.
javascript
Copy code
console.log(a); // undefined
var a = 5;
31. How does this work in JavaScript?
● Answer: this refers to the context in which a function is executed:
○ In the global scope: this refers to the global object (window in browsers).
○ In a method: this refers to the object that owns the method.
○ In an arrow function: this is lexically bound to the surrounding scope.
32. Explain closures.
Answer: A closure is created when a function retains access to its lexical scope, even when
executed outside of that scope.
javascript
Copy code
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const increment = outer();
console.log(increment()); // 1
console.log(increment()); // 2
33. What are higher-order functions?
Answer: Higher-order functions are functions that can accept other functions as arguments or
return them as results.
javascript
Copy code
const numbers = [1, 2, 3];
const doubled = numbers.map((num) => num * 2);
console.log(doubled); // [2, 4, 6]
34. What is a callback function?
Answer: A callback function is a function passed as an argument to another function and
executed later.
javascript
Copy code
function greet(name, callback) {
console.log(`Hello, ${name}`);
callback();
}
greet('John', () => console.log('Callback executed.'));
35. How do you debounce a function?
Answer: Debouncing limits how often a function can be executed, ensuring it is called after a
specified delay.
javascript
Copy code
function debounce(func, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => func(...args), delay);
};
}
const log = debounce(() => console.log('Debounced!'), 300);
window.addEventListener('resize', log);
●
36. What is a singleton in JavaScript?
Answer: A singleton is a design pattern ensuring that a class has only one instance.
javascript
Copy code
class Singleton {
constructor() {
if (Singleton.instance) return Singleton.instance;
Singleton.instance = this;
}
}
const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1 === instance2); // true
37. What is memoization?
Answer: Memoization is an optimization technique to cache the results of expensive function
calls.
javascript
Copy code
function memoize(fn) {
const cache = {};
return function (n) {
if (cache[n]) return cache[n];
return (cache[n] = fn(n));
};
}
const fib = memoize((n) => (n <= 1 ? n : fib(n - 1) + fib(n - 2)));
console.log(fib(10)); // 55
●
38. What is the difference between map(), filter(), and reduce()?
● Answer:
○ map(): Transforms each element in an array.
○ filter(): Returns a new array containing elements that pass a condition.
○ reduce(): Reduces an array to a single value.
39. How do you handle errors in JavaScript?
● Answer:
Using try...catch:
javascript
Copy code
try {
throw new Error('Something went wrong');
} catch (err) {
console.error(err.message);
}
40. What is localStorage and sessionStorage?
● Answer: Both are web storage APIs.
○ localStorage: Persists data until explicitly deleted.
○ sessionStorage: Clears data when the session ends (e.g., tab is closed).
41. How does garbage collection work in JavaScript?
● Answer: JavaScript's garbage collector removes objects that are no longer referenced
to free up memory.
42. What is a generator function?
Answer: A generator function can pause and resume its execution using yield.
javascript
Copy code
function* generator() {
yield 1;
yield 2;
}
const gen = generator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
43. What are ES6 classes?
Answer: ES6 classes provide a syntax to define objects and inheritance.
javascript
Copy code
class Person {
constructor(name) {
this.name = name;
}
}
44. What is Promise.all()?
● Answer: Promise.all() runs multiple promises concurrently and waits for all to
resolve or any to reject.
45. What is the new keyword in JavaScript?
● Answer: The new keyword creates a new object instance of a constructor function.
46. Explain the difference between apply(), call(), and bind().
● Answer: call and apply invoke functions immediately, bind returns a new function.
47. How do you handle CORS errors?
● Answer: Configure the server to include the Access-Control-Allow-Origin
header.
48. What are Web APIs?
● Answer: Web APIs are browser-provided interfaces like DOM, Fetch, and localStorage.