Learn the basics of variables in JavaScript with this beginner-friendly guide. Learn the differences between var, let, and const in JavaScript and when to use each one.
A variable is a named storage location in a computer's memory where data values can be stored and retrieved. In programming, variables are used to store values that can change during the execution of a program. Variables are declared using a specific syntax in each programming language and are given a unique name that is used to refer to the value stored in the memory location.
There are Three Types of Variable in JavaScript
var
let
const
var varVariable = value;
let letVariable = value;
const constVariable = value;
Var
in JavaScriptVariables declared with var have function scope, meaning that they are accessible within the function where they are declared and also within any nested functions. If a var variable is declared outside of a function, it has a global scope and is accessible throughout the entire program. var variables can be re-assigned to a new value, and they are also hoisted, meaning that they are moved to the top of their scope and can be accessed before they are declared.
var x = 2;
console.log(x);
// output: 2
function Print() {
var x = 1;
function InnerPrint() {
var y = 2;
console.log(x); // 1
console.log(y); // 2
}
InnerPrint();
console.log(x); // 1
console.log(y); // ReferenceError: y is not defined // as it is called outside the scope
}
Print();
Let
in JavaScriptVariables declared with let have block scope, meaning that they are accessible within the block where they are declared, as well as within any nested blocks. let variables can be re-assigned to a new value, but they are not hoisted.
let x = 1;
if (x === 1) {
let x = 2;
console.log(x);
// output: 2
}
console.log(x);
// output: 1
Const
in JavaScriptVariables declared with const have block scope and cannot be re-assigned to a new value after they have been declared. const variables are also not hoisted.
const PI = 3.14;
PI = 3.15; // TypeError: Assignment to constant variable.
Note. It's good practice to use const for values that you don't want to change and let for values that will change during the execution of your program.
In this blog, here we tried to understand the types of Variables in JavaScript.
#javascript