Mangcoding

icon chat
Yayan Kurnia Akbar - Thursday, 27 February 2025 - 4 months ago

Getting to Know JavaScript Variables: Var, Let, and Const

single image
Photo By Clément Hélardot on Unsplash

Starting to learn any programming language requires understanding JavaScript variables. What is a variable? What is its purpose? How do we use variables? These three aspects must be fully understood. Let’s begin with what a variable is.

Link Mangcoding

What is a JavaScript Variable

A variable is a concept that can be likened to a container or storage in programming, used to store data or a piece of information. It is then kept in the computer’s memory while the program is running. If illustrated, its representation can be seen in the image below.

Apa itu Variable Javascript

The illustration of the three glasses above represents a variable, where the first glass depicts a variable that has not been assigned a value (in JavaScript, this is referred to as undefined).

The next two glasses contain different types of beverages, just like variables that can hold any type of value, whether it is a number, string, boolean, null, undefined, symbol, array, or object.

When using variables, they must be declared by assigning an identity or a name as an identifier. Variable names must be unique and cannot be duplicated. In JavaScript, variables also need to be introduced so that we can assign values and use them properly.

The naming of a variable is called an identifier. Below is an example of variable declaration in JavaScript.

Variable Example

Declaring a variable in JavaScript can be done in three ways: using the keywords var, let, and const.

Each of these keywords has its own differences when declaring a variable. Let’s discuss these differences.

Link Mangcoding

Using Var

Before the introduction of ES6 features in JavaScript, variables were declared using the var keyword.

var mahasiswa = “iqbal”;

You can also declare multiple variables in a single statement.

var nama = "iqbal", kelas = 10; 

console.log(nama); // output -> iqbal
console.log(kelas); // output -> 10

Writing multiple variables in a single statement is not recommended. In my opinion, writing code this way can make it difficult for other programmers to read.

Currently, using var is considered ineffective for declaring variables due to certain issues. For example, if you forget to use var when declaring a variable, you end up assigning a value to an undeclared variable.

mahasiswa = "iqbal"; // output -> iqbal
// Example of an undeclared variable

The code above does not produce an error because JavaScript treats it as a global variable. In a modern environment, if you enable strict mode using the use strict directive, declaring a variable without var will result in an error. Take a look at the following code :

'use strict' 

nama = 'iqbal'; // output -> ReferenceError: nama is not defined

The code above will produce an error because JavaScript does not recognize the undefined variable nama. In such cases, you need to initialize nama as a variable using var, let, or const.

Another issue with using the var keyword in variable declarations is that you can redeclare a variable with the same identifier, as shown in the following example.

var nama = "iqbal"; 
var nama = "niyaz";
console.log(nama); // output -> niyaz

The above code snippet will produce the output “niyaz.” Even though the initial declaration of the variable nama was assigned the value “iqbal,” we can still redeclare the variable with the same identifier, nama, and assign it a different value. This process is known as reassignment.

Reassignment is considered poor coding practice. In cases where the codebase is complex, maintaining the code can become challenging when debugging or developing an application.

The points above highlight some weaknesses of var, such as reassignment and undeclared variables. However, there are additional issues if we continue using var. Therefore, we must understand the concepts of hoisting and scope in JavaScript.

These two concepts will also help explain the differences between using var and let.

Scope: The Concept of Scope in JavaScript

In JavaScript, a variable initialized using var is assigned to the global object.

To prevent a variable from becoming a global object, we need a new scope. This can be achieved by creating a function to limit the variable’s scope. For further explanation, consider the following code.

var nama = "iqbal";
// Membuat fungsi namaOrang
function namaOrang() {
var nama = "niyaz";
console.log(nama);
}
// Menampilkan fungsi namaOrang
namaOrang(); // output -> niyaz
// Menampilkan variable nama
console.log(nama); // output -> iqbal

The code above shows that we can create a variable named nama with the value “iqbal”, which acts as a global object or global variable.

However, the nama variable inside the namaOrang function creates a new scope, making it a local variable that can only be used within the function.

It is important to note that initializing a variable with var makes it function-scoped. This means that we need to create a function to ensure that the variable remains local to that function, setting a boundary so it can only be used within that function.

Hoisting

When you declare a variable in JavaScript, what happens is that JavaScript “hoists” all variable declarations to the top before executing the code. Even if you place a variable declaration at the end of the script, JavaScript will still move it to the top before execution.

hallo = "hello world" // mengisi variable hallo
console.log(hallo); // menampilkan variable hallo var hallo
// variable hallo akan diangkat keatas sebelum dieksekusi

Here is an explanation of why you should stop using var to declare variables. Next, we will move on to using let. Kuy lah…..

Link Mangcoding

Using Let

Let is a new feature introduced by ES6, essentially an improvement over var.

The difference lies in scope. While var has function scope—meaning if it is declared outside a function, it becomes a global object—let has block scope.

Block scope with let means its scope is limited to the block where the let variable is defined. This block scope concept provides a solution to the issues encountered with var.

For example, when declaring variables with the same identifier.

let nama = "iqbal"; 

let nama = "niyaz";

console.log(nama); // output -> SyntaxError: Identifier 'nama' has already been declared

Reassigning the same identifier, as seen in the code above, only applies when using var.

However, if you use let, an error will occur because the variable nama has already been declared, and you cannot declare a variable with the same identifier again.

In modern JavaScript development, it is recommended not to use var for declaring variables. JavaScript developers should use let instead, as it follows block scope, eliminating the need to create functions just to define local variables.

The concept of hoisting also does not apply to let. Take a look at the following code

nama = "iqbal"; 

let nama;

console.log(nama); // output -> ReferenceError: nama is not defined

Which one is better, var or let? You should switch to using let when initializing a variable! Tired already? Wait… there’s still one more topic left—const. Shall we continue? Let’s go!

Link Mangcoding

Using const

The easiest way to understand const is that you cannot change the value of a variable once it has been assigned. While var and let allow modifying a variable’s value, const does not. This is because const stands for “constant,” meaning it remains unchanged.

const nama = "iqbal"; 

nama = "niyaz";

console.log(nama); // output -> TypeError: Assignment to constant variable.

However, there is an exception for object data types (arrays and objects). A const variable allows data modification using the methods provided by arrays and objects, which is known as mutable.

To make it easier to understand, take a look at the following code as an example of mutability with an object.

const mahasiswa = {
    nama: 'iqbal',
    kelas: 304,
};
mahasiswa.fakultas = 'informatika';
console.log(mahasiswa); // output -> { nama: 'iqbal', kelas: 304, fakultas: 'informatika' }

And this is mutability with an array.

const mahasiswa = ['iqbal', 'niyaz'];
mahasiswa.push('dwi');
console.log(mahasiswa); // output > [ 'iqbal', 'niyaz', 'dwi' ]

Const does not provide immutability (unchangeability) for object data types; rather, it ensures that the reference itself is not changed, as long as there are allowed methods to modify the object.

Link Mangcoding

Which One Should I Choose: var, let, or const?

I tend to use const when declaring a variable. My reason is that const is a very straightforward construct for declaring variables, meaning I assign a variable only once for a specific function.

However, in certain cases, I also use let. As for var, you should avoid or no longer use it.

That’s the explanation of Getting to Know JavaScript Variables: Var, Let, and Const that Mangcoding can share. Hopefully, this article is useful and provides new insights for you. If you have constructive feedback or suggestions, feel free to leave a comment or contact us via email and Mangcoding’s social media.

Source : Muhammadiqbal

Link Copied to Clipboard