Home  >  Article  >  Web Front-end  >  A brief discussion on null and undefined in javascript

A brief discussion on null and undefined in javascript

零下一度
零下一度Original
2017-06-26 09:11:541575browse

As long as we talk about the variables and data types of js, null and undefined are indispensable. These two brothers are the important foundation of js. They must be observed. Countless students have used magnifying glasses to study in multiple batches from multiple angles. These two brothers are really popular. ^-^

js is really weird. It is not enough to have null, but also to create an undefined.

Although it has been criticized, this is the design.

In C# and Java, null means empty and no memory is allocated.

The result of using Number(null) for null in js is 0. What does it mean? It means that it is not empty, it is just a null value, it has no value, and its data type is "object".

So in order to express emptiness, the designer created an undefined, which has a separate data type, which is "undefined".

The result of using Number(undefined) is NaN, and the conversion result can also achieve the design purpose.

The data type conversion in the expression plays a key role in causing such design results.

An undefined variable or a variable that is defined but not assigned a value means empty, which is undefined.

undefined is more used by javascript itself.

For example, if a coder wants to delete the attribute of an object, it is not necessary to assign the attribute to undefined, because then the attribute is still there. Use hasOwnProperty to check that the attribute still exists, and it will appear in some places where logic needs to be judged. The problem is, if you want to delete an attribute, precede delete.

var o1={p1:'v1',p2:'v2'};
o1.p2=undefined;
o1.hasOwnProperty('p2'); //true

To delete array elements, in order to have no side effects, use splice.

Coders need to think carefully if they use undefined to assign values.

For programmers, null is more commonly used. You can assign a null value to a variable, disconnect it from the object instance, ensure garbage collection, and prepare for the problem. Variable symbols are used later.

When comparing null and undefined, there are pitfalls

null == undefined //truenull == false //falseundefined == false //false

Although it is weird, this is the result and this is the design.

You can view the relevant definitions of ECMA-262, rule definition link 1, link 2.

END

The above is the detailed content of A brief discussion on null and undefined in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn