Javascript var, let & const

For a long time, we all know var keyword in javascript to declare a variable. However, ES6 (ECMAScript 2015) introduces 2 new keywords to declare variables, namely let & const.
There are several differences between var, let & const, which we can classify into several types, namely related to scope, hoisting, the ability of these variables to be reassigned & redeclare. Below I will try to explain them one by one.
Scope
Scope is the current context of code, which determines the variable’s accessibility to JavaScript. In short, I often refer to scope as a place for variables to live, where they can be called/accessed.
The keyword var has a function scope, that is, it only recognizes function blocks (other than global scope) as its scope, while let & const has block scope, that is, every block marked with curly brackets { … } is also considered as a context/scope.

Hoisting
Hoisting is a process in which javascript appears to move a function, variable, or class declaration to the top/beginning of the scope, prior to code execution. So we can call them first in the code, even before they are declared without throwing an error.
This applies to variables declared with var, but not to let & const.

Look at the code above. y & z will throw an error when called. While x won’t throw an error, but produces an undefined print out on the console. Why is that? This is because hoisting only occurs in the variable declaration of x, but the assignment process still occurs below, resulting in undefined (but no error) when x is called on the console.log method, or more or less it can be described as follows.

Reassign & Redeclare
Variables declared using the var & let keywords can be reassigned or changed values, while const cannot. Because as the name implies, const is intended for a variable whose nature is a constant or a number whose value remains / does not change.

Meanwhile, let & const both cannot be redeclared. This is intentionally done to avoid mistakes that often occur in the use of var, specifically the use of the same name for new variables, causing the variable to be accidentally redeclared.

Comments
Post a Comment