OnTheFence
OnTheFence

Reputation: 109

Creating global variables inside function - why does this work?

As far as I know variables declared inside a function are local variables (using var keyword or not). If so then why does this output 5? Shouldn't I get a ReferenceError when calling func2 because x is only known to func1?

<script>
    function func1(){
       x = 5;
    }

    function func2(){
       document.write(x);
    }

    func1();
    func2();
</script>

Upvotes: 2

Views: 7891

Answers (4)

Shikari
Shikari

Reputation: 85

"use strict";

function func1() {
  window.x = 5;
}

function func2() {
  document.write(x);
}

func1();
func2();

Upvotes: 0

JLRishe
JLRishe

Reputation: 101662

Afaik, variables declared inside a function are local variables (using var keyword or not).

Variables declared inside a function are local, but you are not declaring any variables. What you have is what's known as an "implicit global" and it only works in "sloppy mode".

From MDN:

Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed.

In strict mode, your code produces an error:

"use strict";

function func1() {
  x = 5;
}

function func2() {
  document.write(x);
}

func1();
func2();

Upvotes: 2

Sushanth --
Sushanth --

Reputation: 55740

function func1(){
   x = 5;
}

is equivalent to

var x; // In global scope
function func1(){
   x = 5;
}

As the variable was not scoped to func1 with a declaration.

If this was the case, then you would come across an error in the console since you are trying to access a variable that is not defined yet.

function func1(){
   var x = 5;
}

Upvotes: 1

Kody
Kody

Reputation: 1378

It is because you did not define it as

function func1(){
   var x = 5;
}

This means that JS will use the global variable x which does not exist, but will when you run func1.

The addition of the "var" defines the variable within the local scope of func1.

Upvotes: 2

Related Questions