1

In JavaScript, variables created within a function only have scope only within that function: if that's the case, why does the following code produce the output 1? Surely x cannot be accessed from outside of foo ?

function foo(){
  x = 1;
}
foo()
console.log(x) // '1'
msanford
  • 11,803
  • 11
  • 66
  • 93
O James
  • 189
  • 1
  • 12
  • 3
    This code will throw an exception in [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode). You should always use strict mode. – Quentin Dec 20 '17 at 15:58
  • 3
    *variable's created within a function only have scope only within that function* — that is not true in the case of *implicit global* variables like yours. – Pointy Dec 20 '17 at 15:59
  • Simply never ever ever use undeclared variables. – Jonas Wilms Dec 20 '17 at 16:08
  • 1
    `x` is not declared inside `foo`. You are just assigning to an undeclared variable. – Felix Kling Dec 20 '17 at 16:14

2 Answers2

6

Because you have assigned to a variable which is defined without var, let or const. And because your code in not strict mode, it is assigned to the global object's (window) property with name x. You can uncomment the use strict part and will see an exception.

// 'use strict';

function foo() {
   x = 1;
   console.log(window.x);
}

foo();
console.log(window.x);

If you declare with keywords you can not access it outside the function and it will not be in the window object.

function foo() {
   let x = 1;
   console.log(x);
}

foo();
console.log(window.x);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
0

In your code you only initialize the variable in side the function without var, let or const so JavaScript threat it as a globe variable

function foo(){
  x = 1;
}
foo()
console.log(x) // '1'

Following is how it work if you use var, let or const

function foo(){
 var x = 1;
 let y = 1;
 const z = 1;
}
foo()
console.log(x)
//console.log(y)
//console.log(z)
Nisal Edu
  • 7,237
  • 4
  • 28
  • 34