+ 1
What's the difference between using let and var for declaring variables. Could someone please help me. Thanks in advance
I see it everywhere in the comment section and people preferring let to var but I don't see in being talked about anywhere in the entire course
4 Respuestas
+ 3
var: uses function scope.
let: uses block scope.
Example:
// Into a function
function scope(){
// This is function scope
//----------------------------------------
var a = 2; // you can access throughout the function
if (a > 0) {
// This if scope
// --------------------------
let b = 7; // you can access just into this if block
var c = 9; // you can access throughout the function
console.log(a);. // 2
console.log(b);. // 7
console.log(c);. // 9
// ----------------------------
}
console.log(a);. // 2
console.log(c); // 9
console.log(b); // this print out an error because b is not in this scope
// -------------------------------------------
}
experiment with the following code:
https://code.sololearn.com/cBBaDFYqdvEb/?ref=app
'let' feature was been added in ECMAScript 6.
I hope this help to understand a little bit more about the usage of let.
+ 1
The let keyword is new in ES6. The only difference really is the scope of the variable declared. If you use the var keyword to define your variable, the scope of that variable is to the function it is defined in. The let keyword is scoped to the innermost enclosing block denoted by { }
https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var
+ 1
CLAD,
scope of let variable is upto the block where it's defined.
scope of var variable is global, it can be used where it is defined.
I saw some time var declared/define it creates problems let variable can be defined/declared only once in it's scope.
Problems created by var variable happens when two function uses same variable name for different loops.
In JavaScript Application program if variable is not declared/defined it takes default value so it doesn't raise an exception while console.log(). If it is not initialised and used then it raises an exception.
so it passes silently
console.log(b);
DHANANJAY PATEL
0
I think of it as this. It just creates an instance of a global variable without actually changing the global variable value. Like this for example:
var a = 10;
function example() {
let a = 5;
document.write(a);
}
example();
document.write(a);
example();
You will notice that the global varible value remains the same after the function is called.