Skip to content

Interview Question JavaScript Part ‐ 1

Anurag Mishra edited this page Aug 7, 2024 · 1 revision

JavaScript Interview Question

1. What is a closure in JavaScript, and how is it used? Provide an example.

Answer: A closure is a function that retains access to its lexical scope, even when that function is executed outside of its original scope. Closures are created every time a function is created, at function creation time.

function outerFunction() {
    let outerVariable = 'I am from outer function';

    function innerFunction() {
        console.log(outerVariable);
    }

    return innerFunction;
}

const myClosure = outerFunction();
myClosure();  // Output: "I am from outer function"

2. Explain the difference between == and === in JavaScript.

Answer: == is the equality operator that performs type coercion, meaning it converts the operands to the same type before making the comparison. === is the strict equality operator that does not perform type coercion, so it only returns true if both the type and the value are the same.

5 == '5';   // true, because '5' is converted to 5
5 === '5';  // false, because the types are different

3. What is the difference between let, const, and var?

Answer: var is function-scoped and can be redeclared and updated. let is block-scoped and can be updated but not redeclared within the same scope. const is also block-scoped but cannot be updated or redeclared; it must be initialized at the time of declaration.

function example() {
    var x = 1;
    if (true) {
        var x = 2;  // same variable
        console.log(x);  // 2
    }
    console.log(x);  // 2
}

function exampleLet() {
    let y = 1;
    if (true) {
        let y = 2;  // different variable
        console.log(y);  // 2
    }
    console.log(y);  // 1
}

const z = 3;
z = 4;  // Error: Assignment to constant variable

4. What is the purpose of JavaScript's this keyword, and how is it used?

Answer: The this keyword refers to the object that is currently executing the code. It allows methods to refer to their parent object and is determined at runtime based on the context in which a function is called.

const obj = {
    name: 'John',
    greet: function() {
        console.log(this.name);
    }
};

obj.greet();  // Output: 'John'

function globalGreet() {
    console.log(this.name);
}

globalGreet.call(obj);  // Output: 'John'

5. How does prototypal inheritance work in JavaScript?

Answer: Prototypal inheritance means that objects can inherit properties and methods from other objects. Each object has a private property (prototype) that links to another object. This allows one object to use the properties and methods of another.

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

Person.prototype.greet = function() {
    console.log(`Hello, my name is ${this.name}`);
};

const john = new Person('John');
john.greet();  // Output: Hello, my name is John

6. Explain the concept of hoisting in JavaScript.

Answer: Hoisting is JavaScript's behavior of moving declarations to the top of their containing scope during the compilation phase. This means that variable and function declarations are processed before any code is executed, but initializations are not hoisted.

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

greet();  // Output: Hello
function greet() {
    console.log('Hello');
}

7. What are IIFE (Immediately Invoked Function Expressions) and why are they used?

Answer: An IIFE is a function that is executed immediately after it is defined. It is used to create a local scope and avoid polluting the global namespace.

(function() {
    var message = 'Hello, IIFE';
    console.log(message);
})();  // Output: Hello, IIFE

8. How do you handle asynchronous code in JavaScript? Explain the differences between callbacks, promises, and async/await.

Answer: Asynchronous code can be handled using callbacks, promises, and async/await.

  • Callbacks: Functions passed as arguments to other functions and executed after some operation has been completed.
  • Promises: Objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value.
  • Async/Await: Syntactic sugar built on promises that allows for writing asynchronous code in a more synchronous fashion.
// Callbacks
function fetchData(callback) {
    setTimeout(() => {
        callback('Data received');
    }, 1000);
}

fetchData((data) => {
    console.log(data);  // Output: Data received
});

// Promises
function fetchDataPromise() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve('Data received');
        }, 1000);
    });
}

fetchDataPromise().then((data) => {
    console.log(data);  // Output: Data received
});

// Async/Await
async function fetchDataAsync() {
    const data = await fetchDataPromise();
    console.log(data);  // Output: Data received
}

fetchDataAsync();

9. What is event delegation and how does it work in JavaScript?

Answer: Event delegation is a technique where you use a single event listener to manage all events of a particular type for multiple elements. This is done by taking advantage of event bubbling.

document.getElementById('parent').addEventListener('click', (event) => {
    if (event.target.matches('.child')) {
        console.log('Child element clicked:', event.target);
    }
});

10. What are the different ways to create objects in JavaScript?

Answer: Objects in JavaScript can be created in several ways:

  • Object literals
  • The Object constructor
  • The new keyword with a constructor function
  • Object.create method
  • Classes (ES6 syntax)
// Object literal
const obj1 = { name: 'John' };

// Object constructor
const obj2 = new Object();
obj2.name = 'Jane';

// Constructor function
function Person(name) {
    this.name = name;
}
const obj3 = new Person('Jim');

// Object.create
const proto = { greet: function() { console.log('Hello'); } };
const obj4 = Object.create(proto);
obj4.name = 'Jack';

// Classes
class Car {
    constructor(model) {
        this.model = model;
    }
}
const obj5 = new Car('Toyota');

11. Explain the difference between null and undefined in JavaScript.

Answer: null is an assignment value that means "no value" and must be assigned. undefined means a variable has been declared but has not yet been assigned a value.

let a;
console.log(a);  // Output: undefined

let b = null;
console.log(b);  // Output: null

12. What is the event loop in JavaScript?

Answer: The event loop is a mechanism that allows JavaScript to perform non-blocking operations by offloading operations to the system kernel whenever possible. It continually checks the call stack and the message queue, processing messages (callbacks) from the queue only when the stack is empty.

13. How can you prevent a default action in an event handler in JavaScript?

Answer: You can prevent a default action in an event handler by calling the event.preventDefault() method.

document.querySelector('a').addEventListener('click', (event) => {
    event.preventDefault();
    console.log('Default action prevented');
});

14. What are arrow functions and how do they differ from regular functions?

Answer: Arrow functions are a shorter syntax for writing functions in JavaScript. They do not have their own this, arguments, super, or new.target. Arrow functions are always anonymous and are best suited for non-method functions.

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

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

15. What is the module pattern in JavaScript?

Answer: The module pattern is a design pattern used to encapsulate private and public methods and variables. It uses closures to create a private scope and exposes only the methods or variables that need to be public.

const Module = (function() {
    let privateVar = 'I am private';

    function privateMethod() {
        console.log(privateVar);
    }

    return {
        publicMethod: function() {
            privateMethod();
        }
    };
})();

Module.publicMethod();  // Output: I am private

16. Explain how the reduce method works in JavaScript.

Answer: The reduce method executes a reducer function on each element of the array, resulting in a single output value. The reducer function takes four arguments: accumulator, currentValue, currentIndex, and array.

const array = [1, 2, 3, 4];


const sum = array.reduce((accumulator, currentValue) => {
    return accumulator + currentValue;
}, 0);
console.log(sum);  // Output: 10

17. What is the difference between forEach and map methods in JavaScript?

Answer: forEach executes a provided function once for each array element and does not return a new array. map executes a provided function once for each array element and returns a new array with the results.

const array = [1, 2, 3, 4];

// forEach
array.forEach((element) => {
    console.log(element);
});

// map
const doubled = array.map((element) => {
    return element * 2;
});
console.log(doubled);  // Output: [2, 4, 6, 8]

18. What is the purpose of the bind, call, and apply methods in JavaScript?

Answer: These methods are used to set the this context for a function.

  • bind creates a new function with a specified this value and arguments.
  • call invokes a function with a specified this value and arguments.
  • apply is similar to call, but takes arguments as an array.
function greet(greeting, punctuation) {
    console.log(`${greeting}, ${this.name}${punctuation}`);
}

const person = { name: 'John' };

const boundGreet = greet.bind(person);
boundGreet('Hello', '!');  // Output: Hello, John!

greet.call(person, 'Hi', '?');  // Output: Hi, John?

greet.apply(person, ['Hey', '.']);  // Output: Hey, John.

19. How do you handle exceptions in JavaScript?

Answer: Exceptions in JavaScript are handled using try...catch blocks. The try block contains code that may throw an error, and the catch block contains code to handle the error.

try {
    // Code that may throw an error
    let result = riskyFunction();
} catch (error) {
    console.log('An error occurred:', error.message);
}

20. What are higher-order functions in JavaScript?

Answer: Higher-order functions are functions that can take other functions as arguments or return functions as their result. They are a key concept in functional programming.

function higherOrderFunction(callback) {
    return function(value) {
        return callback(value);
    };
}

const double = higherOrderFunction((x) => x * 2);
console.log(double(5));  // Output: 10

These detailed answers should give a comprehensive understanding of each concept.

Clone this wiki locally