var vs let js
let: //only available inside the scope it's declared, like in "for" loop,
var: //accessed outside the loop "for"
var vs let js
let: //only available inside the scope it's declared, like in "for" loop,
var: //accessed outside the loop "for"
const let var scope
var num = 1; //var can be function or global scoped
const num = 2; //const can only be block scoped
let num = 3; //let can only be block scoped
difference between var and let
var is function scoped and let is block scoped. Let's say you have:
function understanding_var() {
if (1 == 1) {
var x = 5;
console.log('the value of x inside the if statement is ' + x);
}
console.log(x);
}
//output: the value of x inside the if statement is 5
5
function understanding_let() {
if (1 == 1) {
let x = 5;
console.log('the value of x inside the if statement is ' + x);
}
console.log(x);
}
//output: the value of x inside the if statement is 5
Uncaught ReferenceError: x is not defined
var is defined throughout the entire function, even if it's inside the if
statement, but the scope of let is always within the curly braces, not outside
it, even if the conditional statement is inside the function.
difference between "let" and "var"?
In simple words 'var' is function scoped and 'let' is block scoped
let in javascript
The let statement declares a block scope local variable, optionally initializing it to a value.
let x = 1;
if (x === 1) {
let x = 2;
console.log(x);
// expected output: 2
}
console.log(x);
// expected output: 1
let vs var
// var is function-scoped, so redeclaring it in a block will cause its value outside the block to change as well:
var one = 'one: declared outside the block';
if (true === true) {
var one = 'one: declared inside the block'; // notice: we redeclare 'one' here
console.log(one); // prints 'one: declared inside the block'
}
console.log(one); // also prints 'one: declared inside the block', because the variable was redeclared in the 'if' block. The outer 'var' variable was therefore destroyed and replaced by inner var variable.
// 'let' is block-scoped, so redeclaring a 'let' variable inside of a block creates a different 'let' variable with the same name whose scope is inside the block:
let two = 'two: declared outside the block';
if (true === true) {
let two = 'two: declared inside the block';
console.log(two); // prints 'two: declared inside the block'
}
console.log(two); // prints 'two: declared outside the block', because two declared inside the block is a separate variable. The 'let' variables are unrelated and therefore are unaffected by each other.
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us