0
var functionExpressionA = function(){
  return x+1;
};

var functionExpressionB = function(){
  return y+1;
};

var y=10;
var x=20;

functionExpressionB(); //returns 11
functionExpressionA(); //returns 21

I would like to clarify how hoisting and parsing of this code works in the above example.

My understanding is that the variable names var y and var x are hoisted. However, their assignments 10 and 20 are not hoisted.

If the above is true how is this snippet of Javascript actually parsed by the browser?

With specific interest to the function expressions which contain a variable which at the time of parsing (because of hoisting only the variable name) is undefined

4
  • 1
    Can you add code too Commented Aug 29, 2017 at 12:08
  • A function expression is an anonymous, immediately invoked function. Do you mean function definitions / declarations? Commented Aug 29, 2017 at 12:09
  • This is somewhat vague without a code sample. Please share the relevant part of code related the the 4 points, so that the question can be properly analized. Commented Aug 29, 2017 at 12:11
  • read about function hoisting. Commented Aug 29, 2017 at 12:25

1 Answer 1

3

Functions always get 'dragged to the top'. So your variables will always be loaded later than the func's. Try to load the variables above the functions and it will work. It's called Hoisting.

Sign up to request clarification or add additional context in comments.

2 Comments

@Camille Sébastien Niessen Functions get hoisted and variable names get hoisted. But Does the actual invoking (calling) of the functions have to happen after the variables are assigned their values?
You can always call the functions functionExpressionA and functionExpressionB, however if you call them before you have assigned the variables x and y then your functions will return NaN (undefined + 1 = NaN) unless you've enabled strict mode in which case it will result in an error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.