Why Is There a 'Null' Value in JavaScript

How do I check for null values in JavaScript?

JavaScript is very flexible with regards to checking for "null" values. I'm guessing you're actually looking for empty strings, in which case this simpler code will work:

if(!pass || !cpass || !email || !cemail || !user){

Which will check for empty strings (""), null, undefined, false and the numbers 0 and NaN.

Please note that if you are specifically checking for numbers, it is a common mistake to miss 0 with this method, and num !== 0 is preferred (or num !== -1 or ~num (hacky code that also checks against -1)) for functions that return -1, e.g. indexOf).

Why is there a `null` value in JavaScript?

The question isn't really "why is there a null value in JS" - there is a null value of some sort in most languages and it is generally considered very useful.

The question is, "why is there an undefined value in JS". Major places where it is used:

  1. when you declare var x; but don't assign to it, x holds undefined;
  2. when your function gets fewer arguments than it declares;
  3. when you access a non-existent object property.

null would certainly have worked just as well for (1) and (2)*. (3) should really throw an exception straight away, and the fact that it doesn't, instead of returning this weird undefined that will fail later, is a big source of debugging difficulty.

*: you could also argue that (2) should throw an exception, but then you'd have to provide a better, more explicit mechanism for default/variable arguments.

However JavaScript didn't originally have exceptions, or any way to ask an object if it had a member under a certain name - the only way was (and sometimes still is) to access the member and see what you get. Given that null already had a purpose and you might well want to set a member to it, a different out-of-band value was required. So we have undefined, it's problematic as you point out, and it's another great JavaScript 'feature' we'll never be able to get rid of.

I actually use undefined when I want to unset the values of properties no longer in use but which I don't want to delete. Should I use null instead?

Yes. Keep undefined as a special value for signaling when other languages might throw an exception instead.

null is generally better, except on some IE DOM interfaces where setting something to null can give you an error. Often in this case setting to the empty string tends to work.

Can a null value automatically occur in JS

undefined is what is returned when you attempt to access a property that is not there or an array value that is not there. It is also the initial value of a variable that has been declared, but not assigned a value yet. These are not really mistakes, but the way the language is designed when you request a value that is not there.

null does not occur by default like undefined does. If a variable or property or return value is null, that is because some programmer or API specifically assigned or returned null.

Also, calling a function that does not exist throws a ReferenceError.

Why is null an object and what's the difference between null and undefined?

(name is undefined)

You: What is name? (*)

JavaScript: name? What's a name? I don't know what you're talking about. You haven't ever mentioned any name before. Are you seeing some other scripting language on the (client-)side?

name = null;

You: What is name?

JavaScript: I don't know.

In short; undefined is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; null is where the thing is known to exist, but it's not known what the value is.

One thing to remember is that null is not, conceptually, the same as false or "" or such, even if they equate after type casting, i.e.

name = false;

You: What is name?

JavaScript: Boolean false.

name = '';

You: What is name?

JavaScript: Empty string


*: name in this context is meant as a variable which has never been defined. It could be any undefined variable, however, name is a property of just about any HTML form element. It goes way, way back and was instituted well before id. It is useful because ids must be unique but names do not have to be.

What reason is there to use null instead of undefined in JavaScript?

null and undefined are essentially two different values that mean the same thing. The only difference is in the conventions of how you use them in your system. As some have mentioned, some people use null for meaning "no object" where you might sometimes get an object while undefined means that no object was expected (or that there was an error). My problem with that is its completely arbitrary, and totally unnecessary.

That said, there is one major difference - variables that aren't initialized (including function parameters where no argument was passed, among other things) are always undefined.

Which is why in my code I never use null unless something I don't control returns null (regex matching for example). The beauty of this is it simplifies things a lot. I never have to check if x === undefined || x === null, I can just check x === undefined. And if you're in the habit of using == or simply stuff 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 isn't awful, always use triple equals === and never use null (use undefined instead). It'll make your life way easier.

What is the JavaScript behavior of a null value?

In EcmaScript definition, null is "primitive value that represents the intentional absence of any object value", but it seams impossible in JavaScript at list by my tests, excluding the case of v = null that i think is a Null type of var.

Well, all the test cases in your test had a value. I'm not sure why you did exclude

Teste.Null = null;

but it would have worked for it. Also, a Teste.Undefined = undefined would be compare as equal to null.

var result = "";var Teste = {    Null: null,    Undefined: undefined,    ObjectNew: new Object(),    StringNew: new String(),    NumberNew: new Number(),    ArrayNew: new Array(),    ObjectLiteral: {},    StringLiteral: "",    NumberLiteral: 0,    ArrayLiteral: [],    ObjectNull: Object(null),    StringNull: String(null),    NumberNull: Number(null),    ArrayNull: [null]}for (var i in Teste) {    result += "<p>Type "+i+" is"+(Teste[i] == null?"":" not")+" null: "+Teste[i]+"</p>";}
document.getElementById("result").innerHTML = result;
<div id="result"></div>

What is the difference between null and undefined in JavaScript?

undefined means a variable has been declared but has not yet been assigned a value :

var testVar;
console.log(testVar); //shows undefined
console.log(typeof testVar); //shows undefined

Why would you pass 'null' to 'apply' or 'call'?

Calling apply with null as the first argument is like calling the function without providing any object for the this.

What does the apply method do?

The apply() method calls a function with a given this value and
arguments provided as an array (or an array-like object).

fun.apply(thisArg, [argsArray])

thisArg

The value of this provided for the call to fun. Note that this may not
be the actual value seen by the method: if the method is a function in
non-strict mode code, null and undefined will be replaced with the
global object, and primitive values will be boxed.

Further documentation can be found here.

Javascript NULL Values

You don't have to do that:

var n=null;

if(n)alert('Not null.'); // not shown
if(!n)alert('Is null.'); // popup is shown

Your error implies otherwise:

var n=null;

alert(n.something); // Error: n is null or not an object.

In the case above, something like this should be used:

if(n)alert(n.something);

Why do people declare something as null in JavaScript?

It helps to appreciate the difference between a value and a variable.

A variable is a storage location that contains a value.

null means that the storage location does not contain anything (but null itself is just a special kind of value). Read that last sentence carefully. There is a difference between what null is and what null means. 99% of the time you only care about what null means.

Undefined means that the variable (as opposed to the value) does not exist.



Related Topics



Leave a reply



Submit