Smart Future Point

Java Script


Interview Questions For JavaScript


1. What is the basic syntax of JavaScript?
Show Answer

Ans. The basic syntax of JavaScript consists of statements that are executed in order. A statement can be a variable declaration, a function call, or a control structure. JavaScript statements end with a semicolon (;). For example:

let x = 5; // Variable declaration
console.log(x); // Function call

2. What are the different data types in JavaScript?
Show Answer

Ans. JavaScript has several data types, which can be categorized into two groups:

  • Primitive Data Types:
    • String: Represents text, e.g., "Hello".
    • Number: Represents numeric values, e.g., 42.
    • Boolean: Represents true or false values.
    • Undefined: A variable that has been declared but not assigned a value.
    • Null: Represents the intentional absence of any object value.
    • Symbol: A unique and immutable value, introduced in ES6.
  • Reference Data Types:
    • Object: A collection of key-value pairs.
    • Array: A special type of object used to store ordered collections.

3. How do you define a function in JavaScript?
Show Answer

Ans. You can define a function in JavaScript using the function keyword. Functions can be defined in several ways, including function declarations and function expressions. For example:

function greet(name) {
    return "Hello, " + name;
}

console.log(greet("Alice")); // Outputs: Hello, Alice

4. What are the different types of loops in JavaScript?
Show Answer

Ans. JavaScript provides several types of loops for iterating over data:

  • for loop: Used to execute a block of code a specific number of times.
  • for (let i = 0; i < 5; i++) {
        console.log(i); // Outputs: 0, 1, 2, 3, 4
    }
  • while loop: Executes a block of code as long as a specified condition is true.
  • let i = 0;
    while (i < 5) {
        console.log(i);
        i++;
    }
  • do...while loop: Similar to the while loop, but it guarantees that the block of code is executed at least once.
  • let i = 0;
    do {
        console.log(i);
        i++;
    } while (i < 5);
  • for...of loop: Used to iterate over iterable objects like arrays.
  • const arr = [1, 2, 3];
    for (const value of arr) {
        console.log(value); // Outputs: 1, 2, 3
    }
  • for...in loop: Used to iterate over the properties of an object.
  • const obj = { a: 1, b: 2 };
    for (const key in obj) {
        console.log(key + ": " + obj[key]); // Outputs: a: 1, b: 2
    }

5. What is the difference between let, const, and var?
Show Answer

Ans. The differences between let, const, and var are:

  • var: Function-scoped or globally-scoped, can be re-declared and updated.
  • let: Block-scoped, can be updated but not re-declared in the same scope.
  • const: Block-scoped, cannot be updated or re-declared. It must be initialized at the time of declaration.

6. How do you handle errors in JavaScript?
Show Answer

Ans. You can handle errors in JavaScript using try...catch statements. This allows you to catch exceptions and handle them gracefully. For example:

try {
    // Code that may throw an error
    throw new Error("Something went wrong!");
} catch (error) {
    console.error(error.message); // Outputs: Something went wrong!
}

7. What is the difference between == and === in JavaScript?
Show Answer

Ans. == is the equality operator that compares values after performing type coercion. === is the strict equality operator that checks both value and type.

console.log(5 == '5'); // true
console.log(5 === '5'); // false

8. What is hoisting in JavaScript?
Show Answer

Ans. Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope. Only declarations are hoisted, not initializations.

console.log(x); // undefined
var x = 5;

9. What are closures in JavaScript?
Show Answer

Ans. A closure is a function that has access to its own scope, the scope of the outer function, and the global scope.

function outer() {
    let count = 0;
    return function inner() {
        count++;
        return count;
    };
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2

10. What is the DOM?
Show Answer

Ans. 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.


11. What are JavaScript Promises?
Show Answer

Ans. A JavaScript Promise is an object that represents the eventual completion (or failure) of an asynchronous operation. It has three states: pending, fulfilled, and rejected.

const promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("Success!"), 1000);
});

promise.then(result => console.log(result)); // Outputs: Success!

12. What is async/await in JavaScript?
Show Answer

Ans. async and await are syntactic sugar built on Promises that make asynchronous code look and behave more like synchronous code.

async function fetchData() {
    try {
        const response = await fetch("https://api.example.com");
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error(error);
    }
}

13. Explain event bubbling and capturing.
Show Answer

Ans. Event bubbling means the event propagates from the target element up to the root, while capturing (or trickling) means it goes from the root down to the target. You can control this with the third argument in addEventListener.


14. What is the difference between null and undefined?
Show Answer

Ans. undefined means a variable has been declared but not assigned a value. null is an assignment value that represents no value or object.


15. What is a callback function?
Show Answer

Ans. A callback is a function passed into another function as an argument, which is then invoked inside the outer function to complete a task.

function greet(name, callback) {
    console.log("Hello " + name);
    callback();
}

greet("Alice", () => console.log("Callback executed")); 

16. What is an Immediately Invoked Function Expression (IIFE)?
Show Answer

Ans. An IIFE is a function that runs as soon as it is defined.

(function() {
    console.log("IIFE executed!");
})();

17. How does the this keyword work in JavaScript?
Show Answer

Ans. this refers to the object from where it was called. Its value depends on the context in which it is used (global, object, strict mode, etc.).


18. What are higher-order functions?
Show Answer

Ans. Higher-order functions are functions that can take other functions as arguments or return them.

function higherOrder(fn) {
    return function(value) {
        return fn(value);
    };
}

19. What are JavaScript modules?
Show Answer

Ans. JavaScript modules allow you to split code into separate files and import/export them. This improves maintainability and reusability.

// module.js
export const greet = () => console.log("Hello");

// main.js
import { greet } from './module.js';
greet();

20. What is the difference between call(), apply(), and bind()?
Show Answer

Ans. All three methods change the context of this:

  • call(): calls the function immediately with arguments listed.
  • apply(): same as call, but arguments are passed as an array.
  • bind(): returns a new function with a bound context.


21. What is event delegation?
Show Answer

Ans. Event delegation is a technique in which a parent element handles events for its child elements using event bubbling. This is useful for dynamically added elements.

document.getElementById("parent").addEventListener("click", function(e) {
    if (e.target && e.target.matches("button.classname")) {
        console.log("Button clicked!");
    }
});

22. What are arrow functions and how are they different from regular functions?
Show Answer

Ans. Arrow functions are a shorter syntax for writing functions and do not bind their own this. They are best used for callbacks or methods that don’t require their own context.

// Regular function
function add(a, b) {
    return a + b;
}

// Arrow function
const add = (a, b) => a + b;

23. How does prototypal inheritance work?
Show Answer

Ans. In JavaScript, objects inherit from other objects via the prototype chain. This allows sharing methods and properties between objects.

const parent = {
    greet() {
        console.log("Hello from parent");
    }
};

const child = Object.create(parent);
child.greet(); // Outputs: Hello from parent

24. What is the difference between synchronous and asynchronous code?
Show Answer

Ans. Synchronous code runs line-by-line, blocking the next operation until the current one finishes. Asynchronous code can execute non-blocking operations using callbacks, promises, or async/await.


25. What is the purpose of the new keyword?
Show Answer

Ans. The new keyword creates an instance of an object with a constructor function and sets up the prototype chain.

function Person(name) {
    this.name = name;
}

const person1 = new Person("Alice");

26. What is the use of Object.freeze()?
Show Answer

Ans. Object.freeze() makes an object immutable, preventing new properties from being added or existing properties from being changed or removed.

const obj = Object.freeze({ name: "John" });
obj.name = "Doe"; // No effect

27. What are template literals?
Show Answer

Ans. Template literals are strings that allow embedded expressions and multi-line strings using backticks (`).

const name = "Alice";
const greeting = `Hello, ${name}!`;
console.log(greeting);

28. What is the spread operator and how is it used?
Show Answer

Ans. The spread operator (...) expands elements of an iterable (like an array) into individual elements.

const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // [1, 2, 3, 4, 5]

29. What is destructuring in JavaScript?
Show Answer

Ans. Destructuring is a syntax that allows unpacking values from arrays or properties from objects into distinct variables.

// Array destructuring
const [a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2

// Object destructuring
const person = { name: "Alice", age: 25 };
const { name, age } = person;
console.log(name); // Alice
console.log(age); // 25

30. What are the different ways to create objects in JavaScript?
Show Answer

Ans. There are several ways to create objects in JavaScript:

  • Using object literal:
  • const obj = { name: "Alice" };
  • Using the new Object() syntax:
  • const obj = new Object();
    obj.name = "Alice";
  • Using a constructor function:
  • function Person(name) {
        this.name = name;
    }
    const person = new Person("Alice");
  • Using Object.create():
  • const parent = { greet() { console.log("Hello"); } };
    const child = Object.create(parent);
    child.greet(); // Hello
  • Using class syntax (ES6):
  • class Person {
        constructor(name) {
            this.name = name;
        }
    }
    const p = new Person("Alice");

31. What is the difference between == and === in JavaScript?
Show Answer

Ans. == compares values after type conversion (loose equality), while === compares both value and type (strict equality).

console.log(5 == "5");  // true
console.log(5 === "5"); // false

32. What is a JavaScript Promise?
Show Answer

Ans. A Promise represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

const promise = new Promise((resolve, reject) => {
    resolve("Success");
});
promise.then(result => console.log(result));

33. What is the difference between null and undefined?
Show Answer

Ans. null is an assigned value representing no value, while undefined means a variable has been declared but not assigned a value.

let a;
console.log(a); // undefined
let b = null;
console.log(b); // null

34. What is the use of the spread operator?
Show Answer

Ans. The spread operator (...) allows an iterable to be expanded into individual elements.

const arr = [1, 2, 3];
const newArr = [...arr, 4, 5];
console.log(newArr); // [1, 2, 3, 4, 5]

35. What is hoisting in JavaScript?
Show Answer

Ans. Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope.

console.log(a); // undefined
var a = 5;

36. What is a callback function?
Show Answer

Ans. A callback function is passed as an argument to another function and is executed after the completion of that function.

function greet(name, callback) {
    console.log("Hello " + name);
    callback();
}
greet("Alice", () => console.log("Callback called!"));

37. What is the difference between let, const, and var?
Show Answer

Ans. var is function-scoped, while let and const are block-scoped. const cannot be reassigned.

var x = 10;
let y = 20;
const z = 30;

38. What is event bubbling in JavaScript?
Show Answer

Ans. Event bubbling is a type of event propagation where the event starts from the deepest element and propagates up to the parent elements.

element.addEventListener('click', function() {
    console.log('Clicked!');
}, false);

39. What are arrow functions?
Show Answer

Ans. Arrow functions provide a concise syntax for writing functions and do not have their own this.

const add = (a, b) => a + b;
console.log(add(2, 3)); // 5

40. What is the purpose of the bind() method?
Show Answer

Ans. The bind() method creates a new function with a specified this value.

const obj = { name: "Alice" };
function greet() {
    console.log(this.name);
}
const boundGreet = greet.bind(obj);
boundGreet(); // Alice

41. What is the DOM?
Show Answer

Ans. The DOM (Document Object Model) is a programming interface for HTML and XML documents. It represents the page structure as a tree of objects.


42. What is a closure in JavaScript?
Show Answer

Ans. A closure is a function that retains access to its lexical scope even when executed outside that scope.

function outer() {
    let x = 10;
    return function inner() {
        console.log(x);
    };
}
const fn = outer();
fn(); // 10

43. What are template literals?
Show Answer

Ans. Template literals are strings enclosed in backticks (`) that allow embedded expressions using ${}.

const name = "Alice";
console.log(`Hello, ${name}`);

44. What is async/await in JavaScript?
Show Answer

Ans. async and await are used to handle asynchronous operations in a more readable and synchronous-looking way.

async function getData() {
    let data = await fetch('url');
    console.log(data);
}

45. What is the difference between slice() and splice()?
Show Answer

Ans. slice() returns a shallow copy of an array, while splice() modifies the original array.

let arr = [1, 2, 3, 4];
arr.slice(1, 3);  // [2, 3]
arr.splice(1, 2); // [2, 3], arr becomes [1, 4]

46. What is the use of the typeof operator?
Show Answer

Ans. The typeof operator returns a string indicating the type of a variable.

console.log(typeof "Hello"); // string
console.log(typeof 5);       // number

47. What is an Immediately Invoked Function Expression (IIFE)?
Show Answer

Ans. An IIFE is a function that runs as soon as it is defined.

(function() {
    console.log("IIFE executed");
})();

48. What are higher-order functions in JavaScript?
Show Answer

Ans. Higher-order functions are functions that take other functions as arguments or return functions as results.

function greet(fn) {
    fn();
}
greet(() => console.log("Hello!"));

49. What is the difference between map() and forEach()?
Show Answer

Ans. map() returns a new array with the results, while forEach() executes a function but returns undefined.

const arr = [1, 2, 3];
const mapped = arr.map(x => x * 2); // [2, 4, 6]
arr.forEach(x => console.log(x));   // Logs 1 2 3

50. What is the difference between function declaration and function expression?
Show Answer

Ans. Function declarations are hoisted, while function expressions are not.

// Function Declaration
function greet() {
    return "Hello";
}

// Function Expression
const greet = function() {
    return "Hello";
};

51. What is the event delegation in JavaScript?
Show Answer

Ans. Event delegation refers to the practice of attaching a single event listener to a parent element to handle events for child elements.

document.querySelector("#parent").addEventListener('click', function(event) {
    if (event.target && event.target.matches("button.classname")) {
        console.log("Button clicked");
    }
});

52. What is the purpose of the this keyword in JavaScript?
Show Answer

Ans. The this keyword refers to the context in which a function is called. It can refer to an object, global context, or the calling function itself.

function greet() {
    console.log(this);
}
const obj = { greet };
obj.greet();  // 'this' refers to 'obj'

53. What are the differences between synchronous and asynchronous code in JavaScript?
Show Answer

Ans. Synchronous code runs sequentially, blocking further execution until the current task completes. Asynchronous code allows other operations to run while waiting for an operation to complete.

// Synchronous
console.log("Start");
console.log("End");

// Asynchronous
console.log("Start");
setTimeout(() => console.log("End"), 1000);

54. What is the purpose of the call() method in JavaScript?
Show Answer

Ans. The call() method allows a function to be invoked with a specified this value and arguments passed individually.

function greet(name) {
    console.log(`Hello, ${name}`);
}
greet.call(null, "Alice"); // Hello, Alice

55. What is a JavaScript generator function?
Show Answer

Ans. A generator function is a function that can be paused and resumed, using the yield keyword to produce a sequence of values.

function* numbers() {
    yield 1;
    yield 2;
    yield 3;
}
const gen = numbers();
console.log(gen.next().value); // 1

56. What is the purpose of the setTimeout() method?
Show Answer

Ans. The setTimeout() method is used to execute a function after a specified delay (in milliseconds).

setTimeout(() => {
    console.log("Executed after 2 seconds");
}, 2000);

57. What is the use of the eval() function?
Show Answer

Ans. The eval() function evaluates JavaScript code represented as a string.

eval("console.log('Hello from eval')");

58. What is the difference between localStorage and sessionStorage in JavaScript?
Show Answer

Ans. localStorage stores data with no expiration time, whereas sessionStorage stores data for the duration of the page session.

localStorage.setItem("key", "value");
sessionStorage.setItem("key", "value");

59. What is a JavaScript module?
Show Answer

Ans. A module in JavaScript is a file that contains code which can be exported and imported to use in other files.

// module.js
export const greet = () => "Hello";
// main.js
import { greet } from './module';
console.log(greet());

60. What is the difference between let and var in JavaScript?
Show Answer

Ans. let is block-scoped and does not allow redeclaration in the same scope, while var is function-scoped and allows redeclaration.

let a = 10;
var b = 20;
console.log(a, b);

61. How do you handle errors in JavaScript?
Show Answer

Ans. Errors can be handled using try...catch blocks. The finally block can be used to execute code regardless of success or failure.

try {
    throw new Error("Something went wrong");
} catch (error) {
    console.log(error.message);
} finally {
    console.log("Always runs");
}

62. What are default parameters in JavaScript?
Show Answer

Ans. Default parameters allow you to set default values for function parameters if no value or undefined is passed.

function greet(name = "World") {
    console.log(`Hello, ${name}`);
}
greet(); // Hello, World

63. What is a promise chain?
Show Answer

Ans. A promise chain is a sequence of promise handlers that are executed in order, where each handler returns a new promise.

fetch('/data')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.log(error));

64. What is the purpose of the Object.assign() method?
Show Answer

Ans. Object.assign() is used to copy values from one or more source objects to a target object.

const obj1 = { a: 1 };
const obj2 = { b: 2 };
const merged = Object.assign({}, obj1, obj2);
console.log(merged); // { a: 1, b: 2 }

65. What is destructuring in JavaScript?
Show Answer

Ans. Destructuring allows unpacking values from arrays or properties from objects into distinct variables.

const person = { name: "Alice", age: 25 };
const { name, age } = person;
console.log(name, age); // Alice 25

66. What are regular expressions in JavaScript?
Show Answer

Ans. Regular expressions are patterns used to match character combinations in strings.

const regex = /\d+/;
console.log(regex.test("123")); // true

67. What is the setInterval() method in JavaScript?
Show Answer

Ans. The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).

setInterval(() => {
    console.log("Executed every 1 second");
}, 1000);

68. What is the purpose of the clearTimeout() and clearInterval() methods?
Show Answer

Ans. clearTimeout() clears a timeout set with setTimeout(), and clearInterval() clears an interval set with setInterval().

const timeout = setTimeout(() => console.log("Hello"), 1000);
clearTimeout(timeout);

69. What is the purpose of the apply() method in JavaScript?
Show Answer

Ans. The apply() method calls a function with a specified this value and an array of arguments.

function greet(name) {
    console.log(`Hello, ${name}`);
}
greet.apply(null, ["Alice"]); // Hello, Alice

70. What is the difference between == and Object.is() in JavaScript?
Show Answer

Ans. == compares values after type conversion, while Object.is() compares values without type conversion.

console.log(0 == -0); // true
console.log(Object.is(0, -0)); // false

71. What is an IIFE (Immediately Invoked Function Expression) in JavaScript?
Show Answer

Ans. An IIFE is a function that is defined and invoked immediately after its creation. It's typically used to create a private scope.

(function() {
    console.log("I am an IIFE");
})();

72. What is the purpose of the bind() method in JavaScript?
Show Answer

Ans. The bind() method creates a new function that, when invoked, has its this value set to the provided value, and prepends the given arguments to the function.

function greet(name) {
    console.log(`Hello, ${name}`);
}
const greetAlice = greet.bind(null, "Alice");
greetAlice(); // Hello, Alice

73. What is closure in JavaScript?
Show Answer

Ans. A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope.

function outer() {
    let count = 0;
    return function inner() {
        count++;
        console.log(count);
    };
}
const counter = outer();
counter(); // 1
counter(); // 2

74. What is the event loop in JavaScript?
Show Answer

Ans. The event loop is a mechanism that continuously checks if the call stack is empty and, if so, pushes messages from the event queue to the stack for execution.

console.log("Start");
setTimeout(() => console.log("Inside Timeout"), 0);
console.log("End");

75. What is the purpose of the new keyword in JavaScript?
Show Answer

Ans. The new keyword is used to create a new instance of a constructor function or class.

function Person(name) {
    this.name = name;
}
const john = new Person("John");
console.log(john.name); // John

76. What are template literals in JavaScript?
Show Answer

Ans. Template literals are a way to define strings with embedded expressions. They are defined using backticks (`) and support multi-line strings and string interpolation.

const name = "Alice";
console.log(`Hello, ${name}`); // Hello, Alice

77. What is the purpose of the spread operator in JavaScript?
Show Answer

Ans. The spread operator (...) is used to unpack elements from an array or properties from an object into a new array or object.

const arr = [1, 2, 3];
const newArr = [...arr, 4, 5];
console.log(newArr); // [1, 2, 3, 4, 5]

78. What is the difference between undefined and null in JavaScript?
Show Answer

Ans. undefined indicates that a variable has been declared but not assigned a value, while null is a value that represents the intentional absence of any object value.

let x;
console.log(x); // undefined
let y = null;
console.log(y); // null

79. What is the purpose of the Object.freeze() method?
Show Answer

Ans. The Object.freeze() method prevents modification of an object, including adding, deleting, or modifying its properties.

const obj = { a: 1 };
Object.freeze(obj);
obj.a = 2;
console.log(obj.a); // 1

80. What is the difference between function declarations and function expressions in JavaScript?
Show Answer

Ans. Function declarations are hoisted to the top of their scope, while function expressions are not. Function expressions are created and assigned at runtime.

function declaration() { console.log("declaration"); } // Hoisted
const expression = function() { console.log("expression"); }; // Not hoisted

81. What is the difference between a shallow copy and a deep copy in JavaScript?
Show Answer

Ans. A shallow copy copies the references of objects, whereas a deep copy copies the objects and their nested properties.

const obj1 = { a: 1, b: { c: 2 } };
const shallowCopy = { ...obj1 };
const deepCopy = JSON.parse(JSON.stringify(obj1));
obj1.b.c = 3;
console.log(shallowCopy.b.c); // 3 (shallow copy)
console.log(deepCopy.b.c); // 2 (deep copy)

82. What is the difference between Array.prototype.slice() and Array.prototype.splice()?
Show Answer

Ans. slice() returns a shallow copy of a portion of an array, while splice() modifies the original array by removing or adding elements.

const arr = [1, 2, 3, 4];
const slicedArr = arr.slice(1, 3); // [2, 3]
arr.splice(1, 2); // Removes 2 and 3, arr becomes [1, 4]

83. What is the purpose of the Array.prototype.map() method in JavaScript?
Show Answer

Ans. The map() method creates a new array populated with the results of applying a given function to each element of the array.

const arr = [1, 2, 3];
const doubled = arr.map(num => num * 2);
console.log(doubled); // [2, 4, 6]

84. What is the purpose of the Array.prototype.filter() method in JavaScript?
Show Answer

Ans. The filter() method creates a new array with all elements that pass the test implemented by the provided function.

const arr = [1, 2, 3, 4];
const even = arr.filter(num => num % 2 === 0);
console.log(even); // [2, 4]

85. What is the purpose of the Array.prototype.reduce() method in JavaScript?
Show Answer

Ans. The reduce() method applies a function to each element in an array (from left to right) to reduce it to a single value.

const arr = [1, 2, 3];
const sum = arr.reduce((acc, num) => acc + num, 0);
console.log(sum); // 6

86. What is the purpose of the Array.prototype.find() method in JavaScript?
Show Answer

Ans. The find() method returns the first element in the array that satisfies the provided testing function.

const arr = [1, 2, 3, 4];
const found = arr.find(num => num > 2);
console.log(found); // 3

87. What is the purpose of the Array.prototype.every() method in JavaScript?
Show Answer

Ans. The every() method checks if all elements in an array pass the test implemented by the provided function.

const arr = [1, 2, 3];
const allPositive = arr.every(num => num > 0);
console.log(allPositive); // true

88. What is the purpose of the Array.prototype.some() method in JavaScript?
Show Answer

Ans. The some() method checks if at least one element in the array passes the test implemented by the provided function.

const arr = [1, 2, 3];
const somePositive = arr.some(num => num < 0);
console.log(somePositive); // false

89. What is the purpose of the Array.prototype.includes() method in JavaScript?
Show Answer

Ans. The includes() method checks if an array contains a certain element, returning true or false accordingly.

const arr = [1, 2, 3];
console.log(arr.includes(2)); // true

90. What is the purpose of the Array.prototype.sort() method in JavaScript?
Show Answer

Ans. The sort() method sorts the elements of an array in place and returns the sorted array.

const arr = [3, 1, 2];
arr.sort();
console.log(arr); // [1, 2, 3]

91. What is the purpose of the Array.prototype.concat() method in JavaScript?
Show Answer

Ans. The concat() method is used to merge two or more arrays into one new array.

const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = arr1.concat(arr2);
console.log(merged); // [1, 2, 3, 4]

92. What is the difference between the for...in loop and the for...of loop in JavaScript?
Show Answer

Ans. The for...in loop iterates over the keys of an object, while the for...of loop iterates over the values of an iterable object like an array.

const arr = [1, 2, 3];
for (let value of arr) {
    console.log(value); // 1 2 3
}
for (let key in arr) {
    console.log(key); // 0 1 2
}

93. What is the purpose of the try...catch block in JavaScript?
Show Answer

Ans. The try...catch block is used to handle errors. The try block contains the code that may throw an error, while the catch block handles the error.

try {
    throw new Error("Oops!");
} catch (error) {
    console.log(error.message); // Oops!
}

94. How can you check if an object is an array in JavaScript?
Show Answer

Ans. You can use Array.isArray() to check if a variable is an array.

console.log(Array.isArray([1, 2, 3])); // true
console.log(Array.isArray({ a: 1 })); // false

95. What is the difference between slice() and splice() methods in JavaScript?
Show Answer

Ans. The slice() method returns a shallow copy of a portion of an array, while splice() modifies the original array by adding/removing elements.

const arr = [1, 2, 3, 4];
const sliced = arr.slice(1, 3); // [2, 3]
arr.splice(1, 2); // arr becomes [1, 4]

96. What is the purpose of the async/await syntax in JavaScript?
Show Answer

Ans. The async/await syntax is used for handling asynchronous code in a more readable way. async makes a function return a promise, and await pauses the function execution until the promise is resolved.

async function fetchData() {
    const response = await fetch("/data");
    const data = await response.json();
    console.log(data);
}

97. What is the purpose of the debounce function in JavaScript?
Show Answer

Ans. A debounce function limits the rate at which a function is invoked, ensuring that the function is not executed too frequently within a specified interval.

function debounce(func, delay) {
    let timeout;
    return function(...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => func(...args), delay);
    };
}

98. How does JavaScript handle asynchronous operations?
Show Answer

Ans. JavaScript handles asynchronous operations using callbacks, promises, and async/await. These mechanisms allow the program to continue executing while waiting for a response from an asynchronous operation.


99. What is a promise in JavaScript?
Show Answer

Ans. A promise is an object representing the eventual completion (or failure) of an asynchronous operation. It has three states: pending, resolved, and rejected.

let promise = new Promise((resolve, reject) => {
    resolve("Success");
});
promise.then(result => console.log(result)); // Success

100. How do you create a class in JavaScript?
Show Answer

Ans. A class in JavaScript is created using the class keyword. A class can have a constructor and methods.

class Person {
    constructor(name) {
        this.name = name;
    }
    greet() {
        console.log(`Hello, ${this.name}`);
    }
}
const person = new Person("Alice");
person.greet(); // Hello, Alice

SCHOLARSHIP ADMISSION
Coumputer Course

Popular Courses

(123)
Web Development
(123)
FULL STACK JAVA
PROGRAMING
(123)
PYTHON PROGRAMING
smartfuturepoint