[SOLVED] Why do functions return `undefined` instead of `null` by default?


Why do JavaScript functions return undefined by default instead of null? Is this a totally arbitrary choice by the specification, or is there a larger ECMAScript-behavior context in which this particular choice can be understood?

function a() {}
// undefined

What is the difference between null and undefined? Is there a specification-based reason why is undefined more appropriate as a default return value, or was it an arbitrary choice?


The specification says of null and undefined:

undefined value

primitive value used when a variable has not been assigned a value

null value

primitive value that represents the intentional absence of any object value

undefined represents a failure to assign a value. It is the total absence of a value. null represents the positive assertion of a non-value in an object context. null is intended to be used when an object is expected but the current value is no-object.

Given these two definitions, it seems obvious that undefined is the correct choice, since

  1. functions can return values other than objects, and
  2. a failure to specify a return value maps neatly onto a failure to assign a value

Answered By – apsillers

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *