var, let, const ... or nothing in Javascript

17

The following question: When it is convenient to use var, let and const in ECMA Script 6? responds in part to my question, but not entirely.

Reading the accepted answer, I understood that:

  • let declares a local scope variable

  • const declares a constant within a block (inside a function?)

  • var I did not understand if it's local or global

  • And if you do not put nada , what is the scope? In another related question I read that when you do not put anything, you are declaring a global variable.

I am somewhat confused and would like to understand the exact scope of each form of variable declaration, in a simple answer if possible.

On the other hand, I do not know if this would be a topic for another question, but, I do not understand what the concept of global in Javascript would be. The current DOM tab ?, all the tabs open ?, all the browsers and tabs open?

    
asked by A. Cedano 29.09.2017 в 16:56
source

2 answers

28

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.

    
answered by 29.09.2017 / 17:54
source
9

var declares a local variable, that is, if you declare

function miVar() {
  var x = 0;
}

x will only have scope within the miVar function, if you declare at the beginning of all the js var x = 0; out of any function this will have scope in all the js.

If you do not put var declares a global variable, now what is the difference between declaring a global variable and a local variable but in all the js? That if you put var x = 0; at the beginning of the js this will only have scope in the current js, if you declare it global it will have scope in all the js that are declared in the html. That is to say if in a js I declare x = 0; I can use in another js the variable x and it will have the value of 0

Const could be like a global variable like x = 0 , but the big difference is that being constant can not be redeclared, that is if you put const x = 0; you can not later on in a function put x = 2.

As this page explains about it in const, it can be changed in cases of array, that is, by filling or removing elements link

Let is used to declare variables a little more local, as this answer explains link

practically var takes the parent block so to speak, if you use a let in a for inside a function

function varExp(){
  for( let i = 0; i < 5; i++ ) {

    }
}

let will only be available within the for, if you do it with a var, it will be in the whole function

    
answered by 29.09.2017 в 17:25