Home  >  Article  >  Web Front-end  >  A brief discussion on null and undefined_javascript techniques in JavaScript

A brief discussion on null and undefined_javascript techniques in JavaScript

WBOY
WBOYOriginal
2016-05-16 15:50:501277browse

Let’s talk about null first, which represents a special value and is often used to describe “null value”. Perform a typeof operation on null, and the result returns the string "object". In other words, null can be considered as a special object value, which means "non-object" (it feels weird). In fact, null is usually considered to be the only member of its own type, which can represent numbers, strings, and objects as "valueless".

JavaScript also has a second value to represent the vacancy of the value, which is undefined. Undefined value is used to represent a deeper "null value". There are 4 situations when undefined occurs: ① When a variable is declared but not initialized ② When the object property or array element to be queried does not exist ③ If the function does not have any return value, undefined is returned ④ The value of a function parameter that does not provide actual parameters is also referenced will only get undefined.

The two are similar: ① As mentioned earlier, they are both "false values", which means that when JavaScript expects to use a Boolean value, they will be converted to false; ② Neither of them contains any attributes and method.

The difference between the two: ①null is a keyword in the JavaScript language, while undefined is a global variable predefined by JavaScript, not a keyword. Moreover, in ECMAScript 3, undefined is a readable and writable variable, and any value can be assigned to it. This error was corrected in ECMAScript 5. In this version, undefined is read-only (see the current statement on the Internet) Browsers basically support ECMAScript 5. I don’t know why there is no error when I assign a value to undefined in the browser, but its value is not changed); ② When the typeof operation is executed, null returns the "object" string, and undefined returns " undefined" string.

As for comparing null and undefined, null == undefined returns true, null === undefined returns false. You can think of undefined as a vacancy that represents a system-level, unexpected, or error-like value, and null as a vacancy that represents a program-level, normal, or expected value. If you want to assign them to variables or properties or pass them into functions as parameters, it is best to use null.

The above is the entire content of this article, I hope you all like it.

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