Skip to main content

Variable in JavaScript – Explained with Examples

A JavaScript variable is a container used to store JavaScript data (values).

note

JavaScript variables differ from mathematical or other generic variables. JavaScript variables are so powerful that you can use them to store various kinds of values at different times.

Let's see a variable's syntax.

Syntax

keyword variableName;

In the snippet above is an uninitialized variable. You can initialize JavaScript variables with this syntax:

keyword variableName = variableValue;

Below are some examples.

Example 1: Generic Variable

anyWord;

The code in the snippet above is a generic variable named anyWord. It is generic (not a JavaScript variable) because we defined it without any JavaScript keyword.

note

Using a generic variable can create bugs in your app—as JavaScript may interpret your code inconsistently.

Example 2: Initialized Generic Variable

anyWord = "Val1" + "Val2";

In the snippet above, we initialized the generic variable (anyWord) with a concatenation of "Val1" and "Val2".

note
  • The code above may produce erroneous results because anyWord is not a JavaScript variable.
  • Concatenation means to join two or more things together. For instance, string concatenation implies the joining together of two or more strings.

Example 3: JavaScript Variable

var anyWord;

In the snippet above, we used the keyword var to declare the creation of a JavaScript variable named anyWord.

Example 4: Initialized JavaScript Variable

var anyWord = "Val1" + "Val2";

In the snippet above, we initialized the JavaScript variable (anyWord) with a concatenation of "Val1" and "Val2".

The computer will analyze anyWord as a JavaScript variable because we used the var keyword to declare it so.

Note that the var keyword is one of JavaScript's variable keywords.

But what is a JavaScript variable keyword? Let's find out.

Anatomy of a JavaScript
variable

A JavaScript variable is a container used to store JavaScript data (values).

What Is a JavaScript Variable Keyword?

A JavaScript variable keyword is a code used to declare that a specific variable is a JavaScript variable—not a mathematical or generic variable.

The three types of JavaScript variable keywords are:

  • var
  • let
  • const

Let's discuss the differences between the three keywords.

Var vs. Let vs. Const – What's the Difference?

Below are the main differences between JavaScript's var, let, and const variable keywords.

Hoisting – How does JavaScript hoisting work with var, let, and const variables?

When a var variable gets hoisted, JavaScript automatically assigns it the undefined value.

However, when the computer hoists a let or const variable, JavaScript puts it in a "Temporal dead zone"—until the variable gets fully initialized.

note

Temporal dead zone (TDZ) is the technical name of a block's scope where a variable is inaccessible.

For instance, consider this code:

{
console.log(bestColor);
var bestColor = "blue";
}

// The code above will return: undefined

Try it on StackBlitz

The snippet above returned undefined because JavaScript automatically assigned the value undefined to the variable immediately after hoisting var bestColor.

Let's now see what will happen if we substitute var with the let keyword.

{
console.log(bestColor);
let bestColor = "blue";
}

// The code above will return: ReferenceError

Try it on StackBlitz

The snippet above returned ReferenceError because immediately after hoisting let bestColor, JavaScript made the variable inaccessible.

So, what do you think would happen if we substitute let with the const keyword? Let's find out below.

{
console.log(bestColor);
const bestColor = "blue";
}

// The code above will return: ReferenceError

Try it on StackBlitz

The snippet above returned ReferenceError because immediately after hoisting const bestColor, JavaScript made the variable inaccessible.

Scope – What is the scope of a var, let, or const variable?

A var variable is function scoped. So, when defined in a function, only the function's code would have access to it.

let and const variables are block scoped. So, they are accessible only within their block ({...}).

Example: Blocks do not constrain var variables

if (true) {
var color = "Pink";
}

// Invoke the if statement's color variable:
console.log(color);

// The invocation above will return: "Pink"

Try it on StackBlitz

Notice that console.log called the color variable from outside the if statement's block.

console.log gained access to the color variable's value because var variables do not get constrained by anything—but functions.

In other words, since var is function scoped, only a function can prevent an external code from accessing its value.

Example: Var variable is function scoped

function getBestColor() {
if (true) {
var color = "Pink";
}
}

// Invoke the if statement's color variable:
console.log(color);

// The invocation above will return: ReferenceError

Try it on StackBlitz

The snippet above returned a ReferenceError because the function statement prevents all external code from accessing the var variable. Instead, only the function's local code can access the var variable.

Note that if you defined a var variable locally and globally. In that case, the local version will take precedence.

Here's an example:

var scopeType = "Global Scope";

function myScope() {
var scopeType = "Local Scope";
return scopeType;
}

console.log(myScope());

// The invocation above will return: "Local Scope"

Try it on StackBlitz

Keep in mind that any var variable you defined outside a function will be in the global scope. Therefore, such variable is known, visible, and accessible globally to all code.

CodeSweetly ads

Design in Figma, launch in Webflow

Bring your static designs to life with IX2, wire up content using our powerful CMS, and one-click publish onto the fastest hosting infrastructure.
Find out more

Example: Var variables that are not in any function are in the global scope

var colorOutsideFunc = "Blue";

function getBestColor() {
var colorInsideFunc = "Pink";
return colorOutsideFunc;
}

console.log(getBestColor());

// The invocation above will return: "Blue"

Try it on StackBlitz

The console.log code gained access to colorOutsideFunc because any var variable defined outside a function is globally available to all code.

Let's now see how scope works with a let variable.

if (true) {
let color = "Pink";
}

// Invoke the if statement's color variable:
console.log(color);

// The invocation above will return: ReferenceError

Try it on StackBlitz

The snippet above returned a ReferenceError because the block ({...}) prevents all external code from accessing the let variable. Instead, only the block's local code can access the let variable.

So, suppose you move the console.log code into the if statement's block. In that case, console.log will have access to the color variable.

Here's an example:

if (true) {
let color = "Pink";

// Invoke the if statement's color variable:
console.log(color);
}

// The invocation above will return: "Pink"

Try it on StackBlitz

Let's now see an example of a const variable.

if (true) {
const color = "Pink";
}

// Invoke the if statement's color variable:
console.log(color);

// The invocation above will return: ReferenceError

Try it on StackBlitz

The snippet above returned a ReferenceError because const is block scope. Therefore, the block ({...}) prevents all external code from accessing the const variable. Instead, only the block's local code can access the const variable.

Keep in mind that any let or const variable you defined outside a block will be in the global scope. Therefore, such variable is known, visible, and accessible globally to all code in the same script.

Example: Const (or let) variables not in any block are in the global scope

const colorOutsideFunc = "Blue";

function getBestColor() {
const colorInsideFunc = "Pink";
return colorOutsideFunc;
}

console.log(getBestColor());

// The invocation above will return: "Blue"

Try it on StackBlitz

The console.log code gained access to colorOutsideFunc because any let or const variable defined outside a block is globally available to all code within the same script.

Let's now discuss the difference between var, let, and const declarations.

Declaration – Can you declare a var, let, or const variable without assigning it a value?

You can declare a var or let variable without assigning it a value.

However, you must initialize a const variable with an initial value while declaring it. Otherwise, the computer will throw a SyntaxError.

For instance, consider this snippet:

// Declare a var variable without initializing it with a value:
var color;
// The declaration above will not throw any error.

// Check color's content:
console.log(color);

// The invocation above will output: undefined

// Initialize color with a value:
color = "Yellow";

// Recheck color's content:
console.log(color);

// The invocation above will output: "Yellow"

Try it on StackBlitz

Notice that the snippet above worked correctly—even though we declared the var variable without assigning it an initial value.

Let's now substitute the var keyword with let to see what will happen.

// Declare a let variable without initializing it with a value:
let color;
// The declaration above will not throw any error.

// Check color's content:
console.log(color);

// The invocation above will output: undefined

// Initialize color with a value:
color = "Yellow";

// Recheck color's content:
color;

// The invocation above will output: "Yellow"

Try it on StackBlitz

Observe that the snippet above also worked correctly.

Let's now find out what will happen if you declare a const variable without an initial value.

// Declare a let variable without initializing it with a value:
const color;

// The declaration above will throw a SyntaxError!

Try it on StackBlitz

The snippet above threw a SyntaxError because you cannot declare a const variable without assigning it an initial value.

Name redeclaration – Can you redeclare the name of a var, let, or const variable?

You can redeclare the name of a var variable. However, you are not allowed to redeclare the name of let and const variables.

For instance, the redeclaration of the color variable in the snippet below will work.

{
var color = "Yellow";
var color = "#FFFF00";
console.log(color);
}

Try it on StackBlitz

However, the redeclaration below will fail because you cannot redeclare the name of a let or const variable.

{
const color = "Yellow";
const color = "#FFFF00";
console.log(color);
}

Try it on StackBlitz

Also, note that the snippet below will fail because a variable named bestPet already exists in the script.

{
var bestPet = "Dog";
let bestPet = "Cat";
console.log(bestPet);
}

Try it on StackBlitz

Value reassignment – Can you reassign the value of a var, let, or const variable?

You can reassign the value of a var or let variable. However, you are not allowed to reassign the value of a const variable.

For instance, the reassignment of the color variable below will work.

{
var color = "Yellow";
color = "#FFFF00";
console.log(color);
}

Try it on StackBlitz

Likewise, the reassignment below will also run without any error.

{
let color = "SaddleBrown";
color = "#8B4513";
console.log(color);
}

Try it on StackBlitz

However, the reassignment below will fail because you cannot reassign the values of a const variable.

{
const color = "MidnightBlue";
color = "#191970";
console.log(color);
}

Try it on StackBlitz

Keep in mind that you can update the values of any object—even if the object is in a const variable.

Here's an example:

{
const color = ["MidnightBlue"];
color[0] = "#191970";

console.log(color);
console.log(color[0]);
}

Try it on StackBlitz

Window object – How does a var, let, or const variable work with the window object?

Suppose you declare a var variable in the global scope (out of a function). In that case, the computer will include it as one of the properties of the window object.

As such, the variable will be accessible globally by any code that can access the window object—which makes var vulnerable to any third-party intrusion.

However, suppose you declare a let or const variable in the global scope (out of a block). In such a case, the computer will not add it to the window object.

Therefore, the variable will only be available globally within its script file—not generally to any code that can access the window object.

Example: Global var variables become part of the window object—let and const do not

// Declare a var variable in the global scope:
var colorsArray = ["Pink", "Blue", "Orange"];

// Invoke the colorsArray variable from the window object:
console.log(window.colorsArray);

// The invocation above will return: ["Pink", "Blue", "Orange"]

Try it on CodePen

Notice that we were able to invoke colorsArray from the window object. The invocation worked because colorsArray is a var variable that we defined in the global scope.

Let's now substitute var with the let keyword to see what will happen.

// Declare a var variable in the global scope:
let colorsArray = ["Pink", "Blue", "Orange"];

// Invoke the colorsArray variable from the window object:
console.log(window.colorsArray);

// The invocation above will return: Undefined

Try it on CodePen

Observe that the snippet above returned undefined because the computer would not include a let or const variable as a property of the window object.

Keep in mind that any function declared in the global scope will become one of the properties of the window object.

Therefore, suppose you define your variable in a globally scoped function. In such a case, the variable could be executable by any code that can access the window object—regardless of whether the variable is var, let, or const.

Example: Global functions become part of the window object

// Declare a function in the global scope:
function getColor() {
let colorsArray = ["Pink", "Blue", "Orange"];
return colorsArray[1];
}

// Invoke the getColor function from the window object:
console.log(window.getColor());

// The invocation above will return: "Blue"

Try it on CodePen

Notice that we were able to invoke colorsArray from the window object through the globally scoped getColor function.

Suppose you wish to prevent global access to your function's local code. In such a case, define that function in a const or let variable like so:

// Declare a function inside a const variable:
const getColor = function () {
let colorsArray = ["Pink", "Blue", "Orange"];
return colorsArray[1];
};

// Invoke the getColor function from the window object:
console.log(window.getColor());

// The invocation above will return:
// "Uncaught TypeError: window.getColor is not a function"

Try it on CodePen

Observe that the snippet above returned a TypeError. The error is because the computer does not include const variables as one of the properties of the window object.

However, you can execute the function from your script successfully like so:

console.log(getColor());

// The invocation above will return:"Blue"

Variable naming – How to name a var, let, or const variable

A standard convention for naming const variables is to use all-uppercase letterings.

Here's an example:

const COLORS_ARRAY = ["Pink", "Blue", "Orange"];

console.log(COLORS_ARRAY);

// The invocation above will return: ["Pink", "Blue", "Orange"]

Try it on StackBlitz

Apart from the const convention stated above, all your variable names should conform to these general guidelines:

  • Variable names must start only with a letter, dollar sign ($), or an underscore (_).
note

Avoid starting your variable name with an underscore because it means specific things in some JavaScript construct. Therefore, using it to begin a variable's name may cause some confusion.

  • Names can contain uppercase or lowercase letterings. However, use only Latin characters (a-z, A-Z, 0-9). By so doing, your variable name will be easy for most developers to understand.
  • Variable names are case-sensitive. Therefore, game and Game are different variables.
  • You cannot use JavaScript reserved keywords as a variable name.

Which is the best – var, let, or const?

A good coding habit is to minimize mutable states.

In other words, it's best to minimize random alterations of your variables.

Therefore, const is the recommended declaration keyword for your variables—as it is the only one that prevents variable reassignments.

However, suppose you need to permit the reassignment of your variable. In such a case, use let.

Generally, it's best to avoid var as it makes your variable highly mutable—which can expose your program to third-party intrusions.

Overview

This article discussed what a JavaScript variable is. We also looked at the differences between var, let, and const variables.

Your support matters: Buy me a coffee to support CodeSweetly's mission of simplifying coding concepts.

Join CodeSweetly Newsletter