Different Ways Of Creating Variables In JavaScript

What makes one different from another?

Rukayat Lukman
Webtips
8 min readJul 1, 2020

--

You can declare a variable in JavaScript using three ways: using var, using let, using const. In this article, we will discuss the three ways of creating variables in JavaScript and their differences.

Firstly, we need to know what a variable is and how it can be created. Simply put, variables are containers for storing data values. Variables can be thought of as named containers, you can place data into these containers and then refer to the data simply by naming the container. Before you use a variable in a JavaScript program, you must declare(create) it. Variables are declared using reserved keyword var, let or const — Creating a variable in JavaScript is called “declaring” a variable. JavaScript variables can hold;

  • Numbers, e.g. 123, 120.50 etc.
  • Strings of text e.g. “This text is a string” etc. Note that strings are either wrap in single (‘ ’) or double quotes (“ ”)
  • Boolean e.g. true or false.
  • Undefined — By default, when a variable is declared but not assigned, it is assigned the value of undefined.
  • Null represents an intentional absence of a value — it is usually set on purpose to indicate that a variable has been declared but not yet assigned any value.

Before moving on, we need to know the general rules for constructing names for variables (unique identifiers)

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter, they cannot start with a number.
  • Names can also begin with $ and _
  • Names are case sensitive (y and Y are different variables)
  • Reserved words (like JavaScript keywords e.g break, switch, let, var, const, if, else, return, this, throw, void, while, e.t.c) cannot be used as names
  • Names cannot have space inside of them(e.g first name). When naming an identifier with two words in it, it’s a best practice to use camel case. With this convention, the first letter of each word, excluding the first word, is uppercase. Example: firstName, myOtherVariableName

Declaration of variables

  1. Declaration: The variable is registered using a given name within the corresponding scope (variable scope is explained in my article→https://bit.ly/JavaScript-Variable-Scope).
  2. Initialization: When you declare a variable it is automatically initialized, which means memory is allocated for the variable by the JavaScript engine. Because of this, once a variable is declared, it takes a value of undefined even before assignment.
  3. Assignment: This is when a specific value is assigned to the variable. To assign a value to the variable, use the equal sign (assignment operator)

Examples:

using var keyword

var firstName;              
// Declaration and initialization
firstName = "Rukayat";
// Assignment

using let keyword

let firstName;              
// Declaration and initialization
firstName = "Rukayat";
// Assignment

using const keyword

It is important to note that when using const keyword, the variable must be assigned a value at the point of declaration, else, it will throw a syntax error. Therefore;const firstName;         
firstName = "Rukayat";
// This syntax is wrong for const variables and will throw an error
const firstName = "Rukayat";
//This is the correct syntax

You can also assign a value to the variable when you declare it:

using var keyword

var price     = 5;              // Number
var firstName = "Rukayat"; // String
var developer = true | false; // Boolean
var location = null; // Null
var blue; // undefined

using let keyword

let price     = 5;              // Number
let firstName = "Rukayat"; // String
let developer = true | false; // Boolean
let location = null; // Null
let blue; // undefined

using const keyword

const price     = 5;              // Number
const firstName = "Rukayat"; // String
const developer = true | false; // Boolean
const location = null; // Null
const blue; // undefined

You can declare many variables in one statement. Start the statement with var or let or const and separate the variables by comma:

using var keyword

var price = 5, firstName = "Rukayat", developer = true;

using let keyword

let price = 5, firstName = "Rukayat", developer = true;

using const keyword

const price = 5, firstName = "Rukayat", developer = true;

A declaration can span multiple lines instead of one long line(as implied in the examples above)

using var keyword

var price = 5, 
firstName = "Rukayat",
developer = true;

using let keyword

let price = 5, 
firstName = "Rukayat",
developer = true;

using const keyword

let price = 5, 
firstName = "Rukayat",
developer = true;

As we must have noticed, the examples above have the same syntax of declaring and assigning variables. That’s what is common about the three ways(var, let, const) of creating variables. Now let’s see what makes them different from one another.

Difference between var, let and const in JavaScript

  • The first thing we can do with var that we cannot do with let or const is re-declaring a variable that has already been created. Example;
var firstName = "Rukayat";
var firstName = "Dasola";
console.log(firstName);
//this code will print Dasola

If the code above is created with let or const, it will throw a SyntaxError: Identifier ‘firstName’ has already been declared.

let firstName = "Rukayat";
let firstName = "Dasola";
console.log(firstName);
//this code will throw a syntax error
const firstName = "Rukayat";
const firstName = "Dasola";
console.log(firstName);
//this code will throw a syntax error

With var, JavaScript accepts what you’ve done, even though it might not be what you wanted to do . Variables might accidentally got overridden resulting in change of values and might be difficult to track down when working with programs that deal with lots of different variables. But with let and const, JavaScript will let u know, so you can change the variable name to something else.

  • Another difference is that var variables are function-based scope not block-based scope. That is many things like if statement which create code blocks don’t actually create a new scope when working with var. If we don’t create a new function, we don’t create a new scope. (You can read my article on variable scope to understand what variable scope is all about → https://bit.ly/JavaScript-Variable-Scope )

Example:

if (10 === 10) {
var firstName = "Rukayat";
}
console.log(firstName);
//this code will print Rukayat

Since we don’t create a function in the above example, everything is in the exact same scope. Meaning that we do have access to firstName anywhere even though it was defined in the if statement.

function setName(){
var firstName = "Rukayat";
}
setName();
console.log(firstName);
//this code will throw a reference error

In this example, the code will throw a ReferenceError: firstName is not defined. This is because var variables are function scoped, therefore, the variable cannot be accessed anywhere else except within the function

function setName(){
var firstName = "Rukayat";
console.log(firstName);
setName();
//this code will print Rukayat

But let or const, are both block scoped. That is many things like if statement which create code blocks will create a new scope as do function. Example:

if (10 === 10) {
let firstName = "Rukayat";
}
console.log(firstName);
//this will code throw a reference error
function setName(){
let firstName = "Rukayat";
}
setName();
console.log(firstName);
//this code will throw a reference error

The if statement create a new block as do function, therefore, we will not be able to access firstName anywhere else except where it’s defined. In the example, the code will throw a ReferenceError: firstName is not defined.

if (10 === 10) {
let firstName = "Rukayat";
console.log(firstName);
}
//this code will print Rukayat
function setName(){
let firstName = "Rukayat";
console.log(firstName);
}
setName();
//this code will print Rukayat
  • Accessing a variable before it’s declared is possible with var. When we create a variable with var, its declaration get twisted to the top of the scope. Example:
console.log(age);  
var age;
//this code will print undefined

So in reality, the code above still looks like this:

var age;
console.log(age);
//this code will print undefined

That is why the first code will print undefined even though age was accessed before the declaration. Let’s check another example out;

console.log(age);
var age = 15;
//this code will print undefined

The code above will still print undefined even though we have assigned a value of 15 to age. This is because, in reality, the code above looks like this:

var age;
console.log(age);
age = 15;
//this code will print undefined

This proves that it’s only the declaration that gets twisted to the top of the scope and not the assignment. Another example is:

age = 15;
console.log(age);
var age;
//this code will print 15

This will print 15 because the age declaration is twisted to the top in reality like this:

var age;
age = 15;
console.log(age);

But all these are impossible with let or const. If we try to access a let or const variable before it’s declared, we get a ReferenceError: Cannot access ‘age’ before initialization.

  • So far, we’ve seen how a var variable is different from a const and let variable. But how does a const variable differ from a let and var variable?

As the name implies, const means constant, that is something that cannot change. Therefore a const variable cannot be reassigned. Example:

const firstName = "Rukayat";
firstName = "Dasola";
console.log(firstName);
//this will throw an error

The code above will throw a TypeError: Assignment to constant variable. This is because once we create a variable with const, such a variable cannot be reassigned (changed).

But with var or let, reassignment of a variable is possible because they are not constant, that is their values can be changed using the appropriate syntax. Example:

let firstName = "Rukayat";
firstName = "Dasola";
console.log(firstName);
//this will print Dasola

It is important to note that although we cannot reassign a const variable, but we can reassign a const object properties. That is, if the constant variable is an object, we can still manipulate the object by giving its property/properties a new value. Example:

const person = {
firstName: "Rukayat",
lastName: "Lukman",
age: 10
}
person.firstName = "Dasola";
person.age = 15;
console.log(person);

When we console.log(person), the result will print { firstName: ‘Dasola’, lastName: ‘Lukman’, age: 15 } because we were able to change firstName from Rukayat to Dasola and age from 10 to 15.

Note that the properties values cannot be changed like this:

const person = {
firstName: "Rukayat",
lastName: "Lukman",
age: 10
}
person = {
firstName: "Dasola",
lastName: "Lukman",
age: 15
}
console.log(person);
//this will throw an error

This code will throw a TypeError: Assignment to constant variable. Therefore, a const object properties cannot be changed using the second method but with the first method.

From what we have discussed so far, we can conclude that var has its own flaws, making it a less an ideal way to create a variable in JavaScript. Therefore let should be preferred when declaring a variable that will be reassigned and const should be used for variables that we are sure will not be reassigned (constant variables)

Thanks for reading.

--

--

Rukayat Lukman
Webtips
Writer for

A Junior Front End Web Developer || Code lover || Student of knowledge