For example:
function example() {
console.log("outside the if block above function b declaration"+b());
function a() {
return "you invoked function a";
}
if (true) {
console.log("inside the if block"+a());
console.log("inside the if block above function b declaration"+b());
function b() {
return "you invoked function b";
}
}
}
When i invoke this example() function, I get an error that b is undefined, but when I remove the 2nd line that invokes with function b defined inside the if block It's all ok?
Yes and no. The keyword let
does support a local scope in blocks. The keywords function
and var
work on the function level scope. They define an indentifier, when the block is compiled before execution. So you normally can call functions above the declaration.
In your example the function is declared conditionally. It will get declared after the condition is evaluated and before the inner block is executed. But when it gets declared, it is valid in the entire function's scope. Try moving the invokation below the if-block, and it will be known and executed.
No, it does not. If blocks remain scoped to their containers. Your function B is undefined because the code which defines it never gets executed when blocked by the if statement. However, once the if statement is removed, the code defining the function is executed, defining the function.
Here is a jsfiddle demonstrating the concept.
function defining() {
ifstmt = true;
if(ifstmt) {
var ifscope;
ifscope = "yes";
}
console.log(ifscope); // logs "yes"
}
function notDefining () {
ifstmt = false;
if(ifstmt) {
var ifscope;
ifscope = "no";
}
console.log(ifscope); // logs undefined
}
defining()
notDefining()
in defining()
the variable ifscope
gets defined but clearly isn't limited to the scope of the if statement. In notDefining()
the code defining ifscope
gets skipped and therefore the console.log
returns undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With