-7

Question: What will be the value of bar after it is hoisted?

var bar = function() {
return 3;
};

I think: the function expression. I'm wrong?

  • 1
    I'm not quite sure what you expect as an answer... every variable has the value `undefined` initially, until the line of the assignment is executed. And in this case, `bar` is assigned a function. What do you think *hoisting* is? – Felix Kling Apr 05 '13 at 17:42

3 Answers3

4

Why not just try it?

var bar = function() {
    return 3;
 };

console.log(bar);

Output,

  function () {
    return 3;
  }
PherricOxide
  • 15,493
  • 3
  • 28
  • 41
  • Thank you, but: what's in this case the difference between hoisted or not? How can I simulate hoisting? – Jeroen Bokier Apr 05 '13 at 19:51
  • I think maybe you only provided part of the relevant code. Hoisting isn't really relevant here, I'm guessing your example called bar somewhere further up? – PherricOxide Apr 05 '13 at 20:01
  • console.log(bar); // undefined var bar = function() { return 3; }; – Jeroen Bokier Apr 05 '13 at 20:17
  • I don't understand what you're asking. Hoisting will make "bar" defined higher in the code than where the var bar assignment actually is; see http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html for a good tutorial on the subject. – PherricOxide Apr 05 '13 at 20:22
0

Indeed the function. So yeah, you're right.

fcm
  • 6,305
  • 5
  • 24
  • 37
0

If you try to use an undefined variable then that will of course throw a reference error. If you try to assign to an undefined variable then it will create a global variable (in a web page, roughly equivalent to writing window.foo = bar;). However the variable will still be undefined until it is created.

If however you declare a local variable using const or var, then it will be defined from the beginning of the function as having the value undefined, so accessing the variable "early" will not throw a reference error, and setting it will set the local value. You do not have to declare the variable at the start of the function; the declaration will be hoisted to the scope of the function.

By comparison, in ES6, if you declare a variable using let, then it will only be hoisted to the beginning of the block.

Also, if you declare a "variable" using function, then its value will be hoisted too, so you can call a function before its declaration. (The function has to be in the same script though.)

Neil
  • 54,642
  • 8
  • 60
  • 72