Question answer list for JavaScript developer interview preparation from basic to advance
- Get link
- X
- Other Apps
Here’s a well-organized question-and-answer list for a podcast with an expert JavaScript developer, focused on explaining concepts with practical coding examples in easy-to-understand terms:
Q1: Can you briefly introduce JavaScript for our listeners who might be new to it?
A1: JavaScript is a high-level programming language mainly used for building interactive web pages. It's often used alongside HTML and CSS to create dynamic, user-friendly websites. For example, if you click a button and something changes on the page, that's JavaScript in action.
Fundamentals of JavaScript
Q2: Let’s start with the basics. Could you explain what variables are and how we declare them in JavaScript?
A2: Sure! In JavaScript, variables are used to store data. We can declare variables using let
, const
, or var
. For instance:
let age = 25;
const name = "John";
var isActive = true;
let
is for variables that can change.const
is for values that shouldn’t change.var
is the older version, butlet
andconst
are preferred today.
Data Types and Type Conversion
Q3: What are the main data types in JavaScript, and can you show us an example of how type conversion works?
A3: In JavaScript, we have primitive types like number
, string
, boolean
, null
, undefined
, and symbol
, plus complex types like objects
and arrays
.
For example:
let num = 5; // number
let text = "5"; // string
let result = num + text; // string concatenation
console.log(result); // Outputs "55" because JavaScript converts number to string
We can also convert types explicitly:
let str = "123";
let num = Number(str); // converts string to number
console.log(num); // Outputs 123
Functions and Scope
Q4: Can you explain what functions are and how they relate to scope in JavaScript?
A4: A function in JavaScript is a block of code designed to perform a particular task. Functions can take inputs (parameters) and return an output. Here's a simple example:
function greet(name) {
return "Hello " + name;
}
console.log(greet("Alice")); // Outputs "Hello Alice"
Scope refers to where variables are accessible. For example:
let x = 10; // Global scope
function example() {
let y = 20; // Local scope
console.log(x, y);
}
example();
Variables declared outside the function are in the global scope, while variables inside the function are local to that function.
Objects and Arrays
Q5: What are objects and arrays in JavaScript, and how do you use them in code?
A5: Objects are collections of key-value pairs, while arrays are ordered lists of values.
Example of an object:
let person = {
name: "Alice",
age: 25,
greet: function() { console.log("Hello " + this.name); }
};
console.log(person.name); // Outputs "Alice"
person.greet(); // Outputs "Hello Alice"
Example of an array:
let numbers = [1, 2, 3, 4];
console.log(numbers[0]); // Outputs 1
numbers.push(5); // Adds 5 to the array
console.log(numbers); // Outputs [1, 2, 3, 4, 5]
Loops and Iteration
Q6: How do loops work in JavaScript, and could you show an example of a for
loop?
A6: Loops allow us to repeat a block of code multiple times. A for
loop is great when you know how many times to repeat the code.
Here’s an example of a for
loop:
for (let i = 0; i < 5; i++) {
console.log(i); // Outputs 0, 1, 2, 3, 4
}
This loop runs as long as i
is less than 5, incrementing i
by 1 each time.
Asynchronous JavaScript
Q7: What does asynchronous JavaScript mean, and how do we handle it?
A7: Asynchronous JavaScript allows code to run without blocking other code. A common example is fetching data from a server without freezing the webpage.
We use setTimeout
, Promises
, or async/await
for asynchronous tasks.
For example, using setTimeout
:
setTimeout(() => {
console.log("This message appears after 2 seconds");
}, 2000);
With async/await
for handling asynchronous tasks:
async function fetchData() {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
}
fetchData();
Error Handling
Q8: What’s the importance of error handling in JavaScript, and how do we use try/catch
?
A8: Error handling ensures that your program can recover from unexpected problems. With try/catch
, you can gracefully handle errors instead of crashing the program.
Example:
try {
let result = riskyFunction();
} catch (error) {
console.log("Something went wrong: " + error.message);
}
ES6 Features and Modern JavaScript
Q9: Could you explain some of the cool new features from ES6 like arrow functions and destructuring?
A9: Sure! ES6 brought a lot of modern JavaScript features that simplify our code.
Arrow functions:
const add = (a, b) => a + b;
console.log(add(3, 4)); // Outputs 7
Destructuring:
let person = { name: "Alice", age: 25 };
let { name, age } = person; // Extracts values from the object
console.log(name); // Outputs "Alice"
DOM Manipulation
Q10: How does JavaScript interact with the Document Object Model (DOM) to modify web pages?
A10: The DOM represents the structure of a webpage as a tree of objects. JavaScript allows us to interact with this tree to change the content dynamically.
For example, changing the text of an element:
document.getElementById("greeting").innerText = "Hello, World!";
This code would change the text of an element with the ID greeting
to "Hello, World!"
Q11: For beginners who are just starting with JavaScript, what would be your advice for learning effectively?
A11: My biggest tip would be to practice by building small projects and trying out examples on your own. Don’t just watch tutorials—get your hands dirty in the code! Start with things like a simple to-do list or a calculator. JavaScript is a language you learn by doing:
Understanding "this" in JavaScript
Q12: The this
keyword can be confusing. Can you explain how it works in JavaScript?
A12: Absolutely! The value of this
depends on how a function is called. Here are a few examples:
In a regular function:
this
refers to the global object (in browsers, it's thewindow
).function showThis() { console.log(this); // Outputs the window object } showThis();
In an object method:
this
refers to the object the method is part of.const person = { name: "John", greet: function() { console.log(this.name); } }; person.greet(); // Outputs "John"
In arrow functions: Arrow functions inherit
this
from the surrounding context, which is whythis
is lexically bound.const person = { name: "Alice", greet: () => { console.log(this.name); // 'this' refers to the global object, not the person object } }; person.greet(); // Outputs undefined (because 'this' is not referring to the person object)
JavaScript Closures
Q13: Could you explain what closures are and provide an example?
A13: A closure in JavaScript is when a function "remembers" its lexical scope, even when it's executed outside that scope. This happens because the function still has access to the variables from the surrounding environment.
Example of closure:
function outer() {
let counter = 0;
return function inner() {
counter++;
console.log(counter);
}
}
const increment = outer();
increment(); // Outputs 1
increment(); // Outputs 2
Here, the inner function has access to counter
, even though it's executed outside the outer
function.
Array Methods
Q14: Can you explain some useful array methods like map
, filter
, and reduce
with examples?
A14: Sure! These are higher-order functions that make working with arrays easier and more powerful.
map
: Transforms each element of the array and returns a new array.
let numbers = [1, 2, 3];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // Outputs [2, 4, 6]
filter
: Filters the array based on a condition and returns a new array with elements that pass the test.
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Outputs [2, 4]
reduce
: Accumulates a single result from all elements in the array.
let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // Outputs 10
Event Handling
Q15: How does event handling work in JavaScript, and could you show us an example?
A15: Event handling allows us to respond to user actions like clicks or key presses. In JavaScript, we can attach event listeners to DOM elements.
Example:
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
Here, when the button with the ID myButton
is clicked, the callback function runs, showing an alert.
JavaScript's "prototype" and Inheritance
Q16: Can you explain how inheritance works in JavaScript using prototypes?
A16: JavaScript uses prototypes for inheritance. Every object in JavaScript has a prototype, which is another object that it inherits properties and methods from.
Here's an example of prototype inheritance:
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + " makes a sound.");
};
const dog = new Animal("Buddy");
dog.speak(); // Outputs "Buddy makes a sound."
In this case, dog
inherits the speak
method from the Animal
prototype.
Destructuring Arrays and Objects
Q17: You mentioned destructuring earlier. Can you show us more examples for arrays and objects?
A17: Absolutely! Destructuring is a powerful feature in ES6 that allows you to unpack values from arrays or objects.
For arrays:
let numbers = [1, 2, 3];
let [first, second] = numbers;
console.log(first); // Outputs 1
console.log(second); // Outputs 2
For objects:
let person = { name: "John", age: 30 };
let { name, age } = person;
console.log(name); // Outputs "John"
console.log(age); // Outputs 30
Arrow Functions vs Regular Functions
Q18: What are the differences between arrow functions and regular functions, and when should you use each?
A18: Arrow functions have a simpler syntax and lexically bind the this
value, meaning they inherit this
from their surrounding context.
Example of an arrow function:
const add = (a, b) => a + b;
console.log(add(2, 3)); // Outputs 5
Regular functions, on the other hand, have their own this
value depending on how they are called:
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // Outputs 5
Use arrow functions when you need to preserve the context of this
, especially in callbacks. Regular functions are useful when you need a method with its own this
.
JavaScript Modules
Q19: What are JavaScript modules, and how do we use them?
A19: JavaScript modules allow us to split our code into smaller, reusable pieces. This makes our code cleaner and easier to maintain.
Here's how you can use modules:
- Export a function or variable in one file:
// math.js
export function add(a, b) {
return a + b;
}
- Import it in another file:
// app.js
import { add } from './math.js';
console.log(add(2, 3)); // Outputs 5
Modules help in organizing the code into distinct files, improving scalability and maintainability.
Understanding JavaScript's Event Loop
Q20: Can you explain the event loop in JavaScript and how it works?
A20: The event loop is what allows JavaScript to be non-blocking and asynchronous. JavaScript is single-threaded, meaning it can only do one thing at a time, but the event loop helps manage tasks like I/O operations.
Here’s a basic explanation:
- Call Stack: JavaScript executes functions in the call stack.
- Event Queue: When an asynchronous task like a
setTimeout
or a network request completes, its callback is added to the event queue. - Event Loop: The event loop constantly checks if the call stack is empty. If it is, it moves the first function from the event queue to the call stack and executes it.
Example with setTimeout
:
console.log("Start");
setTimeout(() => {
console.log("This happens later");
}, 1000);
console.log("End");
Output:
Start
End
This happens later
Here, the "This happens later" message is delayed because setTimeout
is asynchronous, and the event loop handles it after the synchronous code has finished.
******************** much more list ************
Q1: What is the difference between null
and undefined
in JavaScript?
A1: null
is an assignment value representing "no value" or "no object," while undefined
means a variable has been declared but has not yet been assigned a value.
Q2: What is the purpose of typeof
in JavaScript?
A2: typeof
is used to check the data type of a variable or expression, such as typeof 42
returning "number"
.
Q3: What is the difference between ==
and ===
?
A3: ==
checks for equality of values but allows type coercion, while ===
checks for both value and type equality, making it stricter.
Q4: Can you explain how setInterval()
works?
A4: setInterval()
runs a specified function repeatedly at set time intervals. For example:
setInterval(() => {
console.log("This runs every 2 seconds");
}, 2000);
Q5: What is a template literal in JavaScript?
A5: Template literals allow for embedded expressions inside string literals using backticks (`
), like ${expression}
. Example:
let name = "John";
console.log(`Hello, ${name}!`);
Advanced Data Types and Structures
Q6: How do you clone an object in JavaScript?
A6: You can clone an object using Object.assign()
or the spread operator:
let obj1 = { name: "Alice", age: 25 };
let obj2 = { ...obj1 };
Q7: What is the difference between a shallow copy and a deep copy of an object?
A7: A shallow copy duplicates the object’s first level of properties, while a deep copy duplicates all nested objects recursively. The JSON.parse(JSON.stringify())
method can create a deep copy:
let deepCopy = JSON.parse(JSON.stringify(obj1));
Q8: What are Set
and Map
in JavaScript?
A8: Set
is a collection of unique values, while Map
stores key-value pairs where keys can be any type. Example:
let set = new Set([1, 2, 3]);
let map = new Map([["key1", "value1"], ["key2", "value2"]]);
Q9: How do you check if an object is empty in JavaScript?
A9: You can check if an object is empty using Object.keys()
:
let obj = {};
console.log(Object.keys(obj).length === 0); // true
Q10: How would you convert an array to an object in JavaScript?
A10: You can use Object.fromEntries()
to convert an array of key-value pairs into an object:
let arr = [['name', 'Alice'], ['age', 25]];
let obj = Object.fromEntries(arr);
Functions and Closures
Q11: What is a closure in JavaScript?
A11: A closure is a function that "remembers" its lexical scope even after the outer function has finished executing.
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
let counter = outer();
counter(); // 1
counter(); // 2
Q12: How do you handle default parameters in JavaScript?
A12: Default parameters can be set by assigning a value in the function declaration:
function greet(name = "Guest") {
console.log(`Hello, ${name}`);
}
greet(); // "Hello, Guest"
Q13: Can you explain the concept of higher-order functions in JavaScript?
A13: Higher-order functions are functions that take other functions as arguments or return them as output. Example:
function applyFunction(arr, func) {
return arr.map(func);
}
let result = applyFunction([1, 2, 3], x => x * 2); // [2, 4, 6]
Q14: What are anonymous functions in JavaScript?
A14: Anonymous functions are functions without a name, often used as arguments to other functions:
setTimeout(function() {
console.log("This is an anonymous function.");
}, 1000);
Q15: What is the difference between call()
, apply()
, and bind()
in JavaScript?
A15: These are methods to control the value of this
in functions:
call()
calls the function immediately with arguments.apply()
calls the function immediately but takes an array of arguments.bind()
returns a new function with the specifiedthis
value.
function greet() {
console.log(`Hello, ${this.name}`);
}
let person = { name: "Alice" };
greet.call(person); // "Hello, Alice"
Asynchronous JavaScript
Q16: What is the difference between synchronous and asynchronous JavaScript?
A16: Synchronous code is executed line by line, blocking further execution, while asynchronous code allows other code to run while waiting for operations like I/O or network requests.
Q17: What is a Promise
in JavaScript?
A17: A Promise
represents a value that may not be available yet but will be resolved in the future. Example:
let promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Success!");
} else {
reject("Error!");
}
});
promise.then(result => console.log(result)).catch(error => console.log(error));
Q18: What is the async/await
syntax used for?
A18: async/await
allows writing asynchronous code in a more synchronous-looking manner, making it easier to read and manage:
async function fetchData() {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
}
Q19: What is the Event Loop
in JavaScript?
A19: The event loop manages the execution of code, handling both synchronous and asynchronous tasks. It checks if the call stack is empty, then processes messages in the event queue.
Q20: What are callbacks in JavaScript?
A20: A callback is a function passed as an argument to another function that is executed after some operation completes:
function fetchData(callback) {
setTimeout(() => {
callback("Data fetched!");
}, 2000);
}
fetchData((message) => {
console.log(message); // "Data fetched!"
});
ES6 and Beyond
Q21: What are arrow functions in JavaScript, and how do they differ from regular functions?
A21: Arrow functions are a concise way to write functions, and they inherit this
from the surrounding context. Example:
const add = (a, b) => a + b;
Q22: What is the purpose of const
and let
in JavaScript?
A22: const
is used for values that shouldn't change, while let
is used for variables that can be reassigned. const
variables cannot be reassigned, but their properties can be modified if they are objects.
Q23: What is destructuring in JavaScript?
A23: Destructuring allows unpacking values from arrays or properties from objects into distinct variables:
let person = { name: "Alice", age: 25 };
let { name, age } = person;
Q24: What are template literals in JavaScript?
A24: Template literals are strings enclosed in backticks (`
) that allow embedding expressions with ${}
:
let name = "Alice";
let greeting = `Hello, ${name}!`;
Q25: What are the benefits of using Map
and Set
over regular objects and arrays?
A25: Map
allows any data type as keys, while Set
only stores unique values. They are more efficient for certain use cases, such as when order matters in Map
, or uniqueness is required in Set
.
Error Handling
Q26: How do you handle errors in JavaScript?
A26: Use try
, catch
, and finally
blocks to catch exceptions and handle errors:
try {
let result = riskyFunction();
} catch (error) {
console.log("Error:", error);
} finally {
console.log("This runs no matter what.");
}
Q27: What is the purpose of the throw
statement in JavaScript?
A27: The throw
statement is used to create custom errors by throwing an exception, which can then be caught by a try/catch
block:
throw new Error("Something went wrong!");
Q28: What is a TypeError
in JavaScript?
A28: A TypeError
occurs when a value is not of the expected type. For example, calling a method on an undefined or null value would result in a TypeError
:
let obj = null;
obj.method(); // TypeError
Q29: What is the difference between a SyntaxError
and a ReferenceError
?
A29: A SyntaxError
occurs when the code structure is invalid (e.g., missing parentheses), while a ReferenceError
occurs when a non-existent variable is accessed.
Q30: How do you debug JavaScript code?
A30: You can use console.log()
to output variable values or use the browser's developer tools to set breakpoints and step through the code.
JavaScript Performance
Q31: What is the use of localStorage
and sessionStorage
?
A31: localStorage
stores data persistently across sessions, while sessionStorage
stores data for the duration of a single page session.
Q32: How do you optimize JavaScript performance?
A32: Optimize JavaScript performance by minimizing DOM manipulation, using efficient loops, and debouncing or throttling events like scroll and resize.
Q33: What is debouncing
in JavaScript?
A33: Debouncing is a technique to limit the rate at which a function is executed, often used for handling events like scrolling or key presses to avoid unnecessary re-execution.
Q34: How do you avoid memory leaks in JavaScript?
A34: Memory leaks can be avoided by removing event listeners, clearing intervals or timeouts, and avoiding unnecessary global variables.
Q35: What are WeakMap
and WeakSet
?
A35: WeakMap
and WeakSet
are similar to Map
and Set
, but their entries do not prevent garbage collection. This means they allow objects to be garbage collected if there are no other references to them.
Functional Programming
Q36: What is functional programming in JavaScript?
A36: Functional programming emphasizes immutability, first-class functions, and higher-order functions. It encourages using pure functions, avoiding side effects, and composing functions.
Q37: What are pure functions in JavaScript?
A37: A pure function always produces the same output for the same input and does not modify any external state.
Q38: What is map()
in functional programming?
A38: map()
is a higher-order function that applies a given function to each element of an array and returns a new array.
Q39: What is filter()
in JavaScript?
A39: filter()
is a method that creates a new array with all elements that pass a given condition (predicate function).
Q40: What is reduce()
in JavaScript?
A40: reduce()
is a method that applies a function to accumulate a single value from all elements of an array, based on a provided callback
Asynchronous JavaScript (Continued)
Q41: What is the difference between setTimeout()
and setInterval()
in JavaScript?
A41: setTimeout()
executes a function once after a specified delay, while setInterval()
executes a function repeatedly at fixed intervals.
setTimeout(() => console.log("Executed once after 2 seconds"), 2000);
setInterval(() => console.log("Executed every 2 seconds"), 2000);
Q42: What is the async
keyword used for in JavaScript?
A42: The async
keyword is used to define a function that returns a Promise
. It allows the use of await
inside it to simplify asynchronous code.
async function fetchData() {
const response = await fetch('https://api.example.com');
const data = await response.json();
console.log(data);
}
Q43: How does the await
keyword work?
A43: await
pauses the execution of an async
function until the Promise
it is waiting for resolves, allowing you to work with asynchronous code as if it were synchronous.
Q44: Can you explain the concept of a "Promise chain"?
A44: A Promise chain is a sequence of .then()
methods that allow you to handle asynchronous tasks sequentially, one after another:
fetchData()
.then(response => processData(response))
.then(processedData => saveData(processedData))
.catch(error => console.log("Error:", error));
Q45: What is the difference between Promise.all()
and Promise.race()
?
A45: Promise.all()
waits for all promises to resolve, while Promise.race()
resolves as soon as the first promise resolves or rejects.
Promise.all([promise1, promise2]).then(results => console.log(results));
Promise.race([promise1, promise2]).then(result => console.log(result));
JavaScript Closures and Scope
Q46: What is lexical scoping in JavaScript?
A46: Lexical scoping means that a variable's scope is determined by where the function is defined, not where it is called.
Q47: What is the purpose of IIFE (Immediately Invoked Function Expressions) in JavaScript?
A47: IIFE is a function that is executed immediately after being defined, often used to create a private scope for variables to avoid polluting the global scope.
(function() {
let privateVariable = "I am private";
console.log(privateVariable);
})();
Q48: Can you explain closures with an example?
A48: A closure allows a function to retain access to its lexical scope even after the outer function has executed.
function outer() {
let counter = 0;
return function inner() {
counter++;
console.log(counter);
};
}
let increment = outer();
increment(); // 1
increment(); // 2
Q49: What is a "callback hell," and how do you avoid it?
A49: "Callback hell" refers to deeply nested callback functions, making code hard to maintain. It can be avoided by using Promises
, async/await
, or modularizing the code.
Q50: What is the difference between local and global scope in JavaScript?
A50: Variables declared in the global scope are accessible from anywhere, whereas variables in a local scope (inside functions or blocks) are only accessible within that scope.
JavaScript Modules
Q51: What are ES6 Modules in JavaScript?
A51: ES6 Modules allow for splitting JavaScript code into separate files. The import
and export
keywords help in organizing code.
// export.js
export const name = "Alice";
// import.js
import { name } from './export.js';
Q52: What is the difference between import
and require
?
A52: import
is used for ES6 modules (static imports), while require
is used for CommonJS modules (dynamic imports) in Node.js.
Q53: Can you explain named and default exports in ES6?
A53: Named exports allow you to export multiple values from a module, while a default export is used when only one value is exported.
// Named export
export const name = "Alice";
// Default export
export default function greet() { console.log("Hello!"); }
Q54: How would you import everything from a module?
A54: Use the * as
syntax to import all exports from a module.
import * as moduleName from './module.js';
Q55: Can you dynamically import a module in JavaScript?
A55: Yes, you can use import()
to load modules dynamically, returning a Promise
.
import('./module.js').then(module => {
module.someFunction();
});
Error Handling and Debugging
Q56: How do you handle asynchronous errors in JavaScript?
A56: Asynchronous errors are handled using try/catch
blocks with async/await
, or using .catch()
with Promises.
Q57: What is a try...catch
block used for?
A57: try...catch
is used to handle exceptions that may occur during the execution of a block of code, preventing the entire application from crashing.
try {
let result = riskyFunction();
} catch (error) {
console.log("An error occurred:", error);
}
Q58: What are finally
blocks in JavaScript?
A58: The finally
block runs code after try...catch
execution, regardless of whether an error occurred or not. It's often used for cleanup.
Q59: How do you throw custom errors in JavaScript?
A59: You can throw custom errors using the throw
statement.
throw new Error("Something went wrong!");
Q60: How can you debug JavaScript code using the browser's developer tools?
A60: Open the browser’s developer tools (F12), go to the "Console" tab for logs, or use the "Sources" tab to set breakpoints and step through code line by line.
JavaScript Functions
Q61: What is the difference between a function declaration and a function expression?
A61: A function declaration defines a function with a name, while a function expression defines a function as part of an expression, which can be anonymous.
// Function declaration
function greet() { console.log("Hello!"); }
// Function expression
const greet = function() { console.log("Hello!"); };
Q62: What is the use of the arguments
object in JavaScript?
A62: The arguments
object holds all the arguments passed to a function, but it is not available in arrow functions.
function sum() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
Q63: What are default parameters in JavaScript functions?
A63: Default parameters allow you to specify a default value for a function parameter when no value is passed.
function greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}
Q64: Can you explain the concept of function hoisting in JavaScript?
A64: Function declarations are hoisted to the top of their scope, meaning you can call them before they are defined.
greet(); // Outputs "Hello!"
function greet() {
console.log("Hello!");
}
Q65: How do you use a bind()
method in JavaScript?
A65: bind()
creates a new function with the this
value set to the provided value.
const person = { name: "John" };
const greet = function() {
console.log(`Hello, ${this.name}`);
};
const boundGreet = greet.bind(person);
boundGreet(); // Outputs "Hello, John"
JavaScript Scope & Closures
Q66: What is the difference between block scope and function scope in JavaScript?
A66: Block scope exists within curly braces {}
, whereas function scope applies within a function. let
and const
have block scope, while var
has function scope.
Q67: How do closures work in JavaScript?
A67: A closure occurs when a function retains access to its lexical scope (variables) even after the function has finished executing.
function outer() {
let counter = 0;
return function inner() {
counter++;
console.log(counter);
};
}
let counterFunction = outer();
counterFunction(); // Outputs 1
counterFunction(); // Outputs 2
Q68: What is the lexical scoping principle in JavaScript?
A68: Lexical scoping means that variables are accessible within the scope where they are defined, not where they are called.
Q69: How can you avoid a closure memory leak in JavaScript?
A69: You can avoid closure memory leaks by ensuring that closures don't hold unnecessary references to large objects or DOM elements after they are no longer needed.
Q70: What is the "this" keyword in JavaScript, and how does it work?
A70: The this
keyword refers to the object the function is a method of, or the global object if used in a non-method function. Its value depends on how the function is called.
JavaScript OOP (Object-Oriented Programming)
Q71: How do you create a class in JavaScript?
A71: You can create a class using the class
keyword introduced in ES6.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound`);
}
}
const dog = new Animal("Buddy");
dog.speak(); // Outputs "Buddy makes a sound"
Q72: What are the key features of Object-Oriented Programming (OOP) in JavaScript?
A72: Key features of OOP include encapsulation, inheritance, polymorphism, and abstraction. JavaScript uses prototypes and classes for inheritance.
Q73: What is the difference between class
and constructor
in JavaScript?
A73: class
is a blueprint for creating objects, while constructor
is a special method within a class used to initialize the object.
Q74: What is inheritance in JavaScript OOP?
A74: Inheritance allows one object to inherit properties and methods from another object. This is achieved using prototypes or the extends
keyword in classes.
class Dog extends Animal {
speak() {
console.log(`${this.name} barks`);
}
}
const dog = new Dog("Buddy");
dog.speak(); // Outputs "Buddy barks"
Q75: What is polymorphism in JavaScript?
A75: Polymorphism is the ability of different objects to respond to the same method name, each in its own way.
JavaScript OOP (Continued)
Q76: What is encapsulation in JavaScript?
A76: Encapsulation is the concept of bundling data (properties) and methods that operate on the data within a single unit, or class. It helps to protect the internal state of an object from unauthorized access.
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
let speed = 0; // Private property
this.accelerate = function() {
speed += 10;
console.log(`Speed: ${speed}`);
};
this.getSpeed = function() {
return speed;
};
}
}
const car = new Car("Tesla", "Model S");
car.accelerate(); // Speed: 10
console.log(car.getSpeed()); // 10
Q77: What is the super
keyword used for in JavaScript?
A77: super
is used to call methods or access properties from a parent class in a subclass.
class Animal {
speak() {
console.log("Animal makes a sound");
}
}
class Dog extends Animal {
speak() {
super.speak(); // Call the parent class method
console.log("Dog barks");
}
}
const dog = new Dog();
dog.speak();
// Outputs:
// Animal makes a sound
// Dog barks
Q78: Can you explain the concept of method overriding in JavaScript?
A78: Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.
class Animal {
speak() {
console.log("Animal makes a sound");
}
}
class Dog extends Animal {
speak() {
console.log("Dog barks");
}
}
const dog = new Dog();
dog.speak(); // Outputs "Dog barks"
Q79: What are getter and setter methods in JavaScript?
A79: Getter and setter methods are used to access and modify the properties of an object, often providing a way to control how a property is read or written.
class Rectangle {
constructor(width, height) {
this._width = width;
this._height = height;
}
get area() {
return this._width * this._height;
}
set width(value) {
this._width = value;
}
set height(value) {
this._height = value;
}
}
const rect = new Rectangle(5, 10);
console.log(rect.area); // 50
rect.width = 8;
console.log(rect.area); // 80
Q80: What is a prototype in JavaScript?
A80: A prototype is an object that every JavaScript object inherits methods and properties from. It is used to implement inheritance and shared functionality.
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
const person = new Person("Alice");
person.greet(); // "Hello, my name is Alice"
JavaScript DOM (Document Object Model)
Q81: What is the Document Object Model (DOM)?
A81: The DOM is an interface that represents the structure of HTML documents as a tree, where each element is a node, and it allows JavaScript to manipulate the content and structure of web pages.
Q82: How do you select an HTML element using JavaScript?
A82: You can select elements using methods like getElementById()
, querySelector()
, getElementsByClassName()
, or querySelectorAll()
.
let element = document.getElementById("myElement");
let divs = document.querySelectorAll("div");
Q83: What is event delegation in JavaScript?
A83: Event delegation is a technique in which you attach a single event listener to a parent element instead of multiple listeners on child elements. This improves performance and handles dynamically added elements.
document.querySelector("#parent").addEventListener("click", function(event) {
if (event.target && event.target.matches("button.classname")) {
// Handle button click
}
});
Q84: How can you change the text content of an element in JavaScript?
A84: Use the textContent
or innerText
property to change the text of an element.
document.getElementById("myElement").textContent = "New text!";
Q85: What is the difference between textContent
and innerHTML
?
A85: textContent
returns or sets the plain text content of an element, while innerHTML
returns or sets the HTML content, including tags.
element.textContent = "Hello"; // Sets plain text
element.innerHTML = "<p>Hello</p>"; // Sets HTML content
Q86: How can you add a class to an element in JavaScript?
A86: Use the classList.add()
method to add a class to an element.
document.getElementById("myElement").classList.add("new-class");
Q87: How do you handle events in JavaScript?
A87: Use the addEventListener()
method to attach an event listener to an element.
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
Q88: What is the stopPropagation()
method used for in JavaScript events?
A88: stopPropagation()
prevents an event from propagating (bubbling) up or down the DOM tree.
document.getElementById("child").addEventListener("click", function(event) {
event.stopPropagation();
});
Q89: What is the preventDefault()
method in JavaScript?
A89: preventDefault()
prevents the default action of an event from being triggered. It's often used with form submissions or anchor tags.
document.getElementById("form").addEventListener("submit", function(event) {
event.preventDefault();
console.log("Form submission prevented");
});
Q90: How do you create an element dynamically in JavaScript?
A90: Use the document.createElement()
method to create a new element and appendChild()
to insert it into the DOM.
let newDiv = document.createElement("div");
newDiv.textContent = "Hello, world!";
document.body.appendChild(newDiv);
JavaScript Advanced Topics
Q91: What is a JavaScript module bundler?
A91: A module bundler like Webpack, Parcel, or Rollup combines multiple JavaScript files into a single output file, enabling better optimization and modularity of code.
Q92: What is the purpose of Promise.resolve()
and Promise.reject()
?
A92: Promise.resolve()
creates a resolved promise, and Promise.reject()
creates a rejected promise. Both are useful for handling values or errors in asynchronous code
let resolved = Promise.resolve("Success");
let rejected = Promise.reject("Error");
Q93: What is the difference between null
and undefined
in JavaScript?
A93: null
is an intentional assignment of a null value to a variable, while undefined
indicates that a variable has been declared but has not been assigned a value.
Q94: What is destructuring in JavaScript?
A94: Destructuring allows you to extract values from arrays or objects and assign them to variables in a more concise way.
const person = { name: "Alice", age: 25 };
const { name, age } = person; // Destructuring
Q95: What is the spread operator in JavaScript?
A95: The spread operator (...
) is used to spread elements from an array or properties from an object into another array or object.
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // Spread elements from arr1
Q96: What are template literals in JavaScript?
A96: Template literals allow you to embed expressions inside strings using backticks () and
${}` syntax.
const name = "Alice";
const greeting = `Hello, ${name}!`; // Template literal
Q97: What is the reduce()
method in JavaScript?
A97: reduce()
applies a function against an accumulator and each element of an array (from left to right) to reduce it to a single value.
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 10
Q98: What is localStorage
and sessionStorage
in JavaScript?
A98: Both localStorage
and sessionStorage
are used to store data in the browser. localStorage
persists data across sessions, while sessionStorage
is limited to the duration of the page session.
localStorage.setItem("name", "Alice");
sessionStorage.setItem("sessionID", "12345");
Q99: What is the fetch()
API in JavaScript?
A99: fetch()
is an API used to make network requests (e.g., HTTP requests). It returns a Promise
and is a modern alternative to XMLHttpRequest
.
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Q100: What are arrow functions in JavaScript?
A100: Arrow functions are a shorthand syntax for defining functions. They don't have their own this
, and they can't be used as constructors.
const sum = (a, b) => a + b;
- Get link
- X
- Other Apps
Comments
Post a Comment