Js local and global variables

function f(shouldInitialize: boolean) {
    if (shouldInitialize) {
        var x = 10;
    }

    return x;
}

f(true);  // returns "10"
f(false); // returns "undefined"

the x here is in the if statement but also in the f function as a local variable. Why does false return undefined? Shouldn"t you also return 10

Mar.22,2021

function f(params){
        var x;
        if(params){
            x = 10; //var x=10; 
        }
        return x;
    }
    f(false);//undefined 

Thank you very much for your warm-hearted advice. Is that what variable promotion means upstairs? this should be the step of the program

.

because x is not defined
false equates to

function f(shouldInitialize: boolean) {
    return x;
}

this is a matter of scope.
uses the var keyword, and the scope of the variable is improved. In true, you can't go here when you can see xpencil false on the outside of if, but you can't see it on the outside.

you can try let or const, even if your true, reports an error directly x is not defined.


laxatives, for this problem, var is the functional scope, that is, the function level. {} cannot limit its domain, there is a variable prompt.
that is, when the js interpreter interprets, it first iterates through the variables in function to make a pre-declaration, and then parses it by line.
this question, after the program enters the function:

  1. declares x first, but does not assign a value, for undefined
  2. then parses if, and finds that var x = 10 if it is false,; this sentence is not executed, but return x is executed directly. Then there is undefined
< hr >

you can compare the following two pieces of code

  

your first question: is undefined returned? The first reaction to the question is to use variable promotion to help you solve the problem, but when you see the second question, you go so far as to ask: shouldn't you also return 10? Suddenly hesitated to answer the first question.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b38262-2b86a.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b38262-2b86a.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?