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"
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 javascript
let a = 'hello'; // globally scoped
var b = 'world'; // globally scoped
console.log(window.a); // undefined
console.log(window.b); // 'world'
var a = 'hello';
var a = 'world'; // No problem, 'hello' is replaced.
let b = 'hello';
let b = 'world'; // SyntaxError: Identifier 'b' has already been declared
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 and var difference
function run() {
var foo = "Foo";
let bar = "Bar";
console.log(foo, bar);
{
let baz = "Bazz";
console.log(baz);
}
console.log(baz); // ReferenceError
}
run();
what to use let vs var js
/* DIFFERENCE BETWEEN LET AND VAR */
//LET EXAMPLE
{
let a = 123;
};
console.log(a); // undefined
//VAR EXAMPLE
{
var a = 123;
};
console.log(a); // 123
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