What is the difference between "let" and "var"? Explain with example.
What is the difference between "let" and "var"?
1005927-Oct-2022
Updated on 18-Apr-2023
Home / DeveloperSection / Forums / What is the difference between "let" and "var"?
What is the difference between "let" and "var"? Explain with example.
Aryan Kumar
18-Apr-2023In JavaScript, let and var are used to declare variables. However, they differ in scope and hoisting behavior.Variables declared by let are only available inside the block where they're defined. Variables declared by var are available throughout the function in which they're declared.
let and var are both used to declare variables in JavaScript, but they differ in scope, hoisting behavior, reassignment, and use in loops. let has block-level scope and cannot be hoisted, while var has function-level scope and is hoisted to the top of its scope.
Ashutosh Patel
16-Nov-2022In the early days of JavaScript, there was only one way of declaring variables and that was using the var keyword. A variable declared with var is defined throughout the program. One of the issues with using the var keyword was redeclaring a variable inside a block will also redeclare the variable outside the block.
With the introduction of ES6 in 2015 two more keywords, let and const came into the picture. var and let are both used for variable declaration in javascript but the difference between them is that var is function scoped and let is block scoped. Variable declared by let cannot be redeclared and must be declared before use whereas variables declared with var keyword are hoisted.
KIRTI SHARMA
03-Nov-2022In programming languages before using the values there must be stored them into a container generally known as a variable.
For accessibility of these variables we must declare them by using keywords and variable names.
In Javascript let and var keywords are used to declare variables.
The Variables defined with let cannot be Redeclared.
Variables defined with let have Block Scope.
For example,
let x = 'John Doe';
let x = 0;
// SyntaxError: 'x' has already been declared
The Variables defined with var can be Redeclared.
Variables defined with var have function Scope.
For example;
var x = 'John Doe';
var x = 0;
Gourav Jangra
28-Oct-2022var have a Global scope. In full script var will same. we can access the value of var anywhere while let have a Block level scope.we can access the value of let within the block.
E.g of let
let city=Gurgaon;
{
let city='Delhi';
console.log(city);
//output will be Delhi
}
console.log(city);
//output will be Gurgaon