Why if (true) is true here?

Tell us what’s happening:

  • I wanna know why if(true) in the checkScope function is false?
  • Why it is returning “function scope”?
  • When cant I see any of the output in the Chrome Inspector’s Console?

Your code so far


function checkScope() {
"use strict";
  let i = "function scope";
  if (true) {
    let i = "block scope";
    console.log("Block scope i is: ", i);
  }
  console.log("Function scope i is: ", i);
  return i;
}

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywordsTell us what’s happening:
I wanna know why if(true) in the checkScope function is false ?
Why it is returning “function scope”

if(true) doesn’t contain a return statement, so the i that is returned is always “function scope”.

Here is a discussion on what you need: link

First thing, code in if (true) will always run because true === true.
That’s why when you run

console.log(checkScope())

and it shows

"Block scope i is: " "block scope"
"Function scope i is: " "function scope"
"function scope"

Lastly, this task is checking Scope, as you can see Scope of “function scope” is checkScope, and Scope of “Block scope” is if, checkScope() return i with i has Scope is function.

Now, you move return i to inside if, I am sure that you can understand deeply.
Rememeber, you are using let, not const.

1 Like