1. What is JavaScript and how is it different from Java?
JavaScript is a high-level, interpreted programming language primarily used for adding interactive elements to web pages. It is lightweight, dynamically typed, and runs directly in web browsers without requiring compilation. JavaScript follows the ECMAScript standard.
Differences between Java and JavaScript:
- Purpose:
- Java is a general-purpose programming language used for backend and standalone applications.
- JavaScript is mainly used for client-side scripting to make web pages dynamic and interactive.
- Execution:
- Java requires compilation into bytecode and runs on the JVM (Java Virtual Machine).
- JavaScript is interpreted by web browsers.
- Syntax and Features:
- Java is statically typed (types are checked at compile time), while JavaScript is dynamically typed (types are determined at runtime).
- Java is class-based, whereas JavaScript is prototype-based.
2. What are JavaScript data types? Explain with examples.
JavaScript has two types of data: Primitive and Non-Primitive (Objects).
Primitive Data Types:
String: Represents textual data.
let name = "John"; // String
Number: Represents numeric values (integers and floats).
let age = 25; // Number
Boolean: Represents true or false.
let isStudent = true; // Boolean
Undefined: Represents an uninitialized variable.
let job; // Undefined
Null: Represents an intentionally empty value.
let salary = null; // Null
Symbol: Introduced in ES6, used to create unique identifiers.
let id = Symbol("id"); // Symbol
BigInt: Used to represent integers larger than 2⁵³ – 1.
let largeNumber = 123456789012345678901234567890n; // BigInt
Non-Primitive Data Types:
Object: Used to store collections of data or more complex entities.
let person = {
name: "Alice",
age: 30,
};
JavaScript is dynamic, meaning variables can change their types during runtime.
3. Explain the concept of ‘hoisting’ in JavaScript.
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed. However, only declarations are hoisted, not initializations.
Example:
console.log(x); // Output: undefined
var x = 10;
In the above example, var x; is hoisted to the top, but the assignment x = 10 remains in place. So, the code is interpreted as:
var x;
console.log(x); // undefined
x = 10;
Key Points:
Variables declared using let and const are also hoisted but are not initialized until their declaration is encountered. Accessing them before initialization results in a ReferenceError.
console.log(y); // ReferenceError
let y = 5;
Function declarations are fully hoisted, meaning they can be called before their actual declaration:
greet(); // Output: "Hello!"
function greet() {
console.log("Hello!");
}
4. What is the difference between let, const and var?
In JavaScript, let, const and var are used for variable declarations, but they have significant differences in scope and mutability.
1. var:
Scope: Function-scoped (accessible only within the function in which it is declared).
Hoisting: Declarations are hoisted and initialized with undefined.
Can be re-declared and updated.
var x = 10;
var x = 20; // Re-declaration allowed
x = 30; // Update allowed
2. let:
Scope: Block-scoped (accessible only within the enclosing block { }).
Hoisting: Declarations are hoisted but remain uninitialized (temporal dead zone).
Cannot be re-declared but can be updated.
let y = 15;
// let y = 25; // SyntaxError: Identifier 'y' has already been declared
y = 35; // Update allowed
3. const:
Scope: Block-scoped.
Hoisting: Behaves like let but must be initialized during declaration.
Cannot be re-declared or updated.
const z = 50;
// z = 60; // TypeError: Assignment to constant variable.
Example Comparison:
function testScope() {
if (true) {
var a = 10; // Function-scoped
let b = 20; // Block-scoped
const c = 30; // Block-scoped
}
console.log(a); // 10
// console.log(b); // ReferenceError: b is not defined
// console.log(c); // ReferenceError: c is not defined
}
testScope();
5. What is the difference between == and === in JavaScript?
Both == and === are comparison operators, but they behave differently:
1. == (Equality Operator):
- Compares values after type coercion (conversion of operands to a common type).
- Example:
console.log(5 == "5"); // true (String "5" is converted to Number 5)
2. === (Strict Equality Operator):
- Compares values without type coercion, ensuring that both value and type are the same.
- Example:
console.log(5 === "5"); // false (Number 5 and String "5" are not the same type)
Why Use ===:
Using === is considered best practice as it avoids unexpected results caused by type coercion.
Example Comparison:
console.log(0 == false); // true (Type coercion: 0 is treated as false)
console.log(0 === false); // false (No coercion: Different types)
6. What are JavaScript closures? Explain with an example.
A closure is a function that has access to its own scope, the scope of the outer function, and the global scope, even after the outer function has returned. Closures are created every time a function is defined inside another function.
Example:
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log(`Outer Variable: ${outerVariable}`);
console.log(`Inner Variable: ${innerVariable}`);
};
}
const closureFunc = outerFunction("Hello");
closureFunc("World");
Output:
Outer Variable: Hello
Inner Variable: World
Here, innerFunction forms a closure by retaining access to outerVariable, even after outerFunction has executed.
Use Case of Closures:
- Maintaining state in asynchronous functions.
- Implementing private variables.
7. What is the difference between undefined and null in JavaScript?
Both undefined and null represent absence of a value, but they have key differences:
Undefined:
- Indicates that a variable has been declared but has not been assigned a value.
- Example:
let x;
console.log(x); // undefined
Null:
- Represents the intentional absence of a value (empty or null).
- Example:
let y = null;
console.log(y); // null
Comparison:
console.log(undefined == null); // true (type coercion)
console.log(undefined === null); // false (strict equality, different types)
8. What are JavaScript promises? Explain with an example.
A promise in JavaScript represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises have three states:
- Pending: The operation is still ongoing.
- Fulfilled: The operation was successful, and a value is available.
- Rejected: The operation failed, and an error is available.
Example:
const fetchData = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Data fetched successfully!");
} else {
reject("Failed to fetch data.");
}
});
fetchData
.then((message) => console.log(message)) // Executes on success
.catch((error) => console.error(error)); // Executes on failure
9. What are arrow functions in JavaScript? How are they different from regular functions?
Arrow functions, introduced in ES6, provide a concise syntax for writing functions. They are anonymous and do not have their own this or arguments.
Syntax:
const add = (a, b) => a + b;
console.log(add(5, 3)); // 8
Differences from Regular Functions:
this Binding:
- Arrow functions inherit this from their surrounding context. Regular functions have their own this.
function regularFunc() {
console.log(this); // Refers to the calling object
}
const arrowFunc = () => {
console.log(this); // Inherits `this` from parent
};
Syntax:
- Arrow functions are more concise, especially for one-liners.
- Regular functions require the function keyword.
10. What is the difference between synchronous and asynchronous programming in JavaScript?
Synchronous Programming:
- Tasks are executed one at a time, in sequence.
- Blocking: One task must complete before the next starts.Example:
console.log("Start");
console.log("End");
Output:
Start
End
Asynchronous Programming:
- Tasks can run concurrently without blocking subsequent tasks. Common in I/O operations like fetching data or reading files. Example:
console.log("Start");
setTimeout(() => console.log("Async Task"), 2000);
console.log("End");
Output:
Start
End
Async Task
Asynchronous programming in JavaScript is commonly achieved using callbacks, promises and async/await.
11. What is the event loop in JavaScript?
The event loop is a mechanism in JavaScript that handles asynchronous operations. It ensures that the non-blocking code (like callbacks and promises) is executed after the current execution stack is cleared.
Steps:
- The call stack executes synchronous code.
- Asynchronous code is sent to the Web APIs (e.g., setTimeout).
- Once complete, the callback moves to the task queue.
- The event loop checks if the call stack is empty and pushes tasks from the task queue.
Example:
console.log("Start");
setTimeout(() => console.log("Async Task"), 0);
console.log("End");
Output:
Start
End
Async Task
12. What is the difference between call(), apply(), and bind() in JavaScript?
call():
- Invokes a function with a specified this context and arguments passed individually.
- Example:
function greet(greeting) {
console.log(`${greeting}, ${this.name}`);
}
const person = { name: "Alice" };
greet.call(person, "Hello"); // Output: "Hello, Alice"
apply():
- Similar to call(), but arguments are passed as an array.
- Example:
greet.apply(person, ["Hi"]); // Output: "Hi, Alice"
bind():
- Returns a new function with a specified this context, without invoking it immediately.
- Example:
const boundGreet = greet.bind(person, "Hey");
boundGreet(); // Output: "Hey, Alice"
13. What is the difference between deep copy and shallow copy in JavaScript?
Shallow Copy:
- Copies only the first level of properties. Nested objects are still referenced.
- Example:
const obj = { a: 1, b: { c: 2 } };
const shallowCopy = { ...obj };
shallowCopy.b.c = 3;
console.log(obj.b.c); // 3
Deep Copy:
- Creates an independent copy of all levels.
- Example using JSON.parse and JSON.stringify:
const deepCopy = JSON.parse(JSON.stringify(obj));
deepCopy.b.c = 4;
console.log(obj.b.c); // 2
14. What is the difference between var, let, and const in JavaScript?
var:
- Has function-level scope or global scope (does not have block scope).
- Can be redeclared and updated.
- Hoisted to the top but initialized as undefined.
var x = 10;
var x = 20; // Redeclaration allowed
console.log(x); // 20
let:
- Has block-level scope.
- Cannot be redeclared in the same scope but can be updated.
- Hoisted but not initialized, leading to a “temporal dead zone.”
let y = 10;
// let y = 20; // Error: Cannot redeclare 'y'
y = 20; // Allowed
const:
- Has block-level scope.
- Cannot be redeclared or updated. Must be initialized during declaration.
const z = 10;
// z = 20; // Error: Assignment to constant variable
15. What is the difference between == and === in JavaScript?
== (Equality Operator):
- Compares values after performing type coercion (converting one type to another).
- Example:
console.log(5 == "5"); // true
=== (Strict Equality Operator):
- Compares values without type coercion. Both value and type must match.
- Example:
console.log(5 === "5"); // false
console.log(5 === 5); // true
16. What is the difference between map() and forEach() in JavaScript?
map():
- Returns a new array with the results of applying a callback function to each element.
- Does not modify the original array.
- Example:
const numbers = [1, 2, 3];
const doubled = numbers.map((num) => num * 2);
console.log(doubled); // [2, 4, 6]
forEach():
- Executes a callback function for each element but does not return a new array.
- Example:
const numbers = [1, 2, 3];
numbers.forEach((num) => console.log(num * 2)); // Logs 2, 4, 6
17. What is the difference between synchronous and asynchronous functions?
Synchronous Functions:
- Block the execution of code until the current task is completed.
- Example:
console.log("Start");
console.log("End");
Asynchronous Functions:
- Do not block the execution of code. They run in the background and return results when available. Example:
console.log("Start");
setTimeout(() => console.log("Async Task"), 1000);
console.log("End");
Output:
Start
End
Async Task
18. What are JavaScript objects?
A JavaScript object is a collection of key-value pairs. Keys are strings (or symbols) and values can be of any type.
Example:
const person = {
name: "Alice",
age: 25,
greet: function () {
console.log(`Hello, my name is ${this.name}`);
},
};
person.greet(); // Hello, my name is Alice
Use Case:
Objects are used to store and manipulate data as a group.
19. What are prototypes in JavaScript?
Every JavaScript object has a prototype, which is a blueprint or template object. Prototypes allow objects to inherit properties and methods from other objects.
Example:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
console.log(`Hello, my name is ${this.name}`);
};
const alice = new Person("Alice");
alice.greet(); // Hello, my name is Alice
Here, greet() is inherited from the Person prototype.
20. What is the difference between call(), apply() and bind()?
call():
- Invokes a function with a specified this value and arguments passed individually.
- Example:
function greet(greeting) {
console.log(`${greeting}, ${this.name}`);
}
const person = { name: "Alice" };
greet.call(person, "Hello"); // Hello, Alice
apply():
- Invokes a function with a specified this value and arguments passed as an array.
- Example:
greet.apply(person, ["Hi"]); // Hi, Alice
bind():
- Returns a new function with a specified this value and arguments, without invoking it.
- Example:
const boundGreet = greet.bind(person, "Hey");
boundGreet(); // Hey, Alice
21. What are closures in JavaScript?
A closure is a function that retains access to its outer (lexical) scope, even after the outer function has executed. Closures allow functions to “remember” the environment they were created in.
Example:
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log(`Outer: ${outerVariable}, Inner: ${innerVariable}`);
};
}
const closureExample = outerFunction("outside");
closureExample("inside"); // Outer: outside, Inner: inside
Explanation:
Here, innerFunction retains access to outerVariable, even after outerFunction has finished execution.
22. What is event bubbling in JavaScript?
Event bubbling is a mechanism where an event propagates from the innermost target element to the outermost elements. This means the event is first captured and handled by the target element and then by its parent elements in sequence.
Example:
document.getElementById("child").addEventListener("click", () => {
console.log("Child Clicked");
});
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent Clicked");
});
Output (when clicking the child):
Child Clicked
Parent Clicked
Note:
Event bubbling can be stopped using event.stopPropagation().
23. What is the difference between null and undefined in JavaScript?
null:
- Represents an intentional absence of value. Explicitly set by the programmer.
let a = null;
console.log(a); // null
undefined:
- Represents a value that has not been assigned. Typically returned for uninitialized variables or missing object properties.
let b;
console.log(b); // undefined
console.log({}.missingProperty); // undefined
24. What is the difference between slice() and splice() in JavaScript?
slice():
- Returns a shallow copy of a portion of an array without modifying the original array.
- Example:
const arr = [1, 2, 3, 4, 5];
const sliced = arr.slice(1, 3);
console.log(sliced); // [2, 3]
console.log(arr); // [1, 2, 3, 4, 5]
splice():
- Modifies the original array by removing or replacing elements.
- Example:
const arr = [1, 2, 3, 4, 5];
const spliced = arr.splice(1, 2); // Removes 2 elements starting from index 1
console.log(spliced); // [2, 3]
console.log(arr); // [1, 4, 5]
25. What is the difference between document.getElementById() and document.querySelector()?
getElementById():
- Selects an element by its unique id.Faster for direct id selection but limited in scope.
const element = document.getElementById("myId");
querySelector():
- Selects the first element that matches a CSS selector.More versatile, supporting classes, tags, and more.
const element = document.querySelector(".myClass");
Key Difference:
- getElementById() is faster for id selection.
- querySelector() is more flexible for various CSS selectors.
26. What is a promise in JavaScript?
A promise is an object representing the eventual completion or failure of an asynchronous operation. Promises can be in one of three states:
- Pending: Initial state.
- Fulfilled: Operation completed successfully.
- Rejected: Operation failed.
Example:
const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Promise fulfilled!");
} else {
reject("Promise rejected!");
}
});
myPromise
.then((message) => console.log(message))
.catch((error) => console.error(error));
27. What is the purpose of async and await in JavaScript?
async:
- Declares a function as asynchronous.
- Always returns a promise.
await:
- Pauses the execution of an async function until the promise is resolved or rejected.
Example:
async function fetchData() {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
}
fetchData();
28. What are JavaScript modules?
JavaScript modules are reusable pieces of code that can be exported from one file and imported into another. They promote code organization and reusability.
Example:
module.js:
export const greet = (name) => `Hello, ${name}!`;
main.js:
import { greet } from "./module.js";
console.log(greet("Alice")); // Hello, Alice!
29. What is the this keyword in JavaScript?
The this keyword refers to the object that is currently executing the code. Its value depends on the context in which it is used.
Example:
In a method:
const obj = {
name: "Alice",
greet() {
console.log(this.name);
},
};
obj.greet(); // Alice
In a standalone function:
function greet() {
console.log(this);
}
greet(); // In browsers, this refers to the global `window` object
30. What are higher-order functions in JavaScript?
A higher-order function is a function that can take other functions as arguments, return functions, or both. These are commonly used for abstraction and functional programming.
Example:
function higherOrderFunction(callback) {
callback();
}
higherOrderFunction(() => {
console.log("This is a higher-order function!");
});
Another example is map, which processes each element of an array:
const numbers = [1, 2, 3];
const squares = numbers.map((num) => num * num);
console.log(squares); // [1, 4, 9]
31. What are arrow functions in JavaScript?
Arrow functions are a shorthand syntax for writing functions. They do not have their own this context and are more concise than traditional function expressions.
Example:
Traditional function:
function sum(a, b) {
return a + b;
}
Arrow function:
const sum = (a, b) => a + b;
console.log(sum(2, 3)); // 5
32. What is the difference between call(), apply() and bind() in JavaScript?
These methods allow you to explicitly set the this value in a function.
call(): Invokes a function with a specified this and arguments provided individually.
const obj = { name: "Alice" };
function greet(greeting) {
console.log(`${greeting}, ${this.name}`);
}
greet.call(obj, "Hello"); // Hello, Alice
apply(): Similar to call(), but arguments are provided as an array.
greet.apply(obj, ["Hi"]); // Hi, Alice
bind(): Returns a new function with this bound to the specified object.
const boundGreet = greet.bind(obj, "Hey");
boundGreet(); // Hey, Alice
33. What are template literals in JavaScript?
Template literals are string literals enclosed in backticks ( ` ) that allow embedded expressions and multi-line strings.
Example:
const name = "Alice";
const greeting = `Hello, ${name}! Welcome to JavaScript.`;
console.log(greeting); // Hello, Alice! Welcome to JavaScript.
Multi-line string:
const multiLine = `This is
a multi-line
string.`;
console.log(multiLine);
34. What is the event.preventDefault() method in JavaScript?
The event.preventDefault() method is used to prevent the default action of an event, such as preventing a form submission or a link from navigating.
Example:
document.querySelector("form").addEventListener("submit", (event) => {
event.preventDefault(); // Prevents form submission
console.log("Form submission prevented.");
});
35. What is the difference between == and === in JavaScript?
== (Abstract Equality): Compares values after type conversion.
console.log(5 == "5"); // true
=== (Strict Equality): Compares values without type conversion.
console.log(5 === "5"); // false
Best Practice:
Always use === for more predictable and accurate comparisons.
36. What are JavaScript events?
JavaScript events are actions or occurrences (like user interactions) that can be handled using event listeners.
Example of common events:
Click Event:
document.getElementById("btn").addEventListener("click", () => {
console.log("Button clicked!");
});
Mouseover Event:
document.getElementById("btn").addEventListener("mouseover", () => {
console.log("Mouse is over the button!");
});
37. What is the difference between synchronous and asynchronous JavaScript?
Synchronous:
- Executes code line-by-line.Each task waits for the previous task to complete.
console.log("First");
console.log("Second");
// Output: First, Second
Asynchronous:
- Allows tasks to run independently of others.Commonly used for tasks like API calls or timers.
console.log("First");
setTimeout(() => console.log("Second"), 1000);
console.log("Third");
// Output: First, Third, Second
38. What is JSON in JavaScript?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is used for storing and transferring data between a server and a client.
Example:
const jsonString = '{"name": "Alice", "age": 25}';
const obj = JSON.parse(jsonString); // Convert JSON string to object
console.log(obj.name); // Alice
Converting an object to JSON:
const jsonObj = { name: "Bob", age: 30 };
const json = JSON.stringify(jsonObj);
console.log(json); // {"name":"Bob","age":30}
39. What is the DOM in JavaScript?
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page as a tree structure where each node is an object.
Example:
Accessing DOM elements:
const element = document.getElementById("myElement");
element.textContent = "Updated text!";
40. What is the setTimeout function in JavaScript?
The setTimeout function executes a block of code or a function after a specified delay.
Example:
setTimeout(() => {
console.log("This runs after 2 seconds");
}, 2000);
41. What is the difference between setTimeout and setInterval in JavaScript?
setTimeout: Executes a function or block of code once after a specified time delay.
setTimeout(() => {
console.log("Executed after 2 seconds");
}, 2000);
setInterval: Repeatedly executes a function or block of code at specified intervals.
setInterval(() => {
console.log("Executed every 2 seconds");
}, 2000);
42. What is the difference between null and undefined in JavaScript?
null: Represents the intentional absence of a value.
let x = null;
console.log(x); // null
undefined: Indicates that a variable has been declared but not initialized or a property doesn’t exist.
let y;
console.log(y); // undefined
console.log({}.property); // undefined
Key Difference:
- null is an assigned value, while undefined is the default.
43. What are promises in JavaScript?
A promise is an object representing the eventual completion or failure of an asynchronous operation.
Example:
const promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Promise resolved!");
} else {
reject("Promise rejected!");
}
});
promise
.then((result) => console.log(result))
.catch((error) => console.log(error));
44. What is the difference between async and await in JavaScript?
async: Declares a function as asynchronous, enabling the use of await within it.
async function fetchData() {
return "Data fetched!";
}
await: Pauses the execution of an async function until the promise resolves.
async function getData() {
const data = await fetchData();
console.log(data);
}
45. What is an Immediately Invoked Function Expression (IIFE)?
An IIFE is a function that runs immediately after it is defined. It is often used to create a private scope.
Example:
(function () {
console.log("This is an IIFE");
})();
46. What is the typeof operator in JavaScript?
The typeof operator returns the data type of a variable or value.
Example:
console.log(typeof 42); // "number"
console.log(typeof "Hello"); // "string"
console.log(typeof {}); // "object"
console.log(typeof undefined); // "undefined"
47. What are closures in JavaScript?
A closure is a function that remembers its lexical scope, even when the function is executed outside that scope.
Example:
function outerFunction() {
let count = 0;
return function innerFunction() {
count++;
console.log(count);
};
}
const counter = outerFunction();
counter(); // 1
counter(); // 2
48. What is the this keyword in JavaScript?
The this keyword refers to the object that is executing the current function. Its value depends on how the function is called.
Example:
Global Context:
console.log(this); // Window object in browsers
Object Context:
const obj = {
name: "Alice",
greet() {
console.log(this.name);
},
};
obj.greet(); // Alice
Arrow Function: Arrow functions do not have their own this and inherit it from the enclosing scope.
const arrowFunc = () => console.log(this);
arrowFunc(); // Window object
49. What is hoisting in JavaScript?
Hoisting is JavaScript’s default behavior of moving declarations (functions and variables) to the top of their scope during compilation.
Example:
console.log(a); // undefined
var a = 5;
hoistedFunction();
function hoistedFunction() {
console.log("This function is hoisted!");
}
Variables declared with let and const
are also hoisted but remain in the “temporal dead zone” until their declaration is reached.
50. What is event bubbling in JavaScript?
Event bubbling is a mechanism where an event propagates from the innermost target element up to its ancestors in the DOM hierarchy.
Example:
document.getElementById("child").addEventListener("click", () => {
console.log("Child clicked");
});
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent clicked");
});
If you click on the child element, both the child and parent event handlers will execute due to event bubbling.