0

In a book trying to illustrate global/local variable scope it used this example to convey the concept:

test();

if (isset(bar)){ 

    alert('bar must be global!');

}else{

    alert('bar must be local!');

}

function test(){

   var foo = 3;
   bar = 5;

}


function isset(varname){

    return typeof varname != 'undefined';

}

Right now the if returns the alert 'bar must be global.', which makes sense because the variable passed to the isset(), bar, in this case is global. But why doesn't the if statement return the alert('foo must be local'); when you pass lets say when you pass foo in the isset function.

Antonio Pavicevac-Ortiz
  • 7,239
  • 17
  • 68
  • 141
  • 1
    Because there's no declared symbol "foo" when you call `isset()`. If you called `isset(foo)` from *inside* the "test" function, it'd be set. – Pointy Oct 16 '14 at 14:24
  • Because you're only calling `isset()` once with `bar` as a parameter. – Andy Oct 16 '14 at 14:24
  • I know that in theory that makes sense. But shouldn't the `else` fire? – Antonio Pavicevac-Ortiz Oct 16 '14 at 14:26
  • 1
    No. You're asking the question "Is bar defined". The answer is yes so the `else` doesn't get examined. – Andy Oct 16 '14 at 14:27
  • But I am asking lets say instead of bar, you use foo. In theory shouldn't the else return, because their is no global variable. – Antonio Pavicevac-Ortiz Oct 16 '14 at 14:31
  • No. You'll get an error because `foo` is undefined. Check your console when you run the script. It won't even call `isset(foo)` because `foo` doesn't exist. – Andy Oct 16 '14 at 14:38

2 Answers2

2

"bar" was not declared anywhere in your function test(). Javascript then assumes it's a global var.

To make sure your don't make these kind of mistakes, may I suggest you use :

"use strict";

Put that line at the beginning of your file. It will prevent a lot of errors as presented here :

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

It will prevent undeclared vars to act as global vars

Simon Paquet
  • 615
  • 5
  • 11
1

Since you haven't used the var keyword, the variable is defined on global scope and still exists after executing test function. This is explained more thoroughly here.

Community
  • 1
  • 1
Roope Hakulinen
  • 7,326
  • 4
  • 43
  • 66