DEV Community

Lody G Mtui
Lody G Mtui

Posted on • Edited on

You either 'let', 'var' or keep 'const' in JavaScript

Difference between var, let and const

In JavaScript, variables are assigned using three main keywords/ways which are:-

  • var
  • let
  • const.

But, var has became the old way to declare a variable due to the introduction of JavaScript ES6.

Many features were introduced such as let and const which have became de-facto ways for variable declarations.

Note Variable is the value that occupies space into the computer memory i.e. container that is used to store data.

There is difference between var, let and const in JavaScript. These differences between all these keywords, are based on the following concepts:-

Scope

This refers to the way in which variables are accessed i.e. It's how we determine the accessibility of variables.
In JavaScript, there are three scopes:

  1. Global Scope
  2. Function Scope
  3. Block Scope

Global Scope

This refers to when variables are declared outside the function block and can be accessed anywhere within the program.

var age = 19;
let game = 'fifa';
const pie = 3.14;

function getAll(){
    console.log(age);
    console.log(game);
    console.log(pie);
}
console.log(age);
console.log(game);
console.log(pie);
getAll();
Enter fullscreen mode Exit fullscreen mode

Note:Any of var, let or const are used to declare global variables which can be accessed anywhere in the program.

Function Scope

This refers to when variables are declared inside the function scope and can only be accessed within a function. Also known as local scope.

function getAge(){
    var name = "John";
    console.log(name);
}
// console.log(name); // ReferenceError: name is not defined
getAge();
Enter fullscreen mode Exit fullscreen mode

Note:Only var is function scoped i.e. a variable declared by var in function block can accessed only in function itself and cannot be accessed outside the function i.e. It throws a ReferenceError

Block Scope

This refers to when variables are declared in the block or curly brackets and cannot be accessed outside it. A block can be function or control structures such as if, for, while etc.

function gaming(){
    let name = "John";
    const age = 19;
    console.log(name);
    console.log(age);
}
// console.log(name); // ReferenceError: name is not defined
// console.log(age); // ReferenceError: name is not defined

if(true){
    let name = "Paul";
    console.log(name);
}
// console.log(name);
gaming();
Enter fullscreen mode Exit fullscreen mode

Note:Both let and const are block scoped i.e. a variable declared by let or const in a block can accessed only in the block and cannot be accessed outside the block i.e. It throws a ReferenceError

Hoisting

This refers to the behavior to move up the declarations to the top of the scope before code execution. It's a tendency that allows variables and functions to be used before their declaration i.e. the variables/ functions declarations are moved up to the start of code block before execution regardless where they are declared in the code block.

  • var allows hoisting
name = "John";
console.log(goal);
var name;
Enter fullscreen mode Exit fullscreen mode
  • let and const don't allow hoisting
goal = "business";
console.log(goal);
let goal;
Enter fullscreen mode Exit fullscreen mode
goal = "business";
console.log(goal);
const goal;
Enter fullscreen mode Exit fullscreen mode

Declaration & Accessibility

The variables declared using var can be declared without initialization.

var age;
console.log(age); // undefined
Enter fullscreen mode Exit fullscreen mode

Note: The variables declared using var can be accessed without initialization and returns undefined.

Also those using let can be declared without initialization.

let age;
console.log(age); // undefined
Enter fullscreen mode Exit fullscreen mode

Note: The variables declared using let cannot be accessed without initialization and returns error.

And those using const cannot be declared without initialization.

const pie;
console.log(pie); // SyntaxError: Missing initializer in const declaration
Enter fullscreen mode Exit fullscreen mode

Note: The variables declared using const cannot be accessed without initialization as it cannot declared without initialization.

Re-declaration

The variables declared using var can be re-declared and updated.

var age = 19;
var age = 20;
age = 30;
Enter fullscreen mode Exit fullscreen mode

While those using let cannot be re-declared but can be updated.

let game = 'fifa';
game = 'pes';
Enter fullscreen mode Exit fullscreen mode

And const can neither be re-declared nor updated.

const pie = 3.14;
const pie = 2.15; // SyntaxError: Identifier 'pie' has already been declared
pie = 10; // TypeError: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode

Summary

Image description

Image credit: GeeksforGeeks

Top comments (14)

Collapse
 
moopet profile image
Ben Sinclair

And const can neither be re-declared nor updated.

Const can be updated if it's an object or array. This is fine, for example:

const foo = [];

foo.push("hello");
Enter fullscreen mode Exit fullscreen mode

So const is kinda-sorta-const, depending where you learned the word "constant". You can't redeclare it or make it point at anything else, but you can modify it if it's a container for other things.

Collapse
 
jzombie profile image
jzombie

Const gives you a constant memory reference. You can't reassign the memory reference, but any properties can be [re]assigned. The constant value assumption is only for primitive types.

To freeze objects: developer.mozilla.org/en-US/docs/W...

Collapse
 
lodyne profile image
Lody G Mtui

I'll check on this. Thanks for the feedback

Collapse
 
mistval profile image
Randall • Edited

It's not a reference to specific memory. The thing pointed to by a const variable can and often will move locations in memory (for example if you keep pushing onto an array, the engine will eventually have to allocate a new, bigger block of memory for it). It's just a constant reference to a specific value.

Thread Thread
 
jzombie profile image
jzombie

Thanks for the clarification.

Collapse
 
lodyne profile image
Lody G Mtui

Thanks for this information, I will learn it and update it

Collapse
 
peerreynders profile image
peerreynders

Too confusing an explanation...

const means that the name-to-value binding is immutable—not the value.

All JavaScript primitive values are immutable to begin with—so once the binding is immutable nothing can change for primitive values.

So with let and var primitive values don't actually mutate but reassignment mutates the binding to a different value instead.


1) MDN: const:

"The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. "

2) MDN: JavaScript data types and data structures

"All types except objects define immutable values (that is, values which can't be changed)"

Collapse
 
moopet profile image
Ben Sinclair

Whatever the technical explanation, it's added confusion for people new to programming in Javascript that something can be called "constant" but can be different depending where it's accessed in a function!

Thread Thread
 
peerreynders profile image
peerreynders • Edited

it's added confusion for people new to programming in Javascript that something can be called "constant".

It's not called a "constant", it's a const declaration.

The expectation of a "constant" probably comes from the C/C++ const type qualifier.

"JavaScript is most despised because it isn’t some other language. If you are good in some other language and you have to program in an environment that only supports JavaScript, then you are forced to use JavaScript, and that is annoying. Most people in that situation don’t even bother to learn JavaScript first, and then they are surprised when JavaScript turns out to have significant differences from the some other language they would rather be using, and that those differences matter."

Douglas Crockford, JavaScript - The Good Parts, 2008; p.2:

JavaScript has its share of warts but it doesn't help when people coerce familiar mental models onto it that don't align with its actual behaviour (which extends to class-based object-orientation). JavaScript is its own thing.

Unfortunately beginners are often told to think of a "variable" as a box that holds a value (probably based on the value in a register idea). But the const confusion demonstrates that the "sticky note with a name which gets moved from one value to the next" mental model would probably be superior.

but can be different depending where it's accessed in a function!

😕

Thread Thread
 
moopet profile image
Ben Sinclair

That expectation is because "const" isn't a word except as a truncation of "constant". There's nothing you can assume about it coming from another language or coming to Javascript as your first language that doesn't hinge on the word, "constant".

Thread Thread
 
peerreynders profile image
peerreynders • Edited

Coming from other languages I was holding the same prejudice, a source of continual annoyance.

Until I finally realized it meant "constant binding", not "constant value".

All of a sudden from that perspective the behaviour is entirely consistent.

A lot of things start to make sense when one takes into account that Brendan Eich was hired for "doing Scheme in the browser" but then had to comply with the "diktat from upper engineering management was that the language must 'look like Java'."

We also have Java to blame for null entering into the language. One bottom-most value (undefined) ought to be enough.

Thread Thread
 
moopet profile image
Ben Sinclair

Wasn't const added waaaay later though, like in ~2010 or something?

Thread Thread
 
peerreynders profile image
peerreynders

ES2015 (ES6) actually.

But I imagine that the whole primitive values are immutable thing was established much, much earlier—leading to a situation where creating a "constant binding" was easy and relatively cheap in terms of run-time performance.

Facilities for creating immutable objects exist (Object.freeze() which is only shallow) but come with run-time overhead.

Collapse
 
steveknoblock profile image
Steve Knoblock

The computer science definition of constant existed for forty years or more before JavaScript decided to use the same term for something different than most computer languages and in mathematics.