2

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?

ShaheerL
  • 61
  • 7
  • 1
    Yea, In JavaScript, functions are first-class objects, which means they can be: **a)** stored in a variable, object, or array. **b)** passed as an argument to a function. **c)** returned from a function. More info [here](https://medium.freecodecamp.org/discover-the-power-of-first-class-functions-fd0d7b599b69) – Shidersz Apr 18 '19 at 04:19
  • 2
    Yes, there are 3 global variables. – Sachink Apr 18 '19 at 04:20

1 Answers1

2

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320