Anıl Pak
Anıl Pak's Blog

Anıl Pak's Blog

Let, const, or var!

Which one and when to use?

Anıl Pak's photo
Anıl Pak
·Sep 11, 2021·

4 min read

Let, const, or var!

Dynamically-typed vs Statically-typed

You can declare variables in various different ways in JavaScript. Before we start digging more we should know a couple of keywords to understand it better.

In programming, there are two different ways to declare variables; dynamically and statically. Java and C# are good examples for statically-typed languages and they expect their variables to be declared before being assigned any values. Dynamically-typed languages perform type checking at runtime but statically typed languages perform it at compile time. For example in C#;

using System;            
public class Program
{
    public static void Main()
    {
        string name = "Anil";
        int age = 30;
        Console.WriteLine($"Hello my name is {name} and I am {age} years old.");
    }
}
// Output -> Hello my name is Anil and I am 30 years old.

In the dynamically-typed languages, you do not have to declare like this. JavaScript is one of the most common dynamically-typed languages. If you want to declare variables in JavaScript there are a few different ways. You can use let, const, or var. But which one and when to use?

Const means that the variable can't be reassigned. If you do not need to reassign, use the keyword as a default choice.

const licenseID = "123456789";
console.log(licenseID);
// Output -> 123456789

If you try to reassign a new value to licenseID, you will get a syntax error like a

const licenseID = "123456789";
licenseID = "10101010101"
console.log(licenseID);
Output => Uncaught TypeError: Assignment to constant variable.

I use let when I need to reassign a variable. For example, you want to declare variables for the best food.

let bestFood = "kebab";
console.log(bestFood); //kebab
bestFood = "baklava";
console.log(bestFood); //baklava 
bestFood = "dolmades";
console.log(bestFood); //dolmades 
bestFood = "calamary";
console.log(bestFood); //calamary

Before we start talking about scope, I also want to highlight one more important feature about const and let. Let's say you want to declare a variable without initializing.

const cardID;
console.log(cardID);
Output => Const declarations require an initialization value (1:12)

Const needs to be initialized! Let's try it with the let keyword.

let cardID;
console.log(cardID);
Output => undefined

You can declare variables with let without initialization.

Scope

The best way to explain what is the scope and how it works is by doing some experiments and it will explain itself.

if (true) {
  const age = 30;
}
console.log(age)
Output => ReferenceError: age is not defined
if (true) {
  let age = 30;
}
console.log(age)
Output => ReferenceError: age is not defined
if (true) {
  var age = 30;
}
console.log(age)
Output => 30

As you see in the example above, The If statement creates scope for the age variable. It means let and const are block scope but var is not block scoped.

Now let's try it with the function, to understand the function scope better.

function eat() {
  const breakfast = "simit";
  let lunch = "dolmades";
  var dinner = "kebab";
  console.log(breakfast); //simit
  console.log(lunch); //dolmades
  console.log(dinner); //kebab
}
eat();

eat() function creates a function scope. The variable breakfast, lunch, dinner are accessible inside of the function scope, but what about the outside of the function? Let's try it again.

function eat() {
  const breakfast = "simit";
}
eat();
console.log(breakfast); 
Output => ReferenceError: breakfast is not defined
function eat() {
   let lunch = "dolmades";
}
eat();
console.log(lunch); 
Output => ReferenceError: lunch is not defined
function eat() {
  var dinner = "kebab";
}
eat();
console.log(dinner); 
Output => ReferenceError: dinner is not defined

The variables outside of the function are inaccessible no matter what keywords you use.

The benefit of scope is, scope isolates the variables and you can use the variables with the same name again and again. Variables names such as; count, index, name, etc are very common to use and scope helps us to reuse them again.

Module Scope

Let's say your application is getting larger and you want to separate your JavaScript code into different pages/modules. You have modules called accordion.js and flatpickr.js

If you want to use the variable you declared in the accordion.js into flatpickr.js, first you have to export accordion modules and import them in flatpickr.js

Conclusion

"const" shows that the variable will not be reassigned. "let" shows that that variable may be reassigned and also will be used in the block it's defined in. "var" is not very clear like "let" or "const". Variable may or may not be reassigned.

The scope is a rule that manages the accessibility of variables. A variable defined in the scope is accessible only in that scope, but inaccessible from outside.

Scopes are created by code blocks, functions, modules in JavaScript.

Const and let variables are scoped by code blocks, functions, or modules, var variables are scoped only by functions or modules.

Hopefully, my post has helped you understand it better!

 
Share this