βœ¨πŸ—³οΈ 17 JavaScript Variables Interview Questions

Β·

9 min read

1. What is a variable in JavaScript?

A variable is a container that holds data.

You can think of it as a label for a specific spot in memory where information is stored.

Variables are essential because they allow you to store, retrieve, and manipulate data throughout your program.

In the code snippet below, me is a variable:

const me = {
    name: "Sumit Upadhyay",
    age: 30,
}
console.log(`Your name is ${me.name} and you are ${me.age}.`)

2. What is the difference between declaration, initialization, and re-assignment?

Declaring a variable means specifying its type (e.g., let) and name.

Initializing a variable means giving it a value.

Reassigning a variable means changing its value. Only variables declared with let or var can be assigned a new value.

let name; // This is a declaration
name = "Sumit Upadhyay" // This is an initialization
name = "Money" // This is a re-assignment

How do you declare a variable in JavaScript?

There are 3 main ways to declare variables in JavaScript:

Option 1: Using let

let age;

Option 2: Using const

// IMPORTANT: We cannot do only `const name;` we must initialize the variable
const name = "Sumit Upadhyay";
var name;

πŸ’‘ Note: You can declare a variable without specifying any type like name = "Fatou" but please don't do this. In non-strict mode (see Question #4), the variable will end up in the global scope.

What is strict mode in JavaScript?

Strict mode is a way to opt into a restricted variant of JavaScript.

When you enable strict mode, the JavaScript engine will enforce stricter parsing and error handling rules.

For example,

  • You can't assign to undeclared variables (which would create a global variable).

  • You can't assign to a non-writable global (e.g., undefined = 5).

  • You can't duplicate parameter names (e.g., function sum(a, a, b) {…}).

  • To enable strict mode, add 'use strict'; at the beginning of your script or function.

'use strict';

function sum(a, a, b) {
    return a + b;
}

console.log("Sum: ", sum(1, 3, 2)) // SyntaxError: Duplicate parameter name not allowed in this context

5. What are some best practices for naming variables in JavaScript?

When naming variables in JavaScript, follow these best practices:

  1. Avoid reserved words: You cannot use JavaScript reserved words (like class, var, function, etc.) as variable names. These are keywords used by the language itself.

  2. Use camelCase for most variables: The convention is to use camelCase for naming variables. This means the first word is lowercase, and each subsequent word starts with a capital letter. Constants, on the other hand, should be written in all uppercase with underscores separating words.

  3. Be descriptive: Variable names should describe what the variable is used for. This makes your code more readable. For tiny scopes (like loop headers), short names like i are Ok; otherwise, avoid vague names like x or data.

// ❌ Bad
let try; // try is a reserved word
let place_of_birth; // not camelCase or uppercase
const x = 100; // not descriptive

// βœ… Good
let shouldRetry;
let placeOfBirth;
const TIMEOUT_MS = 100;

6. What does "scope" mean in the context of JavaScript variables

In JavaScript, scope refers to the area of the code where a variable can be accessed or used.

If a variable or expression is not in the current scope, it will not be available for use.

Think of JavaScript scope like a house 🏠 with different rooms.

Each room has its own set of stuff that can only be accessed by the person in that room.

But there is also a living room where everyone can access stuff. This is equivalent to the global scope (see Question #7).

7. What are the different types of scope in JavaScript?

There are 4 types of scope:

  • Global scope: The default scope for all code running in script mode. Variables declared here are available everywhere and are called global variables. You can think of the global scope as your living room. Everyone can access stuff in it. Avoid using global variables as much as possible, similar to how you would avoid putting all your stuff in the living room.
let fullName = "Sumit Upadhyay"; // This is a global variable
var age; // This is also a global variable

Module scope: The scope for code running in module mode. Variables declared here are available only within the module.

// module.js
let fullName = "Sumit Upadhyay"; // This is a module variable, only available in this module unless exported
export const age = 30; // This is available here and in other modules that import it
  • Local/Function scope: The scope created with a function. Variables declared here are only available within the function.
function sayHi(){
    let fullName = "Sumit Upadhyay"; // fullName is only available within the function
    console.log(`Hi, ${fullName}.`);
}
  • Block scope: The scope created with a block (e.g., with if, for, while, etc.). This scope is only available for variables declared with let, const, etc.
if(myCondition) {
    let age = 10; // age is only available within the block
    console.log(`You are, ${age} years old.`);
}

8. What happens if you try to redeclare a let or const variable?

You will get an error if you try to redeclare a let, const variable within the same scope.

// ❌ Bad: We are redeclaring `fullName` within the same scope
if(myCondition) {
    // We are inside a block scope
    let fullName = "Sumit Upadhyay";
    // …
    let fullName; // SyntaxError: Identifier 'fullName' has already been declared
}


// βœ… This works
if(myCondition) {
    let fullName = "Sumit Upadhyay";
    // …
}
let fullName; // This is Ok since `fullName` is declared outside of the block scope

9. What is "hoisting" in JavaScript?

Hoisting is a behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase before the code is executed.

This means that you can reference some variables or functions before they are declared in the code.

  • Function declarations are fully hoisted, meaning you can call a function before its actual declaration in the code.

  •     sayHello(); // This works, even though the function is declared later in the code
    
        function sayHello() {
            console.log("Hello!");
        }
    
    • Variables declared with var are hoisted and initialized as undefined. This means you can access the variable before it's declared in the code.
console.log(name); // This will log `undefined`
var name = "Sumit Upadhyay"
console.log(name); // This will log `Sumit Upadhyay`
  • Variables declared with let and const are hoisted but not initialized. This means you can't access the variable before it's declared in the code.
console.log(name); // This will throw an error `ReferenceError: Cannot access 'name' before initialization`
let name = "Sumit Upadhyay"
console.log(name); // This will log `Sumit Upadhyay`

10. What are the differences between var, let, and const?

  1. Smallest Scope:

    • var: Function-scoped

    • let: Block-scoped

    • const: Block-scoped

  2. Re-declaration:

    • var: Allowed within the same scope

    • let: Not allowed within the same scope

    • const: Not allowed within the same scope

  3. Re-assignment:

    • var: Allowed

    • let: Allowed

    • const: Not allowed (must be initialized when declared)

  4. Hoisting:

    • var: Hoisted but initialized as undefined

    • let: Hoisted but not initialized

    • const: Hoisted but not initialized

  5. Best Practice:

    • var: DO NOT USE (can cause confusing bugs)

    • let: Preferred for variables that change

    • const: Preferred for variables that don't change

11. What happens if you try to use a variable before it is declared?

It depends on the variable type and the mode.

  • If you try to use let and const before declaring them, you will get a ReferenceError.

  • If you try to use var, you will get undefined.

12. What is the temporal dead zone (TDZ) in JavaScript?

The Temporal Dead Zone (TDZ) is the period between the start of the containing scope (see Question #6 and Question #7) and the actual declaration of a variable.

TDZ only applies to variables declared with const and let (or class).

If you try to access the variable during this period, you will get a ReferenceError.

console.log(age); // ReferenceError: Cannot access 'age' before initialization
let age;

13. Can you provide an example of leveraging block scopes?

Remember what we said in Question #8?

We cannot redeclare a variable (created with let or const) within the same scope.

Unfortunately, there are cases where we want to reuse the same variable name in a switch statement. We can use block scoping to achieve this.

// ❌ Incorrect: The second case will cause an issue because `dayName` is already declared
function getDayName(day) {
    switch(day) {
        case 0:
            let dayName = "Sunday";
            return dayName;
        case 1:
            let dayName = "Monday";
            return dayName;
        // …
    }
}

// βœ… Correct: We use block scoping to reuse the same variable name
function getDayName(day) {
    let dayName;
    switch(day) {
        case 0: {
            let dayName = "Sunday";
            return dayName;
        }
        case 1: {
            let dayName = "Monday";
            return dayName;
        }
        // …
    }
}

πŸ’‘ Note: In the example above, we can just drop the variable name.

function getDayName(day) {
    switch(day) {
        case 0:
            return "Sunday";
        case 1:
            return "Monday";
        // …
    }
}

14. How do you determine the type of a variable in JavaScript?

This is a trick question πŸ˜….

In JavaScript, variables don't have typesβ€”values do.

When you use typeof myVariable, you're checking the type of value the variable holds.

15. What is variable shadowing?

Variable shadowing occurs when a variable in an inner scope has the same name as one in an outer scope.

The inner variable "shadows" the outer one, making it inaccessible within that scope.

In the example below, the variable name inside the function shadows the outer variable name.

let name = "Sumit Upadhyay";

function sayHi(){
    const name = "Sumit"; // This is shadowing the outer variable name
    console.log(`Hi, ${name}`);
}

sayHi(); // Hi, Sumit
console.log(`Hi, ${name}`); // Hi, Sumit Upadhyay

16. When should you use var to declare variables?

NEVER ❌.

var is outdated and has several issues:

  • It's not block-scoped, meaning its scope is the entire function or global environment, even if declared inside a block.

  • It allows redeclaration within the same scope, which can lead to accidental overwrites.

  • It can pollute the global scope if declared outside a function.

  • It's hoisted and initialized as undefined, which can cause confusing bugs.

Instead, use const by default and let when you need to reassign a value.

17. How do you use a variable as an object key?

const name = "Sumit Upadhyay"
const age = 30;
const me = {
    name,
    age
}

That's a wrap πŸŽ‰.

Β