The available choices for the number of global variables are these:
There are two: input and controlVal.
There are three: input, controlVal, and multiplier.
There are four: input,controlVal, val, and multiplier.
There are three: input,controlVal, and val.
My take is that there are two global variables: input and controlVal, but the correct answer is listed as three global variables: input, controlVal, and multiplier.
Is my understanding that:
const multiplier = (number, phase) =>
indicates an arrow function correct? If so, are arrow functions classified as global variables?
I agree the question is a bit misleading, and I’m pretty sure I answered it the same way you did back when I took the quiz. However, the ‘correct’ answer is correct. Functions including arrow functions are objects in JavaScript. In the quiz question, multiplier is a named constant (variable) with an object (the arrow function) assigned to it. It is not inside a block, so it has global scope. Hopefully that made sense.
It does make sense to me that a named constant could have the arrow function as its object. (If I put that correctly.)
My follow up question is if the multiplier function were written differently, as in:
function multiplier(number, phase) {
const val = number * controlVal + phase;
console.log(val);
}
Would multiplier be considered a global variable in this case as well? It seems that it wouldn’t, since it’s not being assigned using the const keyword.
Hmm. That is an excellent question. Not sure I can provide an excellent answer. My natural inclination would be to say that it’s not a global variable, but that it’s a function with global scope. However, multiplier is still a name with a function object assigned to it, so it could still be considered a variable in a sense. I don’t know that it really matters other than for a quiz question. I’m going to tag @mtf to see if we can get a more definitive answer.
> function foo() {}
<- undefined
> foo.toString()
<- "function foo() {}"
> foo = 'foo'
<- "foo"
> foo()
x > Uncaught TypeError: foo is not a function
at <anonymous>:1:1
A function may be declared in any scope. The above shows that functions can be obliterated and their name given a new assignment. That puts them on par with variables.
Once we create an identifier we cannot redeclare it. It’s been hoisted. We can redefine it (give another assignment), but let and const will throw an error.
> const foo = function () {}
x > Uncaught SyntaxError: Identifier 'foo' has already been declared
at <anonymous>:1:1
>
Given the above evidence of how easily a function can be nixed, the const form of function expression seems a no-brainer solution when we consider…
> const faz = function () {}
<- undefined
> faz.toString()
<- "function () {}"
> faz = 'faz'
x > Uncaught TypeError: Assignment to constant variable.
at <anonymous>:1:5