Skip to main content

Command Palette

Search for a command to run...

Javascript Interview - Basic

Updated
View as Markdown
  1. What is the difference between var, let, and const in JavaScript?

    var -
    i) Function scoped : Available throughout the function in which it is declared (or globally if not inside a function).
    ii) Hoisting : Yes, var declarations are hoisted to the top of their scope, but not the assignment.

    iii) Re-declaration : Allowed within the same scope.
    iv) Mutability : The variable can be reassigned.
    let -
    i) Block-scoped : Only available within the {} block it's defined in.
    ii) Hoisting : Yes, but not initialized. Accessing before declaration causes a Reference Error.
    iii) Re-declaration : Not allowed in the same scope.
    iv) Mutability : The variable can be reassigned.
    const -
    i) i) Block-scoped : Only available within the {} block it's defined in.
    ii) Hoisting : Yes, but not initialized. Accessing before declaration causes a Reference Error.
    iii) Re-declaration : Not allowed in the same scope.
    iv) Mutability : The variable cannot be reassigned, but the contents of objects/arrays can be mutated.

  2. What are the different data types in JavaScript?
    JavaScript has a few core data types, which fall into two categories : primitive types and reference types (objects).
    i) Primitive Data Types - String, Number, boolean, undefined, null, symbol, bigint
    ii) Reference Data Types - object, array, function

  3. What is the typeof operator in Javascript?
    The typeof operator in JavaScript is used to determine the data type of a given value or variable.
    It returns a string that indicates the type.

     typeof "hello"        // "string"
     typeof 42            // "number"
     typeof true            // "boolean"
     typeof undefined    // "undefined"
     typeof null            // "object" ⚠️
     typeof Symbol()        // "symbol"
     typeof 10n            // "bigint"
     typeof function() {}    // "function"
     typeof {}            // "object"
     typeof []            // "object"
    
  4. What is the difference between for...in and for...of loops in JavaScript?
    for…in -
    i) Iterates over a key
    ii) Works with - Arrays and Objects
    iii) Return type - Strings (even for array keys)
    iv) Best for - Looping through object props
    v) Avoid with - Arrays (if order matters)

     const user = { name: "Alice", age: 30 };
    
     for (let key in user) {
       console.log(key);        // name, age
       console.log(user[key]);  // Alice, 30
     }
    

    for…of -
    i) Iterates over a Values
    ii) Works with - Arrays, Strings, Maps, Sets
    iii) Return type - Actual values
    iv) Best for - Looping through iterable items
    v) Avoid with - Plain objects (not iterable)

     const arr = [10, 20, 30];
     for (let value of arr) {
       console.log(value); // 10, 20, 30
     }
    
     for (let char of "hello") {
       console.log(char); // h, e, l, l, o
     }
    
  5. What is the difference between function declarations and function expressions?
    Function Declaration -

    i) Syntax - function fn()
    ii) Hoisted - Yes
    iii) this Binding - own this
    iv) Use case - General-purpose
    v) Anonymous - No, It needs a name
    vi) When to use - For reusable named functions in your code.
    Function Expression -
    i) Syntax - const fn = function()
    ii) Hoisted - No
    iii) this Binding - own this
    iv) Use case - Assign to variables, pass around
    v) Anonymous - Can be
    vi) When to use - When you need a function as a value (e.g., in objects, IIFEs).
    Arrow Function -
    i) Syntax - const fn = () => {}
    ii) Hoisted - No
    iii) this Binding - Lexical this (inherits)
    iv) Use case - Callbacks, short functions
    v) Anonymous - Always
    vi) When to use - For short callbacks, array methods, or when you want lexical this.

  6. What are the different types of errors in JavaScript?
    SyntaxError -
    i) What it means: You broke JavaScript’s grammar rules (typos, missing characters, etc.).
    ii) When it happens: During parsing (before the code runs).
    ReferenceError -
    i) What it means: You're trying to use a variable that hasn't been declared.

    ii) When it happens: At runtime.
    TypeError -
    i) What it means: You’re doing something with a value that’s not the right type.

    ii) When it happens: At runtime.

     if (true {   // missing a closing parenthesis
       console.log("Oops");
     }
     // SyntaxError: Unexpected token '{'
    
     console.log(x);
     // ReferenceError: x is not defined
    
     null.f(); 
     // TypeError: Cannot read properties of null
    
  7. What is exception handling in JavaScript?
    Exception handling in JavaScript is how you manage runtime errors — instead of crashing your program, you can catch, handle, or recover from them gracefully.

     function checkAge(age) {
       if (age < 18) {
         throw new Error("You must be at least 18 years old.");
       }
       return "Access granted";
     }
    
     try {
       console.log(checkAge(16));
     } catch (err) {
       console.error(err.message); // You must be at least 18 years old.
     }
    

    try - Wraps code that might throw an error.

    catch - Runs if an error is thrown in the try block. You get access to the error object.
    finally (optional) - Executes after try and catch, regardless of whether an error occurred.
    throw – Manually throw an error, You can throw your own exceptions

     throw new Error("Custom error!");
    
  8. Explain the closures in JavaScript with example?

    A closure allows an inner function to access variables from an outer function even after that outer function has returned.

     function outer() {
       let name = "Alice";
    
       function inner() {
         console.log("Hello, " + name);
       }
    
       return inner;
     }
    
     const greet = outer(); // outer() returns inner function
     greet(); // Hello, Alice
     /*
     outer() defines a variable name.
     inner() uses name, and is returned from outer().
     Even after outer() is done, the inner() function still remembers name.
     */
    
     function counter() {
       let count = 0;
    
       return function () {
         count++;
         console.log("Count:", count);
       };
     }
    
     const increment = counter();
     increment(); // Count: 1
     increment(); // Count: 2
    
     const another = counter();
     another(); // Count: 1 (new closure)
     /*
     Each call to counter() creates a new count variable scoped to that closure.
     You can't access count directly — it's private to the function returned.
     */
    
  9. What are modules in JavaScript? Explain import and export.
    JavaScript modules let you break your code into separate files, each with its own scope. This helps with - Code organization, Reusability, Encapsulation, Avoiding global namespace pollution.

    Each module is a file, and by default, variables and functions inside it are private to that file unless explicitly exported.
    You can use export to expose variables, functions, or classes from a module so other files can use them. A file can have many named exports but only one default export.

     // math.js
     export const PI = 3.14159;
    
     export function add(a, b) {
       return a + b;
     }
     //////////////////////////////////////////
     // greet.js
     export default function greet(name) {
       console.log(`Hello, ${name}`);
     }
    
     import { PI, add } from './math.js';
     console.log(PI);       // 3.14159
     console.log(add(2, 3)); // 5
     //////////////////////////////////////////
     import greet from './greet.js';
     greet('Alice'); // Hello, Alice
     //////////////////////////////////////////
     import { add as sum } from './math.js';
     sum(1, 2); // 3
     //////////////////////////////////////////
     import * as math from './math.js';
     math.add(5, 6);     // 11
     math.PI;            // 3.14159
    
  10. What are callback functions in JavaScript?
    A callback is a function passed as an argument to another function — and it gets executed later, usually after some kind of operation or event.

    function greet(name, callback) {
      console.log("Hi " + name);
      callback();
    }
    
    function sayBye() {
      console.log("Goodbye!");
    }
    
    greet("Alice", sayBye);
    
    ////////////////////////////////////////////
    
    setTimeout(function () {
      console.log("Executed after 2 seconds");
    }, 2000);
    
  11. What is hoisting in JavaScript?

    Hoisting is JavaScript's behavior of moving declarations to the top of their scope before code execution.
    When JavaScript runs your code, it “reorganizes” it internally so that certain declarations appear to be at the top of their scope, even if you wrote them later.

    console.log(x); // undefined (not an error)
    var x = 5;
    
    // Behind the scenes, JS treats it like
    var x;
    console.log(x); // undefined
    x = 5;
    // Only the declaration is hoisted, not the initialization.
    
    sayHello(); // ✅ Works
    
    function sayHello() {
      console.log("Hello!");
    }
    // Function declarations are fully hoisted, including the function body.
    

    let and const are hoisted, but they live in a "temporal dead zone" (TDZ) until the line where they are declared. So you can’t use them before that point.

  12. What is the Temporal Dead Zone?

    The Temporal Dead Zone (TDZ) is the time between when a variable is hoisted and when it's initialized — during this time, accessing the variable throws a ReferenceError.

    This only applies to let and const.

    Even though these variables are hoisted, they can’t be used until the actual line of declaration is reached.

    console.log(a); // ❌ ReferenceError: Cannot access 'a' before initialization
    let a = 10;
    // The variable a is hoisted but in the TDZ until let a = 10 runs.
    // So you can’t access it before that point.
    
    console.log(b); // undefined (no error)
    var b = 20;
    // var is hoisted and initialized to undefined, so it's not in a TDZ.
    // But this can lead to bugs, which is why let/const are safer.
    

    Always declare variables at the top of their scope to avoid TDZ issues.

    Prefer let and const over var — but know the TDZ rules.

  13. What are template literals in JavaScript?
    Template literals
    are string literals that - Use backticks (` ) instead of quotes, Allow multi-line strings, Support string interpolation using ${}

    Introduced in ES6, they make working with strings a lot more readable and fun.

    const name = "Alice";
    const greeting = `Hello, ${name}!`;
    console.log(greeting); // Hello, Alice!
    
  14. What is a Higher-Order Function?
    A higher-order function (HOF) is a function that Takes another function as an argument,

    and/or Returns a function.
    It's a function that works with other functions — treating them as first-class citizens.

    function greet(name) {
      return `Hello, ${name}`;
    }
    
    function processUserInput(callback) {
      const name = "Alice";
      console.log(callback(name));
    }
    
    processUserInput(greet); // Hello, Alice
    
  15. What are setTimeout and setInterval in JavaScript?
    i) setTimeOut()
    Runs a function once after a delay (in milliseconds).

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

    ii) setInterval()
    Runs a function repeatedly every X milliseconds.

    setInterval(() => {
      console.log("This runs every 3 seconds");
    }, 3000);
    

    How to Stop Them -

    const timeoutId = setTimeout(() => {
      console.log("Won't run");
    }, 5000);
    
    clearTimeout(timeoutId);
    /////////////////////////////////////////
    const intervalId = setInterval(() => {
      console.log("Repeating...");
    }, 1000);
    
    clearInterval(intervalId);
    
  16. What is the difference between window and document objects in Javascript?
    i) window Object
    The window object is the global object in the browser.
    It represents the browser window/tab and gives access to everything in the global scope.
    Everything global (like variables, functions, setTimeout, alert) is part of window.

    window has properties for the DOM, history, location, localStorage, etc.

    console.log(window.innerWidth); // Width of the window
    window.alert("Hello!");
    

    ii) document Object
    The document object is a property of window, and it represents the HTML content of the web page (DOM).
    Allows you to access and manipulate HTML. You use it for DOM traversal, selection, and updates.

    console.log(document.title); // Gets the <title> text
    const heading = document.querySelector("h1");
    heading.textContent = "Updated!";
    

    | Feature | window | document | | --- | --- | --- | | Represents | Browser window/tab | Web page's HTML content | | Type of Object | Global browser object | DOM (Document Object Model) | | Access | window.document | Directly as document | | Examples | window.alert(), window.innerWidth | document.querySelector(), document.title |

  17. What is Object.create() used for?
    Object.create() is used to create a new object, and you can directly set its prototype (i.e., what it should inherit from).

    const person = {
      greet() {
        console.log(`Hello, I'm ${this.name}`);
      }
    };
    
    const user = Object.create(person); // inherits from person
    user.name = "Alice";
    user.greet(); // Hello, I'm Alice
    
  18. What is method chaining in JavaScript?
    Method chaining is a technique where you call multiple methods on the same object, one after the other, in a single statement.
    Each method returns the object itself (usually this), allowing the next method to be called on it.

    const calculator = {
      value: 0,
      add(num) {
        this.value += num;
        return this; // 👈 allows chaining
      },
      subtract(num) {
        this.value -= num;
        return this;
      },
      multiply(num) {
        this.value *= num;
        return this;
      },
      result() {
        console.log(this.value);
        return this;
      }
    };
    
    calculator.add(5).subtract(2).multiply(3).result(); 
    // Output: 9
    
  19. What is the purpose of hasOwnProperty() method in Javascript?
    The .hasOwnProperty(prop) method checks if the object has a property of its own - not one inherited through the prototype chain.

    const person = {
      name: "Alice",
      age: 25
    };
    
    console.log(person.hasOwnProperty("name")); // ✅ true
    console.log(person.hasOwnProperty("toString")); // ❌ false (inherited from Object)
    // Returns true if the object owns the property directly.
    // Returns false if it's inherited or not found.
    
  20. What is difference between JSON.stringify and JSON.parse in Javascript?
    JSON.stringify and JSON.parse are two powerful methods in JavaScript used to convert data to and from JSON format — and they’re often used together when working with APIs, localStorage, or data transfers.

    const user = {
      name: "Alice",
      age: 25
    };
    
    // Convert object to JSON string
    const jsonString = JSON.stringify(user);
    console.log(jsonString); // '{"name":"Alice","age":25}'
    
    // Convert JSON string back to object
    const parsedUser = JSON.parse(jsonString);
    console.log(parsedUser.name); // 'Alice'
    

    APIs: Most APIs send and receive data as JSON strings.
    localStorage/sessionStorage: Only stores strings → you stringify before saving and parse after retrieving.

  21. How can we compare two objects in Javascript?
    Basic Comparison Doesn’t Work as Expected, Even though they look the same, they’re different instances in memory.

    const obj1 = { name: "Alice", age: 25 };
    const obj2 = { name: "Alice", age: 25 };
    
    console.log(JSON.stringify(obj1) === JSON.stringify(obj2)); // ✅ true (sometimes)
    
  22. What is the difference between microtasks and macrotasks?

    When JavaScript runs async operations, it puts them in queues — but not all async tasks are treated the same.
    i) Macrotask Queue (aka Task Queue)
    Contains larger async operations

    Runs after the current call stack is empty
    Examples - setTimeout, setInterval, setImmediate, I/O, UI rendering
    ii) Microtask Queue

    Contains smaller, prioritized callbacks

    Runs right after the current call stack and before the next macrotask
    Examples -Promise.then(), Promise.catch(), Promise.finally(), queueMicrotask()

    Execution Order (Event Loop Style) -
    Execute all synchronous code
    Drain the microtask queue

    Run the next macrotask

    Repeat...

  23. How does JavaScript handle shadowing of variables?
    Shadowing happens when a variable declared in a local scope (inner block or function) has the same name as a variable in an outer scope.
    The inner (local) variable "shadows" or hides the outer one within its own scope.

    let name = "Alice";
    
    function greet() {
      let name = "Bob"; // shadows the outer 'name'
      console.log(name); // Bob
    }
    
    greet();
    console.log(name); // Alice
    

    Avoid reusing variable names in nested scopes unless intentional.
    Use clear, descriptive names to prevent accidental shadowing.
    Use linters (like ESLint) to catch unwanted shadowing.