1

Why

 var y = 1;
  if (function f(){}) {
    y += typeof f;
  }
  console.log(y); // 1undefined

Before running code I suppose it will be 1function

I suppose that behind function hoisting f should be visible for all code. Can you provide link for such behavior description?

P.S> at blog post where I find this example there is explanation

The output would be 1undefined. The if condition statement evaluates using eval, so eval(function f(){}) returns function f(){} (which is true). Therefore, inside the if statement, executing typeof f returns undefined because the if statement code executes at run time, and the statement inside the if condition is evaluated during run time.

But it doesn't make situation clearer

7
  • what is the question? and also what is the purpose? Commented Jul 2, 2016 at 10:51
  • I suppose it will be 1function Commented Jul 2, 2016 at 10:52
  • I know but why are you trying to do this? can you give a real world example? I'm just curious Commented Jul 2, 2016 at 10:53
  • Write this: var f = function(){}; before the if, and you'll get 1function. Commented Jul 2, 2016 at 10:54
  • 2
    That's a function expression, not a declaration, and therefore not introducing any variables in any scope. And the quoted explanation is rubbish, there is no eval Commented Jul 2, 2016 at 10:54

1 Answer 1

3

The confusion here is that the syntax function fName() {} is ambiguous and depends on context.

Alone, it is a function declaration and is therefore hoisted. But in certain contexts it is a (named) function expression and therefore isn't.

This is why you see IIFEs declared as (function() {..})() or !function() {..}() to force them into being function expressions rather than declarations.

The important thing about named function expressions is that their name is essentially local to the function itself, and is not accessible outside that function. This is why += f appends undefined in your code.

Of course, this is all completely pointless. Why would anyone in their right minds write such code? So I would like to leave you with this: https://youtu.be/RAA1xgTTw9w :)

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

Comments

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.