DEV Community

Cover image for βœ¨πŸ—³οΈ JavaScript Variables: 17 Quick Questions You Need To Master
Ndeye Fatou Diop
Ndeye Fatou Diop

Posted on • Updated on • Originally published at frontendjoy.com

βœ¨πŸ—³οΈ JavaScript Variables: 17 Quick Questions You Need To Master

Struggling to find a frontend job?

Make sure you can answer these 17 JavaScript variable questions first πŸ‘‡:


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: "Ndeye Fatou Diop",
    age: 30,
}
console.log(`Your name is ${me.name} and you are ${me.age}.`)
Enter fullscreen mode Exit fullscreen mode

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 = "Ndeye Fatou Diop" // This is an initialization
name = "Fatou" // This is a re-assignment
Enter fullscreen mode Exit fullscreen mode

3. How do you declare a variable in JavaScript?

There are 3 main ways to declare variables in JavaScript:

Option 1: Using let

let age;
Enter fullscreen mode Exit fullscreen mode

Option 2: Using const

// IMPORTANT: We cannot do only `const name;` we must initialize the variable
const name = "Ndeye Fatou Diop";
Enter fullscreen mode Exit fullscreen mode

Option 3 (old way, not recommended): Using var

var name;
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ 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.


4. 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

Enter fullscreen mode Exit fullscreen mode

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. See the full list here.

  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;
Enter fullscreen mode Exit fullscreen mode

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 = "Ndeye Fatou Diop"; // This is a global variable
var age; // This is also a global variable
Enter fullscreen mode Exit fullscreen mode
  • Module scope: The scope for code running in module mode. Variables declared here are available only within the module.
// module.js
let fullName = "Ndeye Fatou Diop"; // 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
Enter fullscreen mode Exit fullscreen mode
  • Local/Function scope: The scope created with a function. Variables declared here are only available within the function.
function sayHi(){
    let fullName = "Ndeye Fatou Diop"; // fullName is only available within the function
    console.log(`Hi, ${fullName}.`);
}
Enter fullscreen mode Exit fullscreen mode
  • 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.`);
}
Enter fullscreen mode Exit fullscreen mode

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 = "Ndeye Fatou";
    // …
    let fullName; // SyntaxError: Identifier 'fullName' has already been declared
}


// βœ… This works
if(myCondition) {
    let fullName = "Ndeye Fatou";
    // …
}
let fullName; // This is Ok since `fullName` is declared outside of the block scope
Enter fullscreen mode Exit fullscreen mode

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!");
}
Enter fullscreen mode Exit fullscreen mode
  • 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 = "Ndeye Fatou"
console.log(name); // This will log `Ndeye Fatou`
Enter fullscreen mode Exit fullscreen mode
  • Variable 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 = "Ndeye Fatou"
console.log(name); // This will log `Ndeye Fatou`
Enter fullscreen mode Exit fullscreen mode

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

Feature var let const
Smallest Scope Function-scoped Block-scoped Block-scoped
Redeclaration Allowed within the same scope Not allowed within the same scope Not allowed within the same scope
Re-assignment Allowed Allowed Not allowed (must be initialized when declared)
Hoisting Hoisted but initialized as undefined Hoisted but not initialized Hoisted but not initialized
Best Practice DO NOT USE (can cause confusing bugs) Preferred for variables that change 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;
Enter fullscreen mode Exit fullscreen mode

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) {
    switch(day) {
        case 0: {
            let dayName = "Sunday";
            return dayName;
        }
        case 1: {
            let dayName = "Monday";
            return dayName;
        }
        // …
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Note: In the example above, returning early inside the switch statement would be better than using a variable.

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

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 = "Ndeye Fatou Diop";

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

sayHi(); // Hi, Fatou
console.log(`Hi, ${name}`); // Hi, Ndeye Fatou Diop
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Note: You should avoid variable shadowing when possible because it makes the code harder to follow.


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.

Don't @ me πŸ˜… I know we can modify an object even if we store its reference in a constant.
See my post here πŸ‘‰ ✨🧱 JavaScript Data Types: 27 Quick Questions You Need To Master.


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

const name = "Ndeye Fatou Diop"
const age = 30;
const me = {
    name,
    age
}
Enter fullscreen mode Exit fullscreen mode

That's a wrap πŸŽ‰.

Leave a comment πŸ“© to share your favorite question (or add one).

And don't forget to drop a "πŸ’–πŸ¦„πŸ”₯".

If you're learning React, download my 101 React Tips & Tricks book for FREE.

If you like articles like this, join my FREE newsletter, FrontendJoy.

If you want daily tips, find me on X/Twitter.

Top comments (2)

Collapse
 
ckissi profile image
Csaba Kissi

Amazing in deep explanation of the topic Ndeye!

Collapse
 
_ndeyefatoudiop profile image
Ndeye Fatou Diop

Thank you so much Csaba πŸ˜€

Super glad you like it!