Contenido del Curso
Introduction to React
Introduction to React
ES6 Variables
ES6 (ECMAScript 6) is a revision of JavaScript. ES6 introduced some new useful features that have been standardised today especially in the field of web development. React uses ES6 and hence we need to have some relevant knowledge of ES6 that we're going to use.
In JavaScript we can declare variables using the keyword var
.
In ES6 we let
or const
though const
represents a constant.
Both var
and let
can be used for declaring a variable though there is one fundamental difference between them.
If you try declaring a variable with a name that's already taken using the var
keyword, the older variable will be overridden:
var myVariable = "Hello"; var myVariable = "World"; console.log (myVariable);
The above code will output World
which indicates that the older value was overridden. However if we try to do something similar using the let
keyword:
let myVariable = "Hello"; let myVariable = "World"; console.log (myVariable);
It will show an error at the second line because a variable called ‘myVariable’ is already declared.
Another difference between var
and let
is that var
has a function scope while let
has a block scope. Let's look at the example:
for (var i = 0; i < 7; i++) { // do something } console.log (i);
The above code will have the output 7
, which means that the above code is equivalent to:
var i = 0; for (i = 0; i < 7; i++) { // do something } console.log (i);
Let's look at the example with the let
:
for (let i = 0; i < 7; i++) { // do something } console.log (i);
If we run the above code it will show an error in the last line since the i
variable is not declared in the scope where it's being referenced at.
¡Gracias por tus comentarios!