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}.`)
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
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;
Option 2: Using const
// IMPORTANT: We cannot do only `const name;` we must initialize the variable
const name = "Ndeye Fatou Diop";
Option 3 (old way, not recommended): Using var
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.
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
5. What are some best practices for naming variables in JavaScript?
When naming variables in JavaScript, follow these best practices:
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.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.
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 likex
ordata
.
// β 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 = "Ndeye Fatou Diop"; // 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 = "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
- 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}.`);
}
-
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 = "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
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 asundefined
. 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`
-
Variable declared with
let
andconst
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`
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
andconst
before declaring them, you will get aReferenceError
.If you try to use
var
, you will getundefined
.
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) {
switch(day) {
case 0: {
let dayName = "Sunday";
return dayName;
}
case 1: {
let dayName = "Monday";
return dayName;
}
// β¦
}
}
π‘ 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";
// β¦
}
}
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
π‘ 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
}
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)
Amazing in deep explanation of the topic Ndeye!
Thank you so much Csaba π
Super glad you like it!