ES6 const and let
This lesson explains the difference between var and const and let declarations.
We'll cover the following
Notice that we declared the variable helloWorld
with a var
statement. JavaScript ES6 comes with two more ways to declare variables: const
and let
. In JavaScript ES6, you will rarely find var
anymore.
const
A variable declared with const
cannot be re-assigned or re-declared, and cannot be changed or modified. Once the variable is assigned, you cannot change it:
// not allowedconst helloWorld = 'Welcome to the Road to learn React';helloWorld = 'Bye Bye React';
let
Conversely, a variable declared with let
can be modified:
// allowedlet helloWorld = 'Welcome to the Road to learn React';helloWorld = 'Bye Bye React';
TIP: Declare variables with let
if you think you’ll want to re-assign it later on.
Note that a variable declared directly with const
cannot be modified. However, when the variable is an array or object, the values it holds can get updated through indirect means:
// allowedconst helloWorld = {text: 'Welcome to the Road to learn React'};helloWorld.text = 'Bye Bye React';
There are varying opinions about when to use const and when to use let. I would recommend using const
whenever possible to show the intent of keeping your data structures immutable, so you only have to worry about the values contained in objects and arrays. Immutability is embraced in the React ecosystem, so const
should be your default choice when you define a variable, though it’s not really about immutability, but about assigning variables only once. It shows the intent of not changing (re-assigning) the variable even though its content can be changed.
import React, { Component } from 'react'; import './App.css'; class App extends Component { render() { const helloWorld = 'Welcome to the Road to learn React'; return ( <div className="App"> <h2>{helloWorld}</h2> </div> ); } } export default App;
In this course, we will use const
and let
over var
for the rest of the course.
The most recommended way of declaring a variable is using:
var
let
const
All of above