var y = 1;
if(function f(){}){
y += typeof f;
}
console.log(y);
Can anyone give an answer with an explanation about the above code?
var y = 1;
if(function f(){}){
y += typeof f;
}
console.log(y);
Can anyone give an answer with an explanation about the above code?
Yes this appropriate behavior. The expression function f(){}
will be converted to boolean. And will return true because function is always truthy.
console.log(Boolean(function f(){}))
Now lets come to the second part. Why y
is 1undefined
. The function f
is a named function which is only visible in its own function body. You are try to access f
in the body of if
so its not accessible there hence it its type is "undefined"
console.log(typeof x); //undefined
So 1 + "undefined" is equal to "1undfined"(1 will converted to string and added to "undefined")
console.log(1+"undefined")
In your case, the function is declared and defined inside the if
statement which is a block scope and its scope is only valid inside those parentheses. And the if block is getting evaluated because in JavaScript anything inside the if
condition is coerced to an equivalent truthy or falsy value and for all truth values the if
loop is executed.
var y = 1;
if (function f() {}) { // f has limited scope i.e within the if parenthesis only
y += typeof f; //typeof f is "undefined" and 1+undefined gets concatinated as "1undefined"
}
console.log(y);
But if you do it like this you will get the desired result:
var y = 1;
let fun=function f(){} //Here the fun has scope outside if statement
if(fun){
y += typeof fun; //type of fun will be function not undefined
}
console.log(y);