David G
David G

Reputation: 96810

Why is the variable inside this function global?

I thought any variable defined in a function would be local but I can easily access variable 'e' outside of its function.

function change() {
 var d = 6; 
  e = 7;
}

change();
alert(e); //> alerts 7

Upvotes: 2

Views: 242

Answers (6)

SavoryBytes
SavoryBytes

Reputation: 36236

It is surprisingly easy to create global variables, here are some other gotchas I've seen.

// :-( antipattern: implied global variable
function sum(x, y) {
    result = x + y; // result is global
    return result;
}

// :-) better
function sum(x, y) {
    var result = x + y; // result is local
    return result;
}

// :-( antipattern: chain assignments as part of a var declaration
function foo() {
    var a = b = 0; // b is global
}

// :-) better
function foo() {
    var a, b;
    a = b = 0; // both local
}

Upvotes: 1

epascarello
epascarello

Reputation: 207511

I am guessing that you are going under this assumption that

JSLint expects that a var will be declared only once, and that it will be declared before it is used.

Problem with your code is you are using one var, but your second line has no var in front of it. That is pushing that varaible e into the global namespace.

Why is it happening? You used a semicolon instead of a comma in the variable declaration.

function change() {
 var d = 6, //Change this to a comma 
     e = 7;
}

change();
alert(e); //will produce an error now

Upvotes: 1

eveevans
eveevans

Reputation: 4460

Thats because e is global by default, using var make a scope varible. You can read more about this in Javascript Garden Scope and Namespaces

Upvotes: 1

Matthew Abbott
Matthew Abbott

Reputation: 61589

You've not explicitly declared it as such, so it has taken global scope.

Upvotes: 1

Shadow Wizard
Shadow Wizard

Reputation: 66388

Because it was declared without var it becomes part of the global window object.

Upvotes: 2

kqnr
kqnr

Reputation: 3596

Because new variables will enter the global scope by default. var prevents this from happening by constraining a variable's existence to be within the current scope.

Upvotes: 10

Related Questions