简体   繁体   中英

Where is "undefined" coming from here?

I have the following code:

console.log(doSomething);
doSomething();

function doSomething() {
    console.log("Declare something");
}

which in the console returns

[Function: doSomething]
Declare something

But when I write

console.log(doSomething());

function doSomething() {
    console.log("Declare something");
}

the console says

Declare something
undefined

I understand why it just says "Declare something" and not "[Function: doSomething]", but why does it say "undefined"? Why does it not say "Declare something Declare something"?

Undefined is the return value of the function. Change your function for this for example to prove it.

function doSomething() {
    console.log("Declare something");
    return "test";
} 

The second log is regarding your console.log(doSomething()); which is printing the return of your function. In this case, you are not returning anything and therefore it prints undefined .

Thats because you didn't declare the return statement of the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM