why some programmers crate variable with let instead var | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 2

why some programmers crate variable with let instead var

7th Oct 2016, 7:16 AM
Efsun Idriz
Efsun Idriz - avatar
2 Réponses
+ 6
What will be the output? var num = "nothing"; if (true) { var num = 4; } alert(num); There will be "4", not "nothing". If you will try to do this with function (not "if") you will see "nothing". Why? In javascript a new block will not create a new scope. This can be done by functions only. So variable created in for loop will be available everywhere (in current function). But: let num = "nothing"; if (true) { let num = 4; } alert(num); will write "nothing" because variable created by let is available in current BLOCK only, so our if block will not change our outside variable .
7th Oct 2016, 4:06 PM
Eugeny Orlo
Eugeny Orlo - avatar
+ 3
With let - you can define variables which are accessible only in the scope, where the variable is created. It is more convenient than var and it is the new standard
8th Oct 2016, 10:11 PM
Georgi Tsenov
Georgi Tsenov - avatar