Statement execution problems in JS?

function fn() {
    alert ("wo")
}
console.log(fn())

Why is it that when I execute the above code, the pop-up box pops up first? there"s nothing wrong with this, but console.log outputs undefined?. Where did this undefined come from?

Mar.03,2021

JavaScript Advanced programming (3rd Edition), page 64, the function does not set return, and returns undefined by default.


when interacting with the console, the console will automatically print the value of the expression you entered. For example, if you enter 1 and then press enter, it will print you the value of 2 , 2 , that is, 1 . When you enter console.log (fn ()) , you will first print a return value of fn () , that is, < code. Then print out the second undefined , because there is neither a value nor a return value after the console.log call, so print undefined .


undefined because your function does not return a value, which can be compared with the following code

function fn() {
    alert ('wo')
    return 'wo'
}
console.log(fn())
The

function does not return a value


return returns' wo'


function is divided into two cases: 1 A return value is specified, that is, return xx;2 does not specify a return value, and undefined is returned by default at this time.

Menu