const vs let vs var
Written byPhuoc Nguyen
Category
JavaScript
Created
18 Jun, 2020
There are three keywords to declare a variable:
`var`
`let`
and`const`
which are only available in ES6
#Differences
-
It's not possible to access the
`let`
variable outside of the nearest enclosing block where it is declared.{let foo;}// ReferenceError: foo is not definedconsole.log(foo);The sample code above works if we replace the`let`
with`var`
declaration. -
A
`let`
variable can't be used before it's declared. The sample code below throws a`ReferenceError`
:{foo = 'hello';let foo;console.log(foo);}// ReferenceError: Cannot access 'foo' before initializationWe will see`hello`
in the Console if we use`var`
in the sample code above. -
It's not possible to re-declare variables with
`let`
.// There is no problems if variables are re-declared with the same namevar foo, foo;var bar;var bar;let baz;let baz;// Throw the following error// SyntaxError: Identifier 'baz' has already been declared -
At the top level, global
`let`
variables aren't attached to the global`window`
object.let foo = 'hello';window.foo; // undefinedvar bar = 'world';window.bar; // 'world' -
Using
`let`
can avoid the problem with closures that`var`
has.To demonstrate the problem, let's assume that we have a list of rows. In each row, we have a button for removing the associate item in the row.We loop over the items, and handle the`click`
event of the button in each row:for (var i = 0; i < 10; i++) {document.getElementById(`button-\${i}`).addEventListener('click', function () {// Remove the itemconsole.log(i);});}It doesn't work as we expect. We always see the last item index (`9`
in this case) in the Console when clicking any button. The variable`i`
in the closure of event handler will refer to the same object, which is the last index when looping over the indexes.The problem can be fixed by using`let`
:for (let i = 0; i < 10; i++) {document.getElementById(`button-\${i}`).addEventListener('click', function () {// It's safe to use the index `i` hereconsole.log(i);});} -
The
`const`
keyword behaves same as`let`
, except the variable can't be changed.// Throw the following error// SyntaxError: Missing initializer in const declarationconst a;You also have to specific a value for a constant.const a = 'hello';// Throw the following error// TypeError: Assignment to constant variablea = 'world';It's worth noting that using`const`
doesn't mean that the variable is immutable. You can change the properties of an object:const person = {};person.age = 20;And add more items to an array:const arr = [];arr.push('foo');arr[1] = 'bar';console.log(arr); // ['foo', 'bar']
#Good practice
Don't use
`var`
unless you have to support old browsers which don't support `let`
and `const`
keywords.#Good to know
Each programming language use different keywords to declare a variable and constant.
The following table list out some examples:
Language | Variable declaration | Constant declaration |
---|---|---|
C# | `string s = "hello"` | `const string s = "hello"` |
Java | `String s = "hello"` | `final String s = "Hello"` |
Scala | `var s = "hello"` | `val s = "hello"` |
Swift | `var s = "hello"` | `let s = "hello"` |
Questions? 🙋
Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.
Recent posts ⚡
Copy the content of an element to your clipboard
01 Oct, 2023
Make a text area fit its content automatically
30 Sep, 2023
Quickly insert alternate characters while typing
30 Sep, 2023
Zebra-like background
30 Sep, 2023
Add autocomplete to your text area
28 Sep, 2023
Linear scale of a number between two ranges
28 Sep, 2023
Highlight the current line in a text area
27 Sep, 2023
Create your own custom cursor in a text area
27 Sep, 2023
Mirror a text area for improving user experience
26 Sep, 2023
Display the line numbers in a text area
24 Sep, 2023
Select a given line in a text area
24 Sep, 2023
Newsletter 🔔
If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn