At what time use "VAR" in javascript and why is it necessary? [duplicate]

1

I have a doubt, I have always coded in js but I always did not use the var to put in the declaration of a variable but I saw that some say that var should be put inside a function, others say that it is put when it is out.

Thanks for your contributions.

    
asked by Shiroyasha 04.04.2017 в 17:25
source

4 answers

2

Depends on the javascript version.

If you use JS5 (the standard in browsers) var is the keyword used to declare a variable. Ex:

var miVariable, otraVariableInicializada=1, 
    otraVariableUndefined;

Now if you use Javascript 6 (ECMAScript 2015) or higher (NodeJS), the keyword var has fewer uses.

In general, use the const (for constants and functions) or let (for variables) unless you need to create a closure , in which case var should be used.

const modulo = require('modulo');

const miFunc = () => {
    var enClousure = 1234;

    return () => {
       let valorLocal = modulo.getAlgo();
       return enClousure + valorLocal;
    }; 

};
    
answered by 04.04.2017 в 17:43
1

Here is an example that my professor gave me in his day to see if you understand.

function f1(a,b){
    var c=c+a; // La variable c es LOCAL
    d=d+b; // La variable d es GLOBAL
    document.write("En f1()<br/>");
    document.write("c="+c+"<br/>");
    document.write("d="+d+"<br/>");
}

function f2(){
    document.write("En f2()<br/>");
    document.write("c="+c+"<br/>");
    document.write("d="+d+"<br/>");    
}


// ---------------------------------------

var c = 10; // Variable GLOBAL. Es un script
d = 20; // Variable GLOBAL

f1(1,2);
f2();
    
answered by 04.04.2017 в 17:56
0

When you declare a variable without putting the var in front, you are declaring that variable globally to the entire document *.js instead if you put var variable you are declaring local to the method that you are going to use.

    
answered by 04.04.2017 в 17:38
0

If you put var you can use it inside but not outside where it was declared; Example as a variable name behaves depending on where it was declared; even the declared without "var" inside the function remains global to the page.

    
answered by 04.04.2017 в 17:55