JavaScript - Part : 1 Basic Interview Questions

Ayush RajputAyush Rajput
5 min read
  1. Difference between var , let and const ?

    var : Function scoped , Redeclare , Reassign

    let : Blocked scoped , Not Redeclare , Reassign

    const: Blocked scoped , Not Redeclare , Not Reassign

     var x = 10;
     let y = 20;
     const z = 30;
    
     var x; // Redeclare
     x = 40; // Reassign
    
     //let y;  -> Not Redeclare
     y = 50; // Reassign
    
     //const z; -> Not Redecalre 
     // z = 60; //-> Not Reassign, Error: Assignment to constant variable
    
  2. What is hoisting in JavaScript?

    Hoisting in JavaScript is the behavior of moving variables and function declarations at the top of their scope before code execution

     console.log(a); // undefined :For ex:  variablle decalred with var can be hoisted but initialized as undefined
     var a = 5;
    
     hoistedFunction(); // "I am hoisted" : Functions are fully hoisted as we can call before thier defination
     function hoistedFunction() {
       console.log("I am hoisted");
     }
    
  3. What are the different data types in JavaScript?

    Primitive : String, Number, Boolean, Null, Undefined, Symbol, BigInt

    Non Primitive: Object, Array, Function

     let name = "Ayush";           // String
     let age = 25;                 // Number
     let isStudent = true;         // Boolean
     let score = null;             // Null
     let grade;                    // Undefined
     let id = Symbol("id");        // Symbol
     let bigInt = 12345678901234567890n; // BigInt
    
     let user = { name: "Ayush" }; // Object
     let arr = [1, 2, 3];          // Array (Object)
    
     console.log(typeof 42); // "number"
     console.log(typeof "Hello"); // "string"
     console.log(typeof true); // "boolean"
     console.log(typeof {}); // "object"
     console.log(typeof []); // "object" (Arrays are objects)
     console.log(typeof function(){}); // "function"
     console.log(typeof null); // "object" (This is a JavaScript bug)
     console.log(typeof undefined); // "undefined"
    
  4. Difference between undefined and null?

    undefined: means variable is declared but not assigned a value

    null: variable is explicitly assigned to a null that indicate “no value”

     let a;
     console.log(a);       // undefined
    
     let b = null;
     console.log(b);       // null
    
  5. Difference between == and === ?

    • == checks value only (with type coercion)

    • === checks value and type

        console.log(5 == "5");  // true
        console.log(5 === "5"); // false
      
  6. What are template literals ?

    Strings with embedded expressions using backticks (` )

     let name = "Ayush";
     console.log(`Hello, ${name}!`);
    
  7. What is typeof?

    Checks the type of a value.

     console.log(typeof "Hello");  // string
     console.log(typeof 42);       // number
     console.log(typeof null);     // object (quirk)
    
  8. What is NaN?

    NaN = Not-a-Number; returned when an invalid math operation happens.

     console.log("abc" / 2); // NaN
     console.log(typeof NaN); // number
    
  9. What is an IIFE (Immediately Invoked Function Expression)?

    An IIFE is a function that executes immediately after it is defined.

      (function() {
          console.log("I am an IIFE!");
      })();  // "I am an IIFE!"
    
      // IIFE with arrow fucntion
      (()=>console.log("Arrow IIFE"))();
    
  10. What is the global object?

    It is the top-level object depending on enviroment present in the excection context

    • Browser → window

    • Node.js → global

    • Universal → globalThis

  11. What is a closure?

    A closure is created when a inner(nested) function rememeber and continue to access the varibales from its lexical scope , even after the outer function finishes executing.

    function outer() {
        let count = 0;
    
        return function inner() {
            count++;
            console.log(count);
        };
    }
    
    const counter = outer(); // outer function return inner function
    counter(); // 1
    counter(); // 2    // count updated, inner function remeber previous count defined in outer()
    counter(); // 3
    

    lexical scope - abiltiy of nested function to access the variables defined in thier parent function(defination) scope

  1. Asynchronous Js vs Synchronous Js ?

    Asynchronous JavaScript is a programming technique that allows certain operations to be executed without blocking the main thread (the execution flow of JavaScript).

    JavaScript is synchronous-code execute line by line

  1. What is event loop ?

    Event loop in JS is a mechenism that ensures the execution asynchronous task without blocking the main thread.

    Event loop order → Synchronous code run first then promises then microtask operations like setTimout ans setTimeInterval

  2. What is Promises ?

    In JS Promises are the good way to handle asynchronous tasks. It is used to find out the asynchronous task is successfully completed or not.

    It have three states - Pending , Resolved , Rejected

     //Step 1: Creating a promise
     const ticket = new Promise((resolve, reject)=>{
         const isBoarded = false;  // our promise is reject
         if(isBoarded){
             resolve("Your is on the time");
         }
         else{
             reject("Your flight has been cancelled");
         }
     })
    
     // Step 2:use a promise -> .then if resolve , .catch() if reject 
     ticket.then((data)=>{   // data is that is written inside reolve () or reject()
         console.log("WOW", data)
     }).catch((data)=>{
         console.log("Oh No",data)  // Output: Oh No Your flight has been cancelled
     })
    

    Promises solve the problem of callback hell using promise chaining in which we link multiple .then() and .catch() operations

  1. What is asyn/await ?

    Asycn/ await is a good way to handle the promises. It makes asynchronous code look like synchronous code.

     // Step 1: Creating a promise
     const ticket = new Promise((resolve, reject) => {
         const isBoarded = false; // our promise is rejected
         if (isBoarded) {
             resolve("Your flight is on time");
         } else {
             reject("Your flight has been cancelled");
         }
     });
    
     // Step 2: Using async/await
     async function checkFlight() {
         try {
             const data = await ticket; // Waiting for the promise to resolve
             console.log("WOW", data);
         } catch (error) {
             console.log("Oh No", error); // Output: Oh No Your flight has been cancelled
         }
     }
    
     // Calling the function
     checkFlight();
    
  1. What is optional chaining in JS ?

    Optional Chaining (?.) is a feature in JavaScript that allows you to safely access deeply nested object properties without having to check if each level exists.

    let user = {};
    
    console.log(user.address.street); // ❌ Error: Cannot read properties of undefined
    
    if (user && user.address) {
      console.log(user.address.street);  // Right way 
    }
    
    // Using optional chianing
    let user = {};
    console.log(user.address?.street); // ✅ undefined (no error)
    
0
Subscribe to my newsletter

Read articles from Ayush Rajput directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ayush Rajput
Ayush Rajput