0

I cannot understand the idea behind automatically global. I am reading the following: https://www.w3schools.com/js/js_scope.asp

https://www.w3schools.com/js/tryit.asp?filename=tryjs_local_global

The function myFunction() is called. if I remove this call it displays nothing. I can't understand why the call to myFunction() is necessary for the undeclared variable in myFunction() to be automatically global. Seems not so intuitive.

blue_ego
  • 1
  • 1
  • 4
  • 12
  • Possible duplicate of [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Abana Clara Nov 16 '18 at 02:39

3 Answers3

2

expression

var varName = 'value';

declares variable with var varName and then assign a value 'value' to it with = 'value'

expression

varName = 'value';

just making the assignment a value 'value' to a variable 'varName' which should be declared previously

so

function a() {
   var varName = 'a'
}

declare the variable varName locally and initiate it with 'a' but

function b() {
   varName = 'b'
}

just assigns the variable varName with the value 'b'. but the variable varName is to be declare in the paren global scope.

hypp erster
  • 139
  • 7
1

All it means is in this code:

function myFunction() {
    carName = "Volvo";
}

carName exists outside myFunction after its execution, and is usable by other code. Whereas:

function myFunction() {
    var carName = "Volvo";
}

carName only exists within myFunction, even after it's called. Code outside myFunction can't see it.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
0

When you 'declare' a variable with no explicit declaration keyword (var/let/const), then there is some ambiguity as to whether your intention was to reference an existing variable that may or may not be in a higher scope or to declare a new variable. Much of JavaScript's early defining behavior was to try to have fallback behavior for flexibility. When a variable is assigned to but there is no existing reference, it falls back to creating a variable. And without any declaration keyword there is no way to infer where your intended scope is, so it creates it in a global scope so that other possible references might find it.

In your case, when you call the function it references some variable. JavaScript doesn't know if this was meant to already exist or not, so it creates it in the global scope. As a result, it is still within scope and referenceable after the method is called.

msg45f
  • 695
  • 11
  • 21