Basic JavaScript
Basic JavaScript
17. What are arrow functions? How are they different from regular functions?
Intermediate JavaScript
28. What is the difference between function declaration and function expression?
31. What are Map and Set in JavaScript? How are they different from objects?
33. What is the difference between shallow copy and deep copy?
DOM Manipulation
Advanced JavaScript
ES6+ Features
Asynchronous JavaScript
Interview-Focused
114. How would you find the maximum occurring character in a string?
Miscellaneous
Extra Questions
Answer:
JavaScript is a lightweight, interpreted programming language used primarily to create interactive and
dynamic content on websites. It is often used for client-side scripting but can also be used server-side
with environments like Node.js.
• JavaScript: Interpreted, dynamically typed, and primarily used for web development.
JavaScript is not related to Java except for its name.
Answer:
JavaScript has two main categories of data types:
• Primitive Data Types: String, Number, Boolean, Undefined, Null, Symbol, BigInt.
• Non-Primitive (Object) Data Types: Object (including Arrays, Functions, and other objects).
Answer:
• var:
o Function-scoped.
• let:
o Block-scoped.
• const:
o Block-scoped.
o Cannot be reassigned.
4. What is undefined vs null in JavaScript?
Answer:
• undefined:
A variable that has been declared but not initialized. It indicates the absence of a value.
• null:
Represents an explicitly assigned absence of value. It’s an object type.
Example:
javascript
Copy code
let x; // undefined
Answer:
The isNaN function checks whether a value is NaN (Not-a-Number). If the value is not a number or
cannot be converted to a number, it returns true.
Example:
javascript
Copy code
isNaN('abc'); // true
isNaN(123); // false
Answer:
JavaScript’s primitive data types are:
Answer:
• === (Strict Equality): Compares both value and type without type coercion.
Example:
javascript
Copy code
Answer:
• Global Variables: Variables that are accessible throughout the program (in all scopes).
• Declaration: Declare a variable outside any function or use window object explicitly.
Example:
javascript
Copy code
Answer:
A closure is a function that retains access to its outer scope's variables, even after the outer function has
returned.
Example:
javascript
Copy code
function outerFunction() {
};
Answer:
The typeof operator returns the type of a given variable or value as a string.
Example:
javascript
Copy code
Answer:
An IIFE is a function that is executed immediately after it is defined. It is commonly used to create a
private scope and avoid polluting the global namespace.
Example:
javascript
Copy code
(function () {
console.log("IIFE executed!");
})();
Answer:
Template literals are string literals enclosed in backticks (`) and allow embedded expressions using the
${expression} syntax. They support multi-line strings and string interpolation.
Example:
javascript
Copy code
Answer:
JavaScript is dynamically typed, meaning variables are not bound to a specific data type. A variable’s type
can change at runtime based on the value assigned to it.
Example:
javascript
Copy code
Answer:
Example:
javascript
Copy code
console.log(`${greeting}, ${this.name}${punctuation}`);
Answer:
An event is an action or occurrence detected by the browser, such as a user clicking a button, moving the
mouse, or typing on the keyboard. Events allow developers to define responses to user interactions.
Example:
javascript
Copy code
document.querySelector("button").addEventListener("click", () => {
console.log("Button clicked!");
});
Answer:
• Event Bubbling: Events propagate from the target element to its ancestors (inner to outer
elements).
• Event Capturing: Events propagate from the outermost ancestor to the target element (outer to
inner elements).
Example:
javascript
Copy code
document.querySelector("#parent").addEventListener("click", () => {
document.querySelector("#child").addEventListener("click", () => {
17. What are arrow functions? How are they different from regular functions?
Answer:
Arrow functions are a concise syntax for writing functions introduced in ES6. They do not have their own
this context, making them useful in scenarios where this should refer to the enclosing scope.
Differences:
• No this binding.
Example:
javascript
Copy code
};
Answer:
this refers to the object that is executing the current function.
• In the global context, this refers to the window object (in browsers).
Example:
javascript
Copy code
function globalThis() {
const obj = {
method: function () {
},
};
obj.method();
Answer:
Example:
javascript
Copy code
let x;
console.log(x); // undefined
Answer:
An object in JavaScript is a collection of key-value pairs, where keys are strings (or Symbols) and values
can be any data type, including functions.
Example:
javascript
Copy code
const obj = {
name: "John",
age: 30,
greet: function () {
},
};
console.log(obj.name); // John
Answer:
Prototypal inheritance allows objects to inherit properties and methods from another object. Every
JavaScript object has an internal property called [[Prototype]], which links it to another object.
Example:
javascript
Copy code
Answer:
JavaScript handles asynchronous operations using:
• Async/Await: Simplifies working with promises for writing asynchronous code in a synchronous
style.
• Event Loop: Ensures asynchronous code runs after the current stack of code execution
completes.
Answer:
A Promise represents a value that may be available now, in the future, or never. It is used to handle
asynchronous operations more effectively.
States of a Promise:
Example:
javascript
Copy code
});
promise.then(console.log).catch(console.error);
24. What is the difference between for...in and for...of?
Answer:
Example:
javascript
Copy code
const obj = { a: 1, b: 2 };
console.log(value); // 1, 2, 3
Answer:
Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their scope
before code execution.
Example:
javascript
Copy code
console.log(a); // undefined
var a = 10;
greet(); // "Hello!"
function greet() {
console.log("Hello!");
Answer:
The event loop is a mechanism that allows JavaScript to perform non-blocking operations by offloading
tasks (like I/O operations) to the browser and executing them once the call stack is empty.
Steps:
3. The event loop checks if the call stack is empty, then executes tasks from the queues.
27. What are JavaScript modules, and how do you use them?
Answer:
JavaScript modules allow you to divide code into reusable pieces using export and import.
Usage:
javascript
Copy code
// module.js
javascript
Copy code
28. What is the difference between function declaration and function expression?
Answer:
javascript
Copy code
function greet() {
console.log("Hello!");
javascript
Copy code
console.log("Hello!");
};
javascript
Copy code
greet(); // Works
function greet() {
console.log("Hello!");
console.log("Hi!");
};
Answer:
1. Using Object.assign():
javascript
Copy code
const obj = { a: 1, b: 2 };
javascript
Copy code
javascript
Copy code
javascript
Copy code
Answer:
javascript
Copy code
const obj = { a: 1, b: 2 };
javascript
Copy code
console.log(jsonObject); // { a: 1, b: 2 }
31. What are Map and Set in JavaScript? How are they different from objects?
Answer:
• Map: A collection of key-value pairs where keys can be any type (object, primitive, etc.).
1. Map:
2. Set:
Examples:
javascript
Copy code
// Map example
map.set('a', 1);
map.set(2, 'b');
console.log(map.get(2)); // "b"
// Set example
console.log(set); // Set { 1, 2, 3 }
Answer:
Destructuring allows you to extract values from arrays or properties from objects and assign them to
variables.
Examples:
javascript
Copy code
// Array destructuring
console.log(a, b); // 1, 2
// Object destructuring
const { x, y } = obj;
// Nested destructuring
console.log(inner); // 42
33. What is the difference between shallow copy and deep copy?
Answer:
• Shallow Copy: Copies the first level of properties. Nested objects or arrays are still referenced.
Example:
javascript
Copy code
const obj = { a: 1, b: { c: 2 } };
shallow.b.c = 3;
console.log(obj.b.c); // 3 (referenced)
javascript
Copy code
deep.b.c = 4;
console.log(obj.b.c); // 2 (independent)
Answer:
Symbol is a unique and immutable primitive data type. It’s used to create unique property keys to avoid
name collisions.
Example:
javascript
Copy code
obj[sym1] = 'value1';
console.log(obj[sym1]); // "value1"
Answer:
• Synchronous Code: Executes line by line, blocking subsequent code until the current operation
completes.
• Asynchronous Code: Allows other operations to execute while waiting for a task to complete.
Example:
javascript
Copy code
// Synchronous
console.log('Start');
console.log('End');
// Asynchronous
console.log('Start');
console.log('End');
Answer:
Custom events are created using the CustomEvent constructor and triggered using dispatchEvent.
Example:
javascript
Copy code
console.log(e.detail.message); // "Hello!"
});
document.dispatchEvent(customEvent);
Example:
javascript
Copy code
try {
console.log(data);
} catch (error) {
console.error(error);
fetchData();
Answer:
Currying is a technique of transforming a function with multiple arguments into a sequence of functions,
each taking a single argument.
Example:
javascript
Copy code
function add(a) {
return a + b;
};
}
console.log(add5(3)); // 8
Answer:
Default parameters allow you to set default values for function arguments if no value is provided.
Example:
javascript
Copy code
console.log(`Hello, ${name}!`);
Answer:
javascript
Copy code
console.log(...arr); // 1 2 3
const obj = { a: 1, b: 2 };
console.log(newObj); // { a: 1, b: 2, c: 3 }
• Rest Operator (...): Gathers the rest of the values into an array or object.
Example:
javascript
Copy code
function sum(...numbers) {
console.log(sum(1, 2, 3)); // 6
Answer:
The Document Object Model (DOM) is a programming interface for web documents. It represents the
structure of a webpage as a tree of objects, allowing JavaScript to manipulate HTML and CSS
dynamically.
Example:
javascript
Copy code
Answer:
You can use the following methods to select elements:
javascript
Copy code
javascript
Copy code
javascript
Copy code
Answer:
• innerHTML: Retrieves or sets the HTML content inside an element (including tags).
javascript
Copy code
• innerText: Retrieves or sets the visible text inside an element, considering CSS styles (e.g.,
display: none is excluded).
javascript
Copy code
• textContent: Retrieves or sets the raw text inside an element (ignores CSS styling).
javascript
Copy code
Answer:
javascript
Copy code
newElement.textContent = 'Hello!';
document.body.appendChild(newElement);
javascript
Copy code
newElement.style.color = 'blue';
javascript
Copy code
Answer:
addEventListener is used to attach an event listener to an element. It allows multiple listeners for the
same event and supports additional options like capture.
Syntax:
javascript
Copy code
Example:
javascript
Copy code
button.addEventListener('click', () => {
console.log('Button clicked!');
});
Answer:
• stopPropagation: Prevents the event from propagating to parent elements in the DOM
hierarchy.
javascript
Copy code
event.stopPropagation();
});
• preventDefault: Prevents the default action associated with the event (e.g., stopping form
submission or link navigation).
javascript
Copy code
event.preventDefault();
});
Answer:
You can traverse using properties like:
Example:
javascript
Copy code
Answer:
Dataset attributes allow you to store custom data in HTML elements using data-* attributes. Access
them using element.dataset.
Example:
html
Copy code
javascript
Copy code
console.log(div.dataset.userId); // "123"
console.log(div.dataset.role); // "admin"
Answer:
• classList.add: Adds a single class or multiple classes to an element without affecting existing
classes.
javascript
Copy code
element.classList.add('new-class');
javascript
Copy code
Answer:
Form events like submit, change, and input can be handled using addEventListener.
Example:
javascript
Copy code
console.log('Form submitted!');
});
});
Answer:
• Object.freeze:
javascript
Copy code
• Object.seal:
javascript
Copy code
obj.a = 2; // Allowed
Answer:
• Debounce: Limits the rate at which a function is executed. It delays execution until after a
specified time since the last call. Useful for search input or resize events.
javascript
Copy code
let timeout;
clearTimeout(timeout);
};
• Throttle: Ensures a function is called at most once every specified interval, regardless of how
often it's triggered. Useful for scroll or mousemove events.
javascript
Copy code
let lastCall = 0;
lastCall = now;
func.apply(this, args);
};
Example:
javascript
Copy code
// worker.js
self.postMessage(result);
};
// main.js
Answer:
reduce() applies a function to an accumulator and each array element, reducing the array to a single
value.
Syntax:
javascript
Copy code
array.reduce(callback, initialValue);
Example:
javascript
Copy code
const nums = [1, 2, 3, 4];
console.log(sum); // 10
Answer:
• WeakMap: A map where keys are objects, and they are weakly referenced, allowing garbage
collection.
Example:
javascript
Copy code
weakMap.set(obj, 'info');
Answer:
Object.create() creates a new object with the specified prototype object and optional properties.
Example:
javascript
Copy code
Answer:
The garbage collector automatically removes objects from memory that are no longer reachable.
• Mark-and-Sweep Algorithm: Identifies objects that are not reachable from the root (e.g., global
variables) and frees their memory.
Example:
javascript
Copy code
let obj = { a: 1 };
Answer:
Memoization is an optimization technique that caches the results of expensive function calls to avoid
redundant computations.
Example:
javascript
Copy code
function memoize(func) {
cache[key] = result;
return result;
};
}
Answer:
Exceptions are handled using try...catch blocks.
Example:
javascript
Copy code
try {
} catch (error) {
console.error(error.message);
} finally {
console.log('Execution complete');
Answer:
Dynamic imports allow importing modules at runtime using the import() function. This is useful for code
splitting and lazy loading.
Example:
javascript
Copy code
import('./module.js')
.then((module) => {
module.default(); // Call the default export
})
Answer:
javascript
Copy code
console.log(arr); // [1, 2, 3]
• Immutable Data: Cannot be changed after creation. Any "modification" creates a new value
(e.g., strings, numbers).
javascript
Copy code
Answer:
javascript
Copy code
javascript
Copy code
const id = setInterval(() => console.log("Repeating every second"), 1000);
Timers rely on the event loop, where the callback is queued after the delay.
Answer:
The Temporal Dead Zone (TDZ) refers to the time between entering a scope and declaring a variable
with let or const. During this period, accessing the variable results in a ReferenceError.
Example:
javascript
Copy code
console.log(x); // ReferenceError
Answer:
Recursion is a function calling itself until a base condition is met. JavaScript uses the call stack to manage
recursive calls.
Example:
javascript
Copy code
function factorial(n) {
console.log(factorial(5)); // 120
Example:
javascript
Copy code
const handler = {
get: (target, prop) => (prop in target ? target[prop] : `No such property`),
};
console.log(obj.a); // 1
Answer:
The Reflect API provides methods for performing operations on objects, similar to those used with Proxy
handlers.
Example:
javascript
Copy code
const obj = { a: 1 };
console.log(Reflect.get(obj, 'b')); // 2
Benefits:
Answer:
Decorators are special functions used to modify or enhance classes and their methods. They are part of
the proposed ES decorators feature.
Example (Using a decorator library):
javascript
Copy code
descriptor.writable = false;
return descriptor;
class Example {
@readonly
sayHello() {
return "Hello!";
Answer:
• Avoid memory leaks: Clear unused references and use WeakMap/WeakSet where applicable.
• Efficient loops: Use native array methods like map and reduce instead of for loops when
applicable.
Answer:
Event delegation is a technique where a single event listener is attached to a parent element to handle
events for its child elements. It relies on event bubbling.
Example:
javascript
Copy code
});
Advantages:
Answer:
• Iterators: Objects that implement the next() method, returning { value, done } pairs.
Example:
javascript
Copy code
• Generators: Special functions defined with function* that can pause and resume execution using
yield.
Example:
javascript
Copy code
function* generator() {
yield 1;
yield 2;
yield 3;
}
const gen = generator();
Answer:
• let:
o Allows reassignment.
javascript
Copy code
let x = 10;
x = 20; // Allowed
• const:
javascript
Copy code
const y = 10;
y = 20; // Error
Answer:
Destructuring simplifies extracting values from arrays or properties from objects into variables.
javascript
Copy code
const [a, b] = [1, 2];
console.log(a, b); // 1, 2
javascript
Copy code
const { x, y } = obj;
Answer:
Default parameters allow assigning default values to function arguments if no value or undefined is
provided.
Example:
javascript
Copy code
Answer:
Template literals provide an easier way to create strings, supporting multi-line strings and embedding
expressions.
javascript
Copy code
Answer:
Arrow functions are a concise syntax for defining functions. They do not bind their own this context,
making them useful in callbacks.
Syntax:
javascript
Copy code
console.log(add(2, 3)); // 5
Key Points:
• Shorter syntax.
Answer:
Variables declared with let and const are block-scoped, meaning they are only accessible within the
block {} in which they are defined.
Example:
javascript
Copy code
let x = 10;
const y = 20;
Example:
javascript
Copy code
console.log(mySet); // Set { 1, 2, 3 }
mySet.add(4);
console.log(mySet.has(4)); // true
Answer:
for...of iterates over iterable objects like arrays, strings, maps, and sets.
Example (Array):
javascript
Copy code
console.log(num); // 1, 2, 3
Example (String):
javascript
Copy code
console.log(char); // h, e, l, l, o
Answer:
Feature import require
Example (import):
javascript
Copy code
func();
Example (require):
javascript
Copy code
func();
Answer:
Promise.all() runs multiple promises in parallel and resolves when all promises are resolved. If one
promise rejects, it rejects immediately.
Syntax:
javascript
Copy code
console.log(results);
});
Example:
javascript
Copy code
const p1 = Promise.resolve(10);
const p2 = Promise.resolve(20);
});
Answer:
async/await provide a more synchronous-like structure to asynchronous code, making it easier to read
and understand compared to traditional promise chains (.then(), .catch()).
• async: Declares a function that returns a promise. Inside this function, you can use await.
• await: Pauses the execution of the function until the promise resolves or rejects.
Example:
Without async/await:
javascript
Copy code
fetchData().then(data => {
console.log(data);
}).catch(error => {
console.log(error);
});
With async/await:
javascript
Copy code
try {
console.log(data);
} catch (error) {
console.log(error);
}
}
Using async/await makes asynchronous code look like synchronous code, improving readability.
Answer:
Promise.race() accepts an iterable of promises and resolves as soon as the first promise resolves or
rejects. It "races" the promises and returns the result of the first one to settle.
Example:
javascript
Copy code
In this example, Promise.race() resolves as soon as p1 resolves, even though p2 takes longer.
Answer:
• Object.entries(): Converts an object's properties into an array of [key, value] pairs. Example:
javascript
Copy code
const obj = { a: 1, b: 2 };
javascript
Copy code
const obj = { a: 1, b: 2 };
• Array Example:
javascript
Copy code
• Object Example:
javascript
Copy code
const obj = { a: 1, b: 2 };
The spread operator can also be used to pass individual elements of an array as arguments to a function.
Answer:
Tagged template literals allow you to customize how template literals are processed. A tag function is
used to process the template literal before returning a final result.
Example:
javascript
Copy code
});
return result;
}
const name = 'Alice';
In this example, the highlight function processes the template literal and wraps the variable name with
<b> tags.
Answer:
A callback function is a function passed as an argument to another function, which is then executed at a
later time. It is typically used for asynchronous operations to handle results once the operation
completes.
Example:
javascript
Copy code
function fetchData(callback) {
setTimeout(() => {
callback('Data received');
}, 1000);
fetchData((data) => {
});
Answer:
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation. A
promise can be in one of three states:
Example:
javascript
Copy code
if (success) {
resolve("Operation succeeded");
} else {
reject("Operation failed");
});
Answer:
Promise chaining allows multiple asynchronous operations to be executed one after the other. Each
.then() in the chain returns a new promise.
Example:
javascript
Copy code
fetchData()
.then(data => {
return processData(data);
})
.then(processedData => {
console.log(processedData); // "Data processed"
return saveData(processedData);
})
.then(() => {
console.log("Data saved");
})
.catch(error => {
console.log("Error:", error);
});
Each .then() processes the data from the previous one, and if any promise is rejected, the .catch() block
will handle the error.
Answer:
The fetch() API is a modern way to make HTTP requests (GET, POST, etc.) in JavaScript. It returns a
Promise that resolves to the Response object representing the response to the request.
Example:
javascript
Copy code
fetch('https://api.example.com/data')
Answer:
• fetch:
o Does not use Promises, requiring callback functions for asynchronous handling.
Example (fetch):
javascript
Copy code
fetch('/data')
Example (XMLHttpRequest):
javascript
Copy code
xhr.onload = () => {
console.log(JSON.parse(xhr.responseText));
};
xhr.send();
Answer:
Under the hood, async/await works with Promises. When an async function is called, it returns a
Promise. Inside an async function, when the await keyword is used, it pauses the function's execution
until the Promise resolves or rejects, and then continues with the resolved value or throws an error if
rejected.
2. await pauses the function execution and waits for the Promise to resolve.
3. The resolved value is returned and execution continues after the await.
Example:
javascript
Copy code
return data.json();
javascript
Copy code
function getData() {
Answer:
The finally() method is used to execute code after a promise has been resolved or rejected, regardless of
the outcome. It is useful for cleanup tasks, like closing connections or hiding loading indicators, after the
promise operation.
Example:
javascript
Copy code
fetch('https://api.example.com')
Answer:
JavaScript operates on a single thread by using the event loop. The event loop processes events and
executes code in a queue, ensuring that only one task is processed at a time.
• Asynchronous operations (like setTimeout, fetch, and promises) are pushed into the event
queue.
• The event loop checks the call stack and moves tasks from the event queue to the stack when it's
empty.
Answer:
Errors in asynchronous code can be handled using:
javascript
Copy code
try {
} catch (error) {
console.log('Error:', error);
}
}
javascript
Copy code
fetch('https://api.example.com')
Both methods ensure that errors from failed promises or rejected async functions can be handled
gracefully.
Answer:
The window object represents the global environment in a web browser. It is the top-level object in the
browser's JavaScript execution environment and provides methods and properties for interacting with
the browser. It includes functions for manipulating the DOM, handling events, managing cookies, and
interacting with the browser's history, location, and more.
Example:
javascript
Copy code
Answer:
• localStorage:
o It has no expiration time and remains until explicitly cleared by the user or via JavaScript.
o Data stored in sessionStorage is available only during the page session. Once the
browser or tab is closed, the data is cleared.
o It also stores data per domain but only for the current session.
Example:
javascript
Copy code
// localStorage
localStorage.setItem('username', 'Alice');
// sessionStorage
sessionStorage.setItem('sessionID', '12345');
Answer:
• Cookies:
o Cookies are small pieces of data (up to 4KB) stored by the browser and sent to the server
with every HTTP request.
o They have an expiration date and can be set with a specific domain, path, and secure
flags.
• localStorage:
o localStorage can store larger amounts of data (5MB or more) than cookies.
o Data in localStorage is not automatically sent to the server with each request.
o It persists until explicitly deleted and is not tied to a specific expiration date.
Answer:
The navigator object provides information about the browser, such as the browser name, version,
platform, language, and whether the user has enabled certain features like cookies or JavaScript.
Example:
javascript
Copy code
Answer:
DOM manipulation in JavaScript involves using methods and properties of the document object to
interact with and modify the structure of a webpage. Common operations include selecting elements,
changing content, adding/removing elements, and responding to user events.
Examples:
• Selecting an element:
javascript
Copy code
• Changing content:
javascript
Copy code
javascript
Copy code
document.body.appendChild(newElement);
Answer:
The history API allows you to interact with the browser's session history, enabling you to modify the URL
and navigate through the history stack without reloading the page. It includes methods like pushState(),
replaceState(), and go().
Example:
javascript
Copy code
// Go back in history
history.go(-1);
Answer:
The location object provides information about the current URL and allows you to manipulate it. You can
use it to navigate to different pages, reload the page, or get specific parts of the URL (e.g., hostname,
pathname).
Example:
javascript
Copy code
Answer:
JavaScript handles browser events using event listeners. An event listener waits for a specific event (e.g.,
click, input, load) and triggers a function when the event occurs.
Example:
javascript
Copy code
button.addEventListener('click', function() {
alert('Button clicked!');
});
Answer:
The fetch() API is used to make HTTP requests in JavaScript. It returns a Promise that resolves to the
Response object, representing the response to the request. fetch() is often used for loading data from a
server asynchronously.
Example:
javascript
Copy code
fetch('https://api.example.com/data')
Answer:
• Synchronous requests: The code execution waits for the request to complete before moving to
the next task. This can block the execution of other code and make the page unresponsive.
Example: (Not recommended for I/O operations)
javascript
Copy code
console.log(data);
• Asynchronous requests: The code continues to run while waiting for the request to complete,
preventing the page from freezing. Asynchronous requests are commonly handled using
callbacks, promises, or async/await.
Example:
javascript
Copy code
getDataAsynchronously().then(data => {
console.log(data);
});
Answer:
The Singleton design pattern ensures that a class has only one instance and provides a global access
point to that instance. It is commonly used for managing shared resources like configuration settings or
databases.
Example:
javascript
Copy code
let instance;
function createInstance() {
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
return instance;
};
})();
Answer:
Functional programming is a programming paradigm that treats computation as the evaluation of
mathematical functions, avoiding changing state and mutable data. Core principles include immutability,
pure functions, and higher-order functions.
Example:
Using a pure function:
javascript
Copy code
console.log(add(2, 3)); // 5
javascript
Copy code
function reverseString(str) {
return str.split('').reverse().join('');
console.log(reverseString("hello")); // "olleh"
Answer:
Using the Set object:
javascript
Copy code
console.log(uniqueArray); // [1, 2, 3, 4]
Answer:
javascript
Copy code
function flattenArray(arr) {
return arr.flat(Infinity);
javascript
Copy code
function isPalindrome(str) {
console.log(isPalindrome("madam")); // true
console.log(isPalindrome("hello")); // false
Answer:
Debouncing ensures that a function is not called repeatedly within a short time. It delays the function
execution until after a specified wait time has elapsed.
Example:
javascript
Copy code
let timeout;
clearTimeout(timeout);
};
log();
113. Write a JavaScript function to find the factorial of a number.
Answer:
javascript
Copy code
function factorial(n) {
console.log(factorial(5)); // 120
114. How would you find the maximum occurring character in a string?
Answer:
javascript
Copy code
function maxChar(str) {
charMap[char] = (charMap[char] || 0) + 1;
max = charMap[char];
maxChar = char;
return maxChar;
}
console.log(maxChar("javascript")); // "a"
Answer:
Using JSON.parse and JSON.stringify:
javascript
Copy code
const obj = { a: 1, b: { c: 2 } };
javascript
Copy code
Answer:
Using the spread operator:
javascript
Copy code
console.log(merged); // [1, 2, 3, 4]
Answer:
javascript
Copy code
function shuffleArray(arr) {
return arr;
console.log(shuffleArray([1, 2, 3, 4, 5]));
Answer:
• .map(): Returns a new array with the results of applying a function to each element.
• .forEach(): Executes a function for each element but does not return a new array.
Example:
javascript
Copy code
Answer:
javascript
Copy code
result.push(callback(this[i], i, this));
}
return result;
};
Answer:
javascript
Copy code
Answer:
Promises in JavaScript represent the eventual completion (or failure) of an asynchronous operation and
its resulting value. They are used to avoid callback hell and make code more readable.
Example:
javascript
Copy code
Answer:
javascript
Copy code
promise
Answer:
"use strict"; enables strict mode, which helps catch common coding errors and unsafe actions (like using
undeclared variables).
Example:
javascript
Copy code
"use strict";
Answer:
Tail call optimization refers to the process where the JavaScript engine optimizes a function call made in
the tail position (last action of a function) to prevent stack growth, enabling recursive functions to run
efficiently.
javascript
Copy code
if (!Array.prototype.includes) {
};
Answer:
A transpiler converts modern JavaScript code (e.g., ES6+) into backward-compatible code for older
browsers. Examples include Babel and TypeScript.
Answer:
Answer:
Using try, catch, and finally blocks:
javascript
Copy code
try {
console.error(error.message);
} finally {
console.log("Cleanup actions");
Answer:
Answer:
Using the Performance API:
javascript
Copy code
// Perform task
Answer:
AJAX (Asynchronous JavaScript and XML) allows web pages to update asynchronously without reloading
the entire page. It uses XMLHttpRequest or the fetch() API.
Answer:
• Reflow: When the layout of a web page changes (e.g., adding elements).
• Repaint: When visual properties like color change without affecting layout.
Answer:
Using various methods:
javascript
Copy code
console.log("Log");
console.warn("Warning");
console.error("Error");
console.time("Timer");
// Code
console.timeEnd("Timer");
Answer:
A Service Worker is a script that runs in the background, independent of the web page, enabling
features like offline caching and push notifications.
Answer:
• defer: Executes the script after the HTML document has been parsed.
Answer:
1. Lexical analysis
2. Syntax analysis
3. Bytecode generation
4. Execution
Answer:
Answer:
Answer:
WebSockets provide full-duplex communication between the browser and server over a persistent
connection.
Answer:
It creates an instance of an object from a constructor function.
Answer:
javascript
Copy code
Answer:
The eval() function executes strings as code. It's discouraged due to performance and security risks (e.g.,
code injection).
Answer:
javascript
Copy code
console.log(formatter.format(123456)); // $123,456.00
Answer:
BigInt is a data type for integers larger than Number.MAX_SAFE_INTEGER.
javascript
Copy code
javascript
Copy code
console.log(now.toISOString());
Answer:
Polyfills are fallback scripts for unsupported features. Example:
javascript
Copy code
if (!String.prototype.includes) {
};
Answer:
Both are package managers for JavaScript. Differences:
Answer:
Event delegation allows a parent element to handle events for its child elements using event bubbling.
html
Copy code