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.

Charles Saag
  • 611
  • 5
  • 20

2 Answers2

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;}
Mathias Dolidon
  • 3,775
  • 1
  • 20
  • 28
  • Okay, thank you. So if I understand correctly, Javascript always wants a return from every statement and command? – Charles Saag Feb 13 '18 at 10:25
  • 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). – Mathias Dolidon Feb 13 '18 at 10:26
  • undefined is the implicit return type in js, see https://stackoverflow.com/a/20915520/2455159 – Stephan Luis Sep 03 '20 at 18:42
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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335