All about Var,Let,Const ! JavaScript made simple
Javascript uses three keywords to declare variables which are let, const, Var.
Var has been the oldest keyword, before ES6 features were introduced, Var was used to declare variables.
Var
Var declarations have the global scope or Function Scoped, Which means a variable declared using var outside any function scope can be accessed from anywhere in the program.
var a = 10
function f(){
console.log(a)
}
f();
console.log(a);
output:10
variables declared using var is attached with the global window object in javascript.
Function scoped means var declared under a function can be accessed inside a function only.
To understand further, let's understand the code below
var greeter = "hey hi";
function newFunction() {
var greeter = "hello";
console.log(greeter);
}
newFunction();
output: hello
since , the variable is declared using var inside a function, so its' function scoped , it won't be accessible from outside the function. This is also an example of shadowing.
var variables can be re-declared and updated, this means that we can do this within the same scope and won't get an error.
var name = "pranay";
var name = 'trump';
this.name = 'joe biden';
window.name = 'pranay';
console.log(name);
this code will run smoothly without running into any errors.
Note: this. name and window.the name refers to the name property attached to the global window object which is the same as the globally declared name variable .so, output of this code will be -
output: pranay
Let
Let and const are part of ES6 which were introduced later in 2015 , earlier var was the only available option for JavaScript developers .
Let is block scoped . Anything under {} two curly braces is known as a block. Therefore, a variable declared in a block with let can only be used in that block.
if (true) {
let hello = "say Hello";
console.log(hello);// "say Hello instead"
}
console.log(hello) // hello is not defined
let declared variables, are attached under 'script', and don't attach themselves with the window object.
let can be only declared once, and can be updated/assigned.
this will return the error :
let greet = "say Hi";
let greet = "say Hello "; // error: Identifier 'greeting' has already been declared
Const
In JavaScript, the const keyword is used to declare a variable that cannot be re-assigned after its initial value has been set. This means that once a const variable is assigned a value, it cannot be changed or re-assigned to a new value. This makes const variables useful for declaring values that should not be modified, such as constants or configuration settings.
Syntax
The syntax for declaring a const
variable is similar to declaring a let
variable, but instead of using the let
keyword, you use the const
keyword:
Once a const
variable is declared and assigned a value, you cannot re-assign it to a new value. For example:
const PI = 3.14;
PI = 3.14159; // This will throw an error
Advantages of using Const
One of the main benefits of using const
variables is that they provide a clear indication of variables that are not intended to be modified. This can make your code easier to understand and debug, especially in larger codebases.
Another benefit of using const
variables is that they can help prevent accidental re-assignment of variables. If you accidentally try to re-assign a const
variable, the JavaScript engine will throw an error, which can help you catch mistakes early on.
Code Example
Here's an example of how you might use const
variables in a JavaScript program:
const MAX_WIDTH = 800;
const MAX_HEIGHT = 600;
function resizeImage(image, width, height) {
if (width > MAX_WIDTH || height > MAX_HEIGHT) {
throw new Error(`Image dimensions too large. Maximum dimensions are ${MAX_WIDTH} x ${MAX_HEIGHT}`);
}
// Code to resize image...
}
In this example, we declare two const
variables, MAX_WIDTH
and MAX_HEIGHT
, which represents the maximum dimensions for an image. We then use these variables in the resizeImage
function to check if the image dimensions are within the maximum dimensions. If the image dimensions are too large, we throw an error.
Because MAX_WIDTH
and MAX_HEIGHT
is declared as const
variables, we know that their values cannot be changed elsewhere in the program. This makes it clear that these values are intended to be constants.
In conclusion, the const
keyword in JavaScript is a useful tool for declaring variables that cannot be re-assigned after their initial value has been set. By using const
variables, you can make your code more readable, prevent accidental re-assignment of variables, and create constants that are guaranteed to remain constant throughout your program.
Comparing the three .......
In JavaScript, there are three ways to declare variables: var
, let
, and const
.
var
has been around since the early days of JavaScript and has some quirks that can lead to unexpected behavior, such as hoisting and scope issues.
let
and const
were introduced in ES6 and are more modern alternatives to var
. They both have block-level scoping, which means that variables declared with let
or const
are only accessible within the block in which they are defined.
The main difference between let
and const
is that variables declared with let
can be reassigned, whereas variables declared with const
cannot. This makes const
a better choice for values that should not be changed, such as constants or configuration settings.
Here is a comparison of the three keywords:
Keyword | Hoisting | Scope | Can be reassigned | Can be redeclared |
var | Yes | Function | Yes | Yes |
let | No | Block | Yes | No |
const | No | Block | No | No |
In general, it is recommended to use let
and const
over var
due to their more predictable behaviour and better scoping rules.
Subscribe to my newsletter
Read articles from Pranay Dwivedi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Pranay Dwivedi
Pranay Dwivedi
Front end developer