2

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.

7
  • 3
    where do you get undefined? in the console maybe? Commented Feb 13, 2018 at 10:14
  • When you call this function, it return undefined instead of 0 ? Commented Feb 13, 2018 at 10:14
  • 1
    You should call/console the function as console.log( x() ); and not as console.log( x ); . I am just assuming here :) Commented Feb 13, 2018 at 10:16
  • I think he refers to the console. When you just declare the function. Commented Feb 13, 2018 at 10:16
  • @eisbehr I think he tried this in console and means at the time of declaration Commented Feb 13, 2018 at 10:16

2 Answers 2

4

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;}
Sign up to request clarification or add additional context in comments.

3 Comments

Okay, thank you. So if I understand correctly, Javascript always wants a return from every statement and command?
Yes you can see it as such : in JS a statement can be used in place of an expression, and its value will be undefined (which makes it pretty useless in that place).
undefined is the implicit return type in js, see stackoverflow.com/a/20915520/2455159
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.