0

How can a variable declared in if condition is hoisted and not function? Example 1:

var x = 1;
if(a = 1) {
    x += typeof a;
}
x;    // 1number
a;    // 1

When tried same with function in SpiderMonkey and V8 hoisting didn't happen. Why not? What happens to function in if condition? Example 2:

var x = 1;
if ( function f () { return 9; } ) {
    x += typeof f;
}
x;     // 1undefined
f;     // ReferenceError: f is not defined

However when function is defined inside if on success function is hoisted Example 3:

var x = 1;
if ( true ) {
    x += typeof f;
    function f() { return 1; }
}
x;    // 1function
f;    // f()
typeof f;   // function

Even if condition is false function is hoisted Example 4:

var x = 1;
if ( false ) {
    x += typeof f;
    function f() { return 1; }
}
x;    // 1
f;    // undefined      not ReferenceError: f is not defined
// f still got hoisted

What's happing at example 2? Why function is not hoisted when variable did in example 1?

NAVIN
  • 3,193
  • 4
  • 19
  • 32
  • 2
    Function expressions are not hoisted. – Quentin Sep 03 '18 at 10:25
  • (I fell into the expression `if ( function f () { return 9; } )` trap....) haha – Royi Namir Sep 03 '18 at 10:29
  • @RoyiNamir — Being on the right hand side of an assignment is not the only thing that puts the JS parser into expression mode. Being between `(` and `)` does too. – Quentin Sep 03 '18 at 10:29
  • Yes ..... ^.....I've missed that :) – Royi Namir Sep 03 '18 at 10:29
  • @Quentin how that refers to my problem. I know when we assign a function to some variable it doesn't get hoisted. I'm not assigning any value. My function `f` is a `function declaration` and none of then are `function expressions` – NAVIN Sep 03 '18 at 11:09
  • @Quentin even if it's a not `function expressions` I'm using it after not before. and should been available inside `if` as `var f = function () {}; typeof f; // function`. Why this didn't happened? – NAVIN Sep 03 '18 at 11:14
  • @NAVIN — `if ( function f () { return 9; } ) ` — That's a function expression. – Quentin Sep 03 '18 at 12:30
  • @NAVIN — You aren't assigning the return value of the function expression anywhere, so `f` isn't defined. – Quentin Sep 03 '18 at 12:30
  • `a = 1` is not a declaration, it is not hoisted. It is an assignment that only works in strict mode. Prepend `"use strict";` to all of your snippets, run them again, and you will get much less surprising results. – Bergi Sep 03 '18 at 13:10
  • @Quentin Thanks got it – NAVIN Sep 03 '18 at 13:50

0 Answers0