Interview Practice

Photo by freestocks on Unsplash

Interview Practice

  1. What is Closure in Javascript?

    Need

    Closures in JavaScript are necessary for data privacy and encapsulation. Without closures, it would be challenging to achieve data hiding and manipulation in a controlled manner.

    What is it?

    A closure in JavaScript is a function that has access to its own scope, the outer function's scope, and the global scope. It can access variables from these three scopes even after the outer function has finished execution.

    How is it used?

    Data Encapsulation: Closures are used to protect variables from being accessed directly, effectively encapsulating them. They provide a way to create private variables/functions which can only be accessed within the closure.

     function outerFunction() {
     let count = 0;
     return function innerFunction() {
        count++;
        return count;
       };
     }
    
     const counter = outerFunction();
     console.log(counter()); // Outputs: 1
     console.log(counter()); // Outputs: 2
    

    In this example, count is private to outerFunction and can't be directly accessed. innerFunction, however, has access to count through closure.

  2. What is Hoisting in Javascript?

    Need

    Hoisting in JavaScript is necessary to prevent Reference Errors. Without hoisting, calling a function or accessing a variable before it's declared would result in an error.

    What is it?

    Hoisting in JavaScript is a behavior where variable and function declarations are moved to the top of their containing scope during the compile phase, before the code has been executed.

    How is it used?

     greet("John"); // Outputs: "Hello, John"
     function greet(name) {
     console.log(Hello, ${name});
     }
    

    In this example, the function greet is hoisted to the top of the scope, allowing it to be called before its declaration in the code.

     console.log(myVar); // Outputs: undefined
     var myVar = 5;
    

    In this example, myVar is hoisted and initialized with undefined at the top of the scope, so logging myVar before its assignment doesn’t result in a Reference Error.

Hoisting Limitations: Note that while var declarations are hoisted, let and const declarations are also hoisted but aren’t initialized, and function expressions are not hoisted.

console.log(myLetVar); // Outputs: ReferenceError: myLetVar is not defined
let myLetVar = 5;

In this example, because myLetVar is declared with let, accessing it before its declaration results in a Reference Error, even though let and const declarations are hoisted.