Charles Saag
Charles Saag

Reputation: 631

Why do Javascript functions return "undefined" on creation?

I understand the difference between undefined and null as a type; I'm just not grasping the following event:

function x() {
    return 0;
}

undefined

Why does this happen? What is going on under the hood that is causing the environment to return an "undefined" value?

UPDATE: I'm not invoking the function in the example above, just defining it and the console returns this "undefined" value.

Upvotes: 2

Views: 1160

Answers (2)

Mathias Dolidon
Mathias Dolidon

Reputation: 3903

This fuction definition is a statement. In JS, statements don't return values, which, in JS, is an undefined value.

In JS, assignments with var are statements too, but assignments without var behave as expressions : their whole value is the value being assigned.

Therefore, in the console :

> x=function() {return 0;}
< ƒ () {return 0;}

Upvotes: 4

Quentin
Quentin

Reputation: 943591

What is going on under the hood that is causing the environment to return an "undefined" value?

In this case, undefined represents the lack of a value.

You haven't run any expression, so there is no value to arise from it.

Upvotes: 2

Related Questions