Why do people declare something null in JavaScript?

Possible duplicate:
Why is javascript null ?

I don’t understand what zero is for. 'Undefined'.

+4
source share
5 answers

This helps evaluate the difference between a value and a variable.

A variable is a storage location containing a value.

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

Undefined means that the variable (unlike the value) does not exist.

+6
source

null is an object that you can use when creating variables when you don't have a value yet:

 var myVal = null; 

When you do this, you can also use it to check to determine if it is defined:

 // null is a falsy value if(!myVal) { myVal = 'some value'; } 

I would not use it as usual. It is simple enough to use 'undefined', instead:

 var myVal; // this is undefined 

And it still works as a false value.

Create Objects

When you create an object in javascript, I like to declare all my object properties at the top of my object function:

 function myObject() { // declare public object properties this.myProp = null; this.myProp2 = null; this.init = function() { // ... instantiate all object properties }; this.init(); } 

I do this because it is easier to see which properties of the object are directly on the bat.

+2
source

If a variable is unknown or not initialized in the current scope, it is undefined .

If you want to use a variable and indicate that it has an invalid value, for example, you can set it to null , since accessing the undefined variable will result in an error if you try to work with it (despite checking if it is undefined).

If something is undefined, you also have the option to add it to the object. If a variable is defined but contains null, you know that this variable can be used by another part of your program.

+1
source

For example, it can prepare a global variable that will be used in most parts of the code.

If you run your code with var iNeedThisEverywhere = null; , you can use it inside other objects / actions in the code, but if you do not, this variable will not be used in the whole code.

Of course, you really put something inside this variable somewhere during the code, but since you defined this variable at the very beginning, it will still be split anyway.

0
source

A null-holding value contains a reference to a black hole named null.

 10 + 10 + null = null 

Null has historically been linked to databases, http://en.wikipedia.org/wiki/Null_(SQL ) (Correct me if I am wrong here)

An uninitialized (unknown) variable is undefined.

Regards, / T

0
source

Source: https://habr.com/ru/post/1347449/


All Articles