ShaheerL
ShaheerL

Reputation: 61

Is a Variable That is Equal to a Function Considered a Global Variable?

In a question on one of my quizzes, we were asked to determine how many global variables there are in the following block of code:

    var one = 1;
    var two = 2;
    var multiplier = function(number){
    }

I answered saying there are two: one and two. However, my teacher marked it wrong and stated there are 3 global variables. Is a variable that is equal to a function still considered a global variable?

Upvotes: 2

Views: 140

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370699

Functions are first-class in Javascript - they can be assigned to any variable. A variable can hold any value - a number (as with one and two), a string, etc, an object, or a function.

A global variable which happens to point to a function (as with multiplier) is still a global variable.

Note that function declarations on the top level create global variables as well, for example:

function multiplier(number) {
}

// The function declaration created a property on the global object:
console.log(typeof window.multiplier);
// just like:
var one = 1;
console.log(typeof window.one);

Of course, global variables are best avoided when not necessary, and they're rarely necessary.

Upvotes: 2

Related Questions