Antonio Pavicevac-Ortiz
Antonio Pavicevac-Ortiz

Reputation: 7739

Why doesn't my homemade isset function in javascript completely work?

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.

Upvotes: 0

Views: 48

Answers (2)

Simon Paquet
Simon Paquet

Reputation: 625

"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

Upvotes: 2

Roope Hakulinen
Roope Hakulinen

Reputation: 7405

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.

Upvotes: 1

Related Questions