-1

Is it correct to assume that omitting var from a local variable will
ALWAYS override a global of the same name, if it's also missing var?
Also, is there any merit to using var with creative license.

So there's a frame of reference, here is what I discovered
from riddles I created for a previous post.

In Riddle #3,

  • omitting the var from a = 5 overrides its global counterpart
  • b remains polarized between local and global
  • the alert() at the bottom returns 5*5+4+15
  • 4 is the local b. 15 is the global b, declared on line 25

In Riddle #2,

  • omitting the var from b = 4 overrides its global counterpart
  • a remains polarized between local and global
  • the alert() at the bottom returns 5*3+4+4 -
  • 5 is the local a. 3 is the global a, declared on line 11

In Riddle #1,

  • omitting the var from both local variables overrides ALL global counterparts
  • There is no distinction between local and global variables.
  • the alert() at the bottom returns 5*5+4+4
  • Only variables declared inside the function are recognized
Community
  • 1
  • 1
Wilhelm
  • 1,407
  • 5
  • 16
  • 32

2 Answers2

0

Local variables, and formal function parameters, will always override globals (or other variables declared in higher scopes). However those local variables don't actually exist other than for the duration of the function call.

To see this, replace any global variable a or b with its upper-case equivalent (leaving any local re-declarations or use thereof in lower-case) and you'll find that your code works identically.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • Thanks, I figured as much. I was more interested in 'why' but I realized the answer as I was responding to @jovan. Thanks again. – Wilhelm Jan 26 '14 at 10:12
-2

No. local Scope doesn't override the global scope until AFTER the function is called.

For Example:

a = 3;
b = 2;

function line(x) {
    a = 5;
    b = 4;

    return a*x + b;
}

// returns 19 by referencing "global a = 3"
alert(line(a));

b = line(a) - b;

// returns 25 by referencing "local a = 5"
alert(b);

Omitting var disregards global variables (of identical name) once the function line(x) is called.

Wilhelm
  • 1,407
  • 5
  • 16
  • 32