Summary for those who do not want to read the whole explanation:
-
const
define constants, but if we are not careful they can be modified. It has block reach, as let
.
-
var
defines variables with a local scope (the current context)
-
let
defines variables with a local scope and from the line where they are declared, not before.
- If we do not declare an identifier, it will be created as a global variable unless our code is declared "strict"
const identificador= ...
Create constants, but if the constant is an object, its attributes are modifiable, so you have to be careful with what we do:
function falla() {
const k1= 5;
console.log(k1);
k1=6;
console.log(k1);
}
function funciona() {
const k1={};
k1.hola='mundo';
console.log(k1.hola);
}
funciona();
falla();
var identificador ...
Javascript is a little special for what things and this is a good example: the variable can be declared when using it, at the beginning of our code or at the end, it will not really matter because the interpreter will "go up" (in English to this) it is called hoisting and it also affects the declaration of functions) the statement at the beginning of the current scope / context:
function ejemplo() {
// la declaro abajo, pero el compilador pondrá la declaración aquí, manteniendo la asignación abajo
a='hola mundo';
console.log(a);
var a=6;
console.log(a);
if (a===6) {
var b=4;
}
console.log(b); //se declaró en un if, pero su alcance es toda la función
}
ejemplo();
Also, it does not matter if we declare it several times, the extra declarations will be ignored:
var a=4
var a=5;
console.log(a)
There is a problem with the values of a variable related to closures and asynchronous callbacks that usually bind inexperienced programmers, I give an example and how to solve it:
function print(c) {
console.log(c);
}
//generamos una función con un valor fijado de antemano
function generador(c) {
return function () {
print(c);
}
}
for (var i=0;i<5;i++) {
setTimeout(function () { print(i);});
}
for (var i=0;i<5;i++) {
setTimeout(generador(i));
}
let identificador=...
And we come to the latest novelty of Javascript, which behaves in a similar way to what is a variable declaration in other languages such as Java or C: the variable can only be used from its declaration and its scope is local to block, not to function:
function funciona() {
let a='hola';
console.log(a);
}
function falla() {
a='hola';
console.log(a);
let a;
}
function fallariaTambien() {
let a=1;
if (a==1) {
let b=2;
}
console.log(b);
}
funciona();
//se declara una nueva instancia de i para cada iteración!! el problema que teníamos con var desaparece :)
for (let i=0;i<5;i++) {
setTimeout(()=>console.log(i));
}
try {
falla();
} catch(e) {
console.log('Capturado',e.toString());
}
try {
fallariaTambien();
} catch(e) {
console.log('Capturado',e.toString());
}
Unlike var
, duplicates are not allowed:
let a=4;
let a=5;
console.log(a)
And what happens if we use an identifier without declaring it? So we have two scenarios: "normal" Javascript and "strict" Javascript: In the first the variable is created as an attribute of the global object and in the second case there is a compilation error, warning that the variable has not been declared. / p>
function normal() {
hola='hola';
}
function estricta() {
'use strict';
// esto indica al intérprete que funcione en modo estricto: todo ha de estar definido o no funcionará
fallo='esto falla';
}
normal();
console.log(window.hola);
estricta()
This example shows the two scenarios and also helps answer the question "What is global in Javascript?"
If we are running in a browser, the global object is always window
.
If we are executing the code in NodeJS, the global object is global
.
But beware, window
is not the entire browser window, but the current tab. This is because until the arrival of Firefox there were no tabs and every page that we opened in a browser forced us to have a new window open. For security we can not share variables between different tabs.