What reason is using a null value instead of undefined in JavaScript?

I have been writing JavaScript for quite some time now and I have never had a reason to use null . It seems that undefined always preferable and programmatically fulfills the same goal. What are the practical reasons to use null instead of undefined ?

+89
javascript null undefined
Jul 07 '11 at 1:01
source share
13 answers

Null and undefined are essentially two different values ​​that mean the same thing. The only difference is the agreements on how you use them in your system. As already noted, some people use null for the value "no object", where you can sometimes get the object, and undefined means that the object was not expected (or an error occurred). My problem is that it is completely arbitrary and completely unnecessary.

However, there is one significant difference - variables that are not initialized (including function parameters in which the argument was not passed, by the way) are always undefined.

This is why in my code I never use null, unless something that I do not control returns null (e.g. regular expression matching). The beauty of this is that it assimilates things very strongly. I never need to check if x === undefined || x === null. And if you're used to using == or just things like if (x) .... Stop it. !x will evaluate to true for an empty string, 0, null, NaN - i.e. things you probably don't want. If you want to write javascript that is not terrible, always use triple equals === and never use null (use undefined instead). It will make your life easier.

+39
03 Mar. '15 at 6:58
source share

I actually have no answer, but according to Nicholas S. Zakas, page 30 of his book , Professional JavaScript for Web Developers :

When defining a variable that is intended for subsequent storage of an object, it is recommended to initialize the null variable, unlike everything else. That way, you can explicitly check for null to determine if the variable was populated with an object reference at a later time.

+74
Jul 07 2018-11-11T00:
source share

You can accept the agreement proposed here, but there is really no good reason. It is not used consistently enough to be meaningful.

To make a convention useful, you must first know that the function being called follows the convention. Then you must explicitly check the return value and decide what to do. If you get undefined, you can assume that there was some kind of error that the called function found out about. But if an error occurred and the function found out about it, and it would be useful to send it to a wider environment, why not use the error object? display error?

Thus, in the end, a convention is practically worthless except for very small programs in simple environments.

+11
Jul 07 2018-11-11T00:
source share

undefined there is no concept of the concept of a thing; he has no type, and he was never mentioned before in this area; null is where the thing is known to exist, but it doesn't matter.

+9
Jul 07 2018-11-11T00:
source share

Each has its own coding method and its own internal semantics, but over the years I have found this to be the most intuitive advice that I give to people who ask this question: when in doubt, do what JavaScript does .

Suppose you are working with object properties, such as jQuery plugin options ... ask yourself what JavaScript value gives a property that is not yet defined - the answer is undefined . Therefore, in this context, I would initialize these types of things with undefined so that it matches JavaScript (for variables you can do var myVar; instead of var myVar = undefined; ).

Now let's say that you are manipulating the DOM ... what value does JavaScript assign to non-existent elements? The answer is null . This is the value that I would initialize if you create a placeholder variable that will later contain a link to an element, document fragment or similar information related to the DOM.

If you are working with JSON, you need to make a special case: for undefined property values, you must either set them to "" or null , because an undefined value is not considered the correct JSON format.

With that said, as the previous poster put it, if you find that you initialize the material using null or undefined more than once in the blue moon, then you might want to reconsider how you are going to code your application.

+9
Oct 28 '15 at 17:29
source share

At the end of the day, since both null and undefined lead to the same value ( Boolean(undefined) === false && Boolean(null) === false ), you can technically use either of them to get the job done. However, there is a right path, IMO.

  1. Leave using undefined for the JavaScript compiler.

    undefined used to describe variables that do not point to a link. This is what the JS compiler takes care of you. During compilation, the JS engine will set the value of all moved variables to undefined . When the engine goes through the code and the values ​​become available, the engine will assign the appropriate values ​​to the corresponding variables. For those variables for which no values ​​are found, the variables will continue to maintain a reference to the undefined primitive.

  2. Use null only if you explicitly want to designate the value of the variable as "no value".

    As @ com2gz states: null used to define something programmatically empty. undefined means the link does not exist. null value has a specific reference to "nothing." If you call a non-existent property of an object, you will get undefined . If I made this property intentionally empty, then it must be null so that you know that it is intentional.

TL; DR; Do not use undefined primitive. This is the value that the JS compiler will automatically set for you when you declare variables without assignment or try to access the properties of objects that are not referenced. On the other hand, use null if and only if you intentionally want the variable to not matter.

I have never explicitly set anything to indefinite (and I have not come across this in many codebases that I interacted with). Also, I rarely use null . The only time I use null is when I want to designate the value of a function argument as irrelevant, that is:

 function printArguments(a,b) { console.log(a,b); } printArguments(null, " hello") // logs: null hello 
+5
Jan 10 '18 at 22:55
source share

DOM nodes and elements are not undefined, but can be null.

  • NextDecrease in the last child of an element is null.

  • PreviousDecrease in the first child is null.

  • The link document.getElementById is null if the item does not exist in the document.

But in none of these cases is the value undefined ; there simply is no node.

+2
Jul 07 '11 at 3:28
source share

A useful property in null that undefined does not qualify:

 > null + 3 3 > undefined + 3 NaN 

I use null when I want to "turn off" a numerical value, or initialize some. My last use was css conversion control:

 const transforms = { perspective : null, rotateX : null }; // if already set, increase, if not, set to x runTimeFunction((x) => { trasforms.perspective += x; }); // still useful, as setting perspective to 0 is different than turning it off runTimeFunction2((x) => { transforms.perspective = null; }); // toCss will check for 'null' values and not set then at all runTimeFunction3(() => { el.style.transform = toCss(transforms); }); 

Not sure if I should use this property ...

+2
Aug 27 '16 at 23:37
source share

Here's the reason: var undefined = 1 is legal javascript, but var null = 1 is a syntax error. The difference is that null is a language keyword, and undefined for some reason.

If your code relies on comparing with undefined , as if it were a keyword ( if (foo == undefined) is a very simple mistake), this only works because no one has defined a variable with that name. All this code is vulnerable to someone accidentally or maliciously defining a global variable with this name. Of course, we all know that randomly defining a global variable is completely impossible in javascript ...

+2
Sep 07 '16 at 0:29
source share

I totally disagree that using null or undefined is not required. undefined is a thing that supports the entire prototype chain process. Thus, a compiler with a null value cannot check whether this property is null or not defined in the prototype endpoint. In other dynamically typed languages ​​(e.g. Python), it throws an exception if you want to access an undefined property, but for prototype-based programming languages, you also need to check the parent prototypes and this is the place where undefined is most needed.

The whole point of using null is simply a variable or a property to bind to an object that is single-point and has the meaning of void, and also zero use has performance. This code has different runtimes.

 var p1 = function(){this.value = 1}; var big_array = new Array(100000000).fill(1).map((x, index)=>{ p = new p1(); if(index > 50000000){ px = "some_string"; } return p; }); big_array.reduce((sum, p)=> sum + p.value, 0) var p2 = function(){this.value = 1, px = null}; var big_array = new Array(100000000).fill(1).map((x, index)=>{ p = new p2(); if(index > 50000000){ px = "some_string"; } return p; }); big_array.reduce((sum, p)=> sum + p.value, 0) 
+1
Jun 23 '16 at 12:06 on
source share

I am working on this exact question right now and am looking at the following philosophy:

  • Any function designed to return a result must return null if it cannot find a result.
  • Any function that is NOT intended to return a result implicitly returns undefined.

For me, this question is significant, because anyone calling a function that returns a result should not doubt whether to test for undefined vs null.

This answer does not attempt to address:

  • Null vs undefined property values
  • Variables in your functions vanish vs undefined

In my opinion, variables are your own business, not part of your API, and properties in any OO system are defined and therefore must be defined with a value different from what they will be if not defined (null for certain, undefined - this is what you get when accessing something that is not in your object).

+1
Jul 01 '16 at 16:33
source share

Some have said that you can initialize null objects. I just wanted to note that the default values ​​for the destructuring arguments do not work with null . For example:

 const test = ({ name } = {}) => { console.log(name) } test() // logs undefined test(null) // throws error 

This requires performing null checks before calling the function, which can happen often.

0
Mar 17 '19 at 0:52
source share

I just want to add that using certain JavaScript libraries, null and undefined can have unintended consequences.

For example, the lodash get function, which takes a default value as the third argument:

 const user = { address: { block: null, unit: undefined, } } console.log(_.get(user, 'address.block', 'Default Value')) // prints null console.log(_.get(user, 'address.unit', 'Default Value')) // prints 'Default Value' console.log(_.get(user, 'address.postalCode', 'Default Value')) // prints 'Default Value' 

Another example: if you use defaultProps in React, if the property is set to null , the default details are not used, because in fact null is interpreted as defined by the user. eg

 class MyComponent extends React.Component { static defaultProps = { callback: () => {console.log('COMPONENT MOUNTED')}, } componentDidMount() { this.props.callback(); } } //in some other component <MyComponent /> // Console WILL print "COMPONENT MOUNTED" <MyComponent callback={null}/> // Console will NOT print "COMPONENT MOUNTED" <MyComponent callback={undefined}/> // Console WILL print "COMPONENT MOUNTED" 
0
Jul 18 '19 at 8:54
source share



All Articles