Skip to main content

Command Palette

Search for a command to run...

let, const & var

Updated
10 min read
let, const & var

Hello readers,

This is the first blog of my Js series. You guys have loved my previous web-dev fundamentals and networking series. If you have not read that yet, then here is the link:

  1. Web dev fundamentals

  2. Networking blogs

  3. Git series

In this blog, I'm going to cover a very basic but important topic in JS: variables.

Variables are easy to define and declare, but some nuances can confuse you in front of an interviewer or cause real-life bugs. Read the full blog; you will definitely learn something new. Trust that this blog is much more than just the definition of let, const, and var. Along with variables, I will also provide an overview of data types in JS.

Let's start the blog

What is a variable?

To understand a variable, think of it like a box with a label, so

  1. label is your variable name

  2. Items inside the box are your content (DataType)

So a variable is a named container for storing data values. These values can be used and modified later in the program, which is why the term "variable" is used (the value can vary).

Why are variables needed?

To understand the need for variables, imagine a room filled with containers without labels (variable names). Isn't it too hard to pick a particular container? That's why we use variables to identify our values stored in memory.

Naming rule of a variable

Here are some key points you should keep in mind while creating a variable:

1. It can contain only characters, numbers, $, and _

2. It cannot start with a number.

3. You cannot use keywords as variable names, for example: class, number, new, etc.

Now you are ready to declare your variable and store values.

Ways to declare a variable

JavaScript is a dynamically typed language, meaning it automatically detects the type of value stored in a variable, so there's no need to define any data type before the variable name. However, we use var, let, and const to declare variables.

var

  • Var is the oldest way to declare a variable in Js. You can still use it; it is perfectly valid, but not recommended. Later in this blog, you will learn why.

  • Var is function-scoped, meaning only functions can create a boundary around var; otherwise, wherever you declare a variable using var, it will be accessed globally. (Problem)

  • You can redeclare a variable declared using var with the same name. (Problem)

  • You can access it even before declaring it because it is directly bound with Global (in the case of a browser, Global is Window) during hoisting. The value is set to undefined, so you will get undefined if you access the variable before initialization.

  • Assigning a value while declaring is optional. You can assign a value later.

var x = 10;
💡
Hoisting is a memory preparation phase in JavaScript where the references of var, let, const, and functions used in the file are stored in memory as you run the script. Thus, var is marked as undefined.

let

  • Let is introduced in ES6 (2015 JS version) to solve the problems with var. It also prevents memory leaks and accidental re-declaration of variables.

  • Let is block-scoped, so if you define a variable using let, it can be accessed only inside that block.

  • If you have already declared a variable using let, you can't create a new variable with the same name. Re-declaration is not allowed. If you do, you will get a syntax error.

  • While hoisting, variables defined using let are not bound to the global, which is why you can't access these variables before declaration. These variables are also hoisted but stored in a different scope (in the case of a browser, it is the script).

  • If you try to access a variable defined using let before its declaration, you will get a reference error: cannot access before initialization.

  • In let, assigning a value is also optional.

let x = 10
let name;
name = "abhishek" //assigning value after variable declaration 
  1. const

const is also introduced with let, and almost all features are the same as let, but there are some strictness added, which are:

  • You can't change the value after assigning.

  • You must assign the value while declaring the variable.

const x = 10;
const name; // not allowed
💡
Temporal Dead Zone: As I told you, let & const variables are also hoisted but not accessible till you declare them. And this gap is known as the temporal dead zone.

Comparison between var, let & const

Shadowing

When you define a variable in an outer scope and then define another variable with the same name in an inner scope, it is called shadowing. Since both variables exist at different levels of scope, this is perfectly fine. This is also known as legal shadowing.

illegal shadowing

If a variable is defined with let in the outer scope and you try to shadow that variable using var inside a block scope, it will cause a conflict because var has no block-level scope. In the outer scope, you have already defined a variable using let, so now there are two variables with the same name, and one is defined using let, which is not valid syntax. In this type of shadowing, you will get a syntax error.

Scopes

Scope defines where your variable can be accessed. Basically, the boundaries of your variable are its scope. In JS, there are mainly 3 types of scopes, which are:

  1. Global Scoped:
    When you define your variable outside the function or block, then that variable has a global scope, which means it can be accessed anywhere in the file.

  2. Function Scoped:
    Function-scoped means the variable will only be accessible inside the function. If you define a variable inside the function, then that will not be accessed outside the function. Var is function-scoped.

  3. Block Scoped:
    When you define variables inside the curly {...} Braces then those are under the block scope.
    let and const has the block scope, but var has function scope. So even if you define variables using var inside the blocks, they are also accessible outside the block.

Data Types in JS

Till now, I have only talked about the label of the container, which is variable, but inside the container, there should be some content; otherwise, what's the meaning of creating a container?

So the content we keep inside the variable (container) is known as data, and we can keep a variety of data inside it, which is known as the data type.

In JS, Data types are divided into two categories:

  1. Primitive: Those data types that are already defined by the makers are known as primitive data types. There are a total of 7 primitive data types.

  2. Non-Primitive: User-defined data types are known as non-primitive or user-defined data types.

Primitive v/s Non-Primitive

Primitive:

Those data types that are already defined are known as primitive data types. Here are the primitive data types:

Number:

  • A number is used to store the numeric values. It covers all types of numbers like integers, floats, etc. Along with the regular numbers, Infinity, -Infinity, and NaN are also number types.
    Here are some examples of number data types:
let age = 10
let num = Infinity
let larget_neg_num = -Infinity
let nan_value = "not a number"/2

BigInt:

  • Number data type can't store big numbers. The safe range of the number data type is ±(253-1) After this range, the value will not be precise in the number data type. So, that's why we have another data type, which is BigInt, to store large numbers
const bigInt = 1234567890123456789012345678901234567890n;
💡
BigInt is rarely used, but if you are dealing with large numbers, then you must use BigInt for precision.

String:

  • A string is a sequence of characters. It is defined using the single quote, double quote, and back tics. Even if you write numbers inside the quotes, those will be treated as a string.
let name = "Abhishek";
let location = 'jharkhand';
let age = `20`

console.log( `Hello, ${name}!` ); // Embeeding a variable. Only allowed in backticks

// embed an expression
alert( `the result is ${1 + 2}` ); // the result is 3

Boolean:

  • This has only two values: true and false. The Boolean data type is used to store yes or no values. Even if you use comparison operators, you will also get a Boolean value.
let isAgeVerifed = true
let isPassed = false

let isGreater = 3 > 1
console.log(isGreater) //true

null:

null is a special data type of JS, which means the variable is empty. Users intentionally assign null to the variable that till now has had no (null) data. Further, we will see, but now it has empty(null) values.

let age = null

undefined

  • When you don't assign a value to a variable, then that variable's data type is known as undefined.

  • Or simply, if a variable is declared but not assigned, then its value is undefined.

  • Undefined is reserved as a default initial value for unassigned variables.

let age;
console.log(age) //undefined
💡
To get the type of any variable, just write console.log(typeof variable_name), and you will get the type of that variable.

That's it. These are the primitive data types of JS. Numbers and Strings are very important, so i will cover them in detail in another blog. Now let's see a non-primitive data type.

Non-Primitive Data Type:

There is only one data type in Non-Primitive, which is object. It is an umbrella type of all complex data structures, like:

Array:

Array is a collection of data types. You can add anytype of data inside an array. It also has too many methods that help to manage the data inside the array. Arrays have 0-based indexing.

let array = ["abhishek",10, false, null]

Object:

Objects store data in pairs of key-value. The keys can be symbols or string but there are no restrictions in value, thse can be any data type. You can define objects in too many ways; here is one of them:

let obj = {
    name: "Abhishek",
    age: 22,
    location: {state: "JH", pincode: "834006"}
}

Functions

Functions are the reusable blocks of code that are also considered as Object and can have properties and methods.

function add(num1, num2){
    return num1+num2;
}

Dates, Regular Expressions, and other built-in types are also objects in JS.

That's it for this blog, guys. I will write separate blogs for numbers, strings, and non-primitive data types (Objects, Arrays, Functions, Dates). Do check out this series.

I hope you guys loved my writing and learned something new from this blog. See you in another blog with an in-depth discussion.