Let and Const in ES2015 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Let and Const in ES2015

Hey! Can anyone explain me what's the difference between var and let and where use const? :)

6th Jul 2017, 8:13 PM
Czarek
Czarek - avatar
4 Answers
+ 10
In a nutshell without weird words or exceptions. "let" has a local scope, you can use it when you want to make a variable usable for the local scope only. Example: for (let i in array) { } ... variable "i" will be available inside the for loop only. let is not supported in all browser yet. var is global and generally you can access to a variable declared with this keyword everywhere (i want to emphasize "generally") const is a constant and his value cannot be changed in runtime, just this. Use it when you want to make variables without change their value, for example: const screen_width = innerWidth;
6th Jul 2017, 8:35 PM
Maz
Maz - avatar
+ 10
I recommend to deepen a bit following these articles: http://ccoenraets.github.io/es6-tutorial/
6th Jul 2017, 8:42 PM
Maz
Maz - avatar
+ 4
'var' has a function scope , no matter where it is declared within a function it can be used anywhere inside it In 'var' Using first and declaring later will take it's value as 'undefined' (no error) In 'let' Using first and declaring later will cause error - "unknown variable" So using this is technically wrong - function doSomething(){ for(var i = 0; i<10 ; i++){ } for(var i = 0; i<10 ; i++){ } } Instead 'let' should be used which has kind of a bracket scope as @Maz said The variables we use in high-level-languages like Java,C++, etc have bracket scope like 'let' (I always thought var has it too before finding out about let ) https://www.youtube.com/watch?v=q8SHaDQdul0 🎥 16.1: let vs var - Topics of JavaScript/ES6 - YouTube Hope this clarifies var ⛹
30th Sep 2017, 5:18 AM
Utkαrsh
Utkαrsh - avatar
0
Thanks. Now it's clear for me :)
6th Jul 2017, 8:40 PM
Czarek
Czarek - avatar