<\/script>')

Function (a) {var a = 'test'; }: Is "var" required? What if a undefined?

Pretty javascript 101 question, but here:

function test(a){
    var a='test';
}

Does var require the variable not to change globally?

function test(a){
    a='test';
}

is that enough?

How about if a function is called using undefined?

function test(a){
    a='test';
}
test();

Will the above snippet be global?

+4
source share
4 answers

Each parameter is implicitly a var.

(The given value of the argument does not matter.)

+3
source

"use strict", , var, a , window.a. " " .

, , , . 'a'

, "use strict", var , "use strict" , . / ,

Edit:

, let , . var, let

!

+1

. , .

, , , undefined, .

function test(a){
    var a = 'test';
}

"var", ?

var , a, .

function test(a){
    a = 'test';
}

?

, , . a, .

, undefined?

function test(a){
    a = 'test';
}
test();

, , a - , undefined, var , a , .

+1

Well, there are a few points for comment:

First of all, inside a function, variables must have varif they are not a reference to an external var:

var outside_var = "OUT!";
var myFunction = function() {
    var inner_var = "IN";
    console.log(outside_var); //Will prompt "OUT!"
    console.log(inner_var);   //Will prompt "IN"
}
console.log(outside_var); //Will prompt "OUT!"
console.log(inner_var);   //Will prompt undefined

Another thing is that every var defined as an argument is already defined in the function scope, you do not need to declare it with var:

var outside_var = "OUT!";
var myFunction = function(a) {   //imagine you call myFunction("I'M");
    var inner_var = a + " IN";
    console.log(outside_var); //Will prompt "OUT!"
    console.log(a);           //Will prompt "I'M"
    console.log(inner_var);   //Will prompt "I'M IN"
}
console.log(outside_var); //Will prompt "OUT!"
console.log(a);           //Will prompt undefined
console.log(inner_var);   //Will prompt undefined
0
source

Source: https://habr.com/ru/post/1536571/


All Articles