Categories
Codes Javascript

JavaScript: var, let, const

“You get whatever accomplishment you are willing to declare.”

– Georgia O’Keeffe

Introduction

ES6 in JavaScript has given new ways of declaring a new variable. Now, let and const has also become available.

Personally I really like this new additions in JavaScript, because I think JavaScript codes in ES6 are easier to trace, without the need to worry about accidental redeclaration of variable because of var. We’ll learn more about that soon.

So, what is the difference between var, let, and const? You will know about this more as you keep reading. And I differentiate them in terms of use, scope, and hoisting.

Var

Before ES6, var was the only way to declare a new variable. It’s quite simple, although there are some rather invisible stuffs hidden behind, waiting for the newbies learn it the hard way by discovering and understanding them on their own. We’ll learn more about that just a bit later.

The snippet below shows you how to declare a variable with var.

var x; // declaration
x = 5; // value assignment

// combined declaration & assignment
var x = 5;

Uses

Variables declared with var can be reassigned and redeclared, as long the variable is within the scope of the declaration. It is shown like this example below:

var m = "declare m";
var m = "redeclare m"; // this will not return an error

function reassign(){
  var x = 1;
  console.log(x); // 1

  x = 5;
  console.log(x); // 5
}

reassign();

Scope

There are two kinds of scope of var: global scope and function scope. Global scope means that the declared variable can be used anywhere, it’s at the top. Function scope is limited in the function where the variable is declared. The example below should give you more understanding:

var globalScope = 'global';

function sampleFunc(){
  var functionScope = 'function';

  console.log(globalScope); // "global"
  console.log(functionScope); // "function"
}

sampleFunc(); // will print "global" and "function"

console.log(globalScope); // "global"
console.log(functionScope); // undefined

As you can see, the variable globalScope can be accessed in sampleFunc(), but variable functionScope cannot be accessed outside sampleFunc() so it returns undefined.

Hoisting

What is hoisting? Hoisting is a mechanism used by JavaScript to move all variables and functions declaration to the top of their scope. It is best explained with the example below:

console.log(x); // undefined
var x = 5;

The snippet above is actually interpreted like this:

var x;
console.log(x); // undefined
x = 5;

The problem with var

At first glance, var does not seem to have any problems when declaring a variable. S0, why they need to add let & const?

Let’s say you have this kind of script:

var x = 0;
console.log("Global x: " + x); // Global x: 0

if (x == 0){
  var x = 5;
  console.log("Function x: " + x); // Function x: 5
}

console.log("Global x: " + x); // Global x: 5

Do you notice the var x declaration inside the if-block? It does not return an error. And the x variable inside the if-block is interpreted as the x from var x = 0, the more global scope one.

This problem could occur when the code is getting complex in real-life implementation. One might accidentally redeclaring a new variable with the same name, probably forgotten and have not touched the code in a long time, and messed up everything but without an error shown.

So, it’s much better to use let and const instead of var.

Let

“Let it go, let it goooo!”

– Elsa, from Frozen

ES6 introduces let as the alternative of var to declare a variable. Though it’s not alternative for me, it’s an improvement for it. The example below shows a declaration with let:

let x; // declaration
x = 3; // value assignment

let x = 3; // declaration and value assignment.

If you are used to declaring with var, just change var with let. Simple.

Uses

Like var, the value of a let variable can be reassigned. Unlike var, a let variable cannot be redeclared. See this example below:

let x = 0;
x = 5; // x's value is 5

---------------------------------

let x = 0;
let x = 10; // Uncaught SyntaxError: Identifier 'x' has already been declared

Redeclaring a variable with the same name will result in a SyntaxError, implying it has already been declared and cannot be redeclared.

Scope

let is block-scoped. It means the variable declared is only usable inside that block. What is a block, you ask? A block is the part of code where it begins with { and ends with }. See this example below:

let x = 0;

if (x == 0){
  let x = 5;
  console.log(x); // 5
}

console.log(x); // 0

The x inside the block is interpreted as a different x from let x = 0. It will not return an error, and the x = 0 keeps its value.

Hoisting

Like var, let variables are also hoisted to the top. Also, unlike var which will be interpreted as undefined when initialized, let is not initialized. Which is why it will return as ReferenceError if it happens:

console.log(x); // Uncaught ReferenceError: Cannot access 'x' before initialization
let x = 0;

Const

The other alternative of declaring variable is const. You might wonder why there is const, when let pretty much already do the job as a better var. Just keep on reading. Here is an example of declaring a const variable.

const a = 10; // declaration & value assigment

Uses

const variable can be only declared and assigned once. It means it cannot be redeclared and reassigned like var and let.

const a = 5;
const a = 3; // Uncaught SyntaxError: Identifier 'a' has already been declared

---------------------------
const a = 7;
a = 9; // Uncaught TypeError: Assignment to constant variable.

Scope

Like let, const is also block-scoped. Exactly the same, see the example below:

const x = 0;
if (x == 0){
  const x = 5;
  console.log(x); // 5
}

console.log(x); // 0

The x inside the block is interpreted as a different x from const x = 0. It will not return an error because it’s not reassigned, and the x = 0 keeps its value.

Although, there is an exception when you are dealing with object and array. The properties’ values can be reassigned even though the object or array is a const. See the example below.

const x = {
  propA: 5,
  propB: 3
};

console.log(x.propA); // 5
x.propA = 500;

console.log(x.propA); // 500

No errors returned. Safe.

But a const object cannot be reassigned as a whole, it will return an error. This is what I mean:

const x = {
  propA: 5,
  propB: 3
};

// Uncaught TypeError: Assignment to constant variable.
const x = { 
  propC: 9
};

Hoisting

Like let, const also gets hoisted to the top, but not initalized. It will return ReferenceError when it happens.

console.log(x); // Uncaught ReferenceError: Cannot access 'x' before initialization
let x = 0;

Which One Should I Use?

We learned all of the ways on declaring a variable in JavaScript. So, which one should we use?

Personally, I would start declaring a new variable with const, and assign it a value. Most of the time the value rarely changes. As the coding goes on, when I think it’s needed to reassign the variable, I will change const to let.

What about var? I don’t use it anymore. Maybe a little, for writing this post only.

Conclusion

Last part! A post will not end without conclusions. I will give you a table to simplify things:

varletconst
ScopeGlobal / FunctionBlockBlock
Can be RedeclaredYesNoNo
Can be ReassignedYesYesNo, but can reassign property in an object.
HoistingAs undefinedCannot be initializedCannot be initialized

There, you are welcome.

The update of let and const gives us more choice and safety in JavaScript programming. For me, it helps a lot because:

  • Less worry about bugs happening because of redeclaration.
  • A const variable lets me know that the value does not change.
  • A let variable means the variable will change somewhere in the block.

Thanks a lot for reading, hope you learned something new and use it to code better! Live the code and code your life!

The opportunity to declare a truth may come when we least expect it. Let us be prepared.

– Thomas S. Monson

By Ericko Yap

Just a guy who is obsessed to improve himself. Working as a programmer in a digital banking company. Currently programming himself in calisthenics, reading books, and maintaining a blog.

Leave a Reply

Your email address will not be published. Required fields are marked *