Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about if statement in function in javascript - how if the if statement return true but the function return false

can i ask you guys a question? Below is my code:

var num = 1;
var isNumberEqualOne = function(){
    if(num == 1){
      return true;
    }
    return false;
}();
alert(isNumberEqualOne);

In this code, the statement in the function return true, after return true, the code in the function is still executing right? So at the end, the code meet return false, so why the function still return true.Sorry for my bad english.Thanks

like image 805
dramasea Avatar asked Dec 12 '22 12:12

dramasea


1 Answers

return will halt the function and return immediately. The remaining body of code in the function will not be executed.

In your example, num is assigned 1, so the condition inside your function is true. This means that your function will return there and then with true.

You could also rewrite that function so its body is return (num == 1).

like image 79
alex Avatar answered Apr 28 '23 11:04

alex