JavaScript Variables

A variable is a value assigned to an identifier, so you can reference and use it later in the program.

In a simple way variable is like a box or container that we can use to store data inside.

This is because JavaScript is loosely typed, a concept you'll frequently hear about.

A variable must be declared before you can use it.

We have 2 main ways to declare variables. The first is to use const:


const a = 0;

The second way is to use let:


let a = 0;

What's the difference?

Let's deep dive into the explainition and understand what are their difference.

const defines a constant reference to a value. This means the reference cannot be changed. You cannot reassign a new value to it.

While using let you can assign a new value to it.

For example, you cannot do this:


const a = 0;
a = 1;
console.log(a);

Because you'll get an error: TypeError: Assignment to constant variable this error means that you can not re-assign another value to the const variable Keyword.

Example


const a = 0;
a = 1;
console.log(a);

On the other hand, you can do it using let:


let a = 0;
a = 1;
console.log(a);

Example


let a = 0;
a = 1;
console.log(a);

constdoes not mean "constant" in the way some other languages like C mean. In particular, it does not mean the value cannot change - it means it cannot be reassigned. If the variable points to an object or an array (we'll see more about objects and arrays later) the content of the object or the array can freely change.

constConst variables must be initialized at the declaration time:


const a = 0;

but letvalues can be initialized later:


let a;
a = 0;

You can declare multiple variables at once in the same statement:


const a  = 1,
  b = 2;

let c  = 1,
  d = 2;

Example


const a  = 1,
b = 2;
console.log(a);
console.log(b);

let c  = 1,
d = 2;
console.log(c);
console.log(d);

But you cannot redeclare the same variable more than one time:


let a  = 1;

let a  = 2;

or you'd get a "duplicate declaration" error.

My advice is to always use constif you don't or intended to change it later and only use letwhen you know you'll need to reassign a value to that variable. Why? Because the less power our code has, the better. If we know a value cannot be reassigned, it's one less source for bugs.

Now that we saw how to work with constand letI want to mention var.

Until 2015, varwas the only way we could declare a variable in JavaScript. Today, a modern codebase will most likely just use constand let. There are some fundamental differences which we will elaborate in blog post within our website, but if you're just starting out, you might not care about them. Just use constand let.