04022025083955AM
04022025083955AM
1. Primitive Types:
o Number
o String
o Boolean
o Undefined
o Null
o Symbol
o BigInt
2. Non-Primitive Types:
o Object
Example:
Answer:
var:
o Function-scoped.
o Can be redeclared and updated.
o Hoisted but not block-scoped.
let:
o Block-scoped.
o Can be updated but not redeclared in the same scope.
o Hoisted but in the temporal dead zone.
const:
o Block-scoped.
o Cannot be updated or redeclared.
o The value itself is constant, but the properties of objects declared with const can be
modified.
Example:
// var
var x = 10;
var x = 20; // Allowed
console.log(x); // 20
Page 1 JavaScript
Interview Questions – Java Script
// let
let y = 30;
y = 40; // Allowed
console.log(y); // 40
// const
const z = 50;
z = 60; // Error: Assignment to constant variable.
Answer:
== (Abstract Equality): Compares values for equality, performing type conversion if necessary.
=== (Strict Equality): Compares values and types without performing type conversion.
Example:
Answer: A closure is a function that has access to its outer function’s variables, even after the outer
function has returned.
Example:
function outerFunction() {
let outerVariable = "I am from outer scope";
Answer: The event loop is a mechanism in JavaScript that ensures non-blocking operations by handling
asynchronous callbacks. It continuously checks the call stack and message queue for tasks to execute.
Key Components:
Page 2 JavaScript
Interview Questions – Java Script
Example:
console.log("Start");
setTimeout(() => {
console.log("Async Task");
}, 0);
console.log("End");
// Output:
// Start
// End
// Async Task
Answer: A promise is an object that represents the eventual completion (or failure) of an asynchronous
operation.
States of a Promise:
Example:
if (success) {
resolve("Promise fulfilled");
} else {
reject("Promise rejected");
}
});
promise
.then((result) => console.log(result)) // Output: Promise fulfilled
.catch((error) => console.error(error));
Page 3 JavaScript
Interview Questions – Java Script
Answer: async and await are used to handle asynchronous code in a more readable and sequential
manner.
Example:
fetchData();
Answer:
undefined: A variable that has been declared but not assigned a value.
null: Represents the intentional absence of a value.
Example:
let a;
console.log(a); // Output: undefined
let b = null;
console.log(b); // Output: null
Answer:
Example:
// map
Page 4 JavaScript
Interview Questions – Java Script
// filter
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // Output: [2, 4]
// reduce
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // Output: 15
Answer: Arrow functions are a shorthand syntax for writing functions. They do not have their own this
context and cannot be used as constructors.
Example:
// Regular function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
console.log(add(2, 3)); // Output: 5
Answer: JavaScript is a lightweight, interpreted programming language primarily used for adding
interactivity to web pages. Java, on the other hand, is a compiled, object-oriented programming
language used for building platform-independent applications. JavaScript runs in the browser, while
Java can run on servers and desktop applications.
Answer: Promises are objects that represent the eventual completion or failure of an asynchronous
operation. They can be in one of three states: pending, fulfilled, or rejected.
Page 5 JavaScript
Interview Questions – Java Script
Example:
promise
.then((result) => console.log(result))
.catch((error) => console.error(error));
Answer: Event delegation is a technique in which a single event listener is added to a parent element to
handle events for its child elements. It takes advantage of event bubbling.
Example:
Answer:
Example:
Page 6 JavaScript
Interview Questions – Java Script
Answer: Use the event.preventDefault() method to prevent the default behavior of an event (e.g.,
stopping a form submission).
Example:
Question 18: What is the difference between synchronous and asynchronous programming?
Answer:
Synchronous: Tasks are executed sequentially, blocking further execution until the current task
completes.
Asynchronous: Tasks are executed without blocking, allowing the program to continue running
while waiting for a task to complete.
Answer: Higher-order functions are functions that take other functions as arguments or return them as
results.
Example:
function higherOrderFunction(callback) {
callback();
}
Answer: Hoisting is JavaScript's behavior of moving variable and function declarations to the top of
their scope before execution.
Example:
console.log(x); // undefined
var x = 5;
Answer: Modules are reusable pieces of code that can be exported from one file and imported into
another using export and import keywords.
Page 7 JavaScript
Interview Questions – Java Script
Example:
// module.js
export const greet = () => console.log("Hello");
// main.js
import { greet } from "./module.js";
greet();
Question 22: What is the purpose of the async and await keywords?
Answer: The async keyword is used to declare a function that returns a Promise. The await keyword is
used inside an async function to pause execution until the Promise is resolved.
Example:
Example:
try {
const result = riskyOperation();
} catch (error) {
console.error("An error occurred:", error);
}
Answer:
Question 26: How can you manipulate the DOM using JavaScript?
Page 8 JavaScript
Interview Questions – Java Script
Answer: Use DOM methods like getElementById, querySelector, appendChild, and removeChild to
manipulate DOM elements.
Answer:
The event loop is a mechanism that handles the execution of multiple pieces of code, such as
asynchronous callbacks. It continuously checks the call stack and the message queue. If the
call stack is empty, it pushes the first task from the message queue to the stack for execution.
It is responsible for managing asynchronous operations.
Question 28: What is the difference between microtasks and macrotasks in JavaScript?
Answer:
Microtasks include operations like Promises and MutationObserver. They are executed
immediately after the currently executing task completes and before macrotasks.
Macrotasks include setTimeout, setInterval, and setImmediate. They are queued in the
message queue and executed only after microtasks are completed.
Question 29: What is garbage collection in JavaScript, and how does it work?
Answer:
Garbage collection is the process of reclaiming memory that is no longer being used. In
JavaScript, this is done automatically using algorithms like mark-and-sweep, where objects no
longer reachable from the root are marked as garbage and cleared.
Answer:
Currying is a technique of transforming a function with multiple arguments into a sequence of
functions, each taking a single argument.
function multiply(a) {
return function (b) {
return a * b;
};
}
const multiplyByTwo = multiply(2);
console.log(multiplyByTwo(3)); // Output: 6
Question 31: What is the difference between DOMContentLoaded and load events?
Answer:
o DOMContentLoaded: Fired when the initial HTML document is completely loaded and
parsed, without waiting for stylesheets, images, and subframes.
o load: Fired when the entire page, including all dependent resources (like images and
stylesheets), has loaded.
Question 32: How do you prevent Cross-Site Scripting (XSS) attacks in JavaScript?
Page 9 JavaScript
Interview Questions – Java Script
Answer:
o Sanitize user inputs using libraries like DOMPurify.
o Use textContent instead of innerHTML when updating DOM elements.
o Implement Content Security Policy (CSP) headers to restrict the sources of scripts.
Answer:
o Throttling: Limits the execution of a function to once in a specified time frame.
o Debouncing: Ensures a function is executed only after a specified pause time since the
last call.
Example of Debouncing:
Question 34: What are CORS issues, and how do you handle them?
Answer:
Cross-Origin Resource Sharing (CORS) issues occur when a web page from one domain tries to
access resources on another domain without proper authorization.
To resolve:
o Use proper CORS headers on the server (Access-Control-Allow-Origin).
o Enable credentials sharing if required.
o Use JSONP or server-side proxies as alternatives.
Question 35: What is the Singleton Pattern, and how do you implement it in JavaScript?
Answer:
The Singleton Pattern ensures a class has only one instance and provides a global point of
access to it.
Example:
Page 10 JavaScript
Interview Questions – Java Script
Answer:
o Fetch:
Returns a Promise, making it easier to handle asynchronous requests.
Simplified API compared to XMLHttpRequest.
Does not support progress events.
o XMLHttpRequest:
More complex and older API.
Supports progress events and synchronous requests.
Page 11 JavaScript