Learn javascript's undefined and null_javascript skills from me
When discussing primitive data types in JavaScript, most people know the basics from String to Number to Boolean. These primitive types are fairly simple and behave like common sense. However, this article will focus more on the unique primitive data types Null and Undefined, and what makes them so similar yet paradoxical.
1. Understand null and undefined
In JavaScript, null is a literal and a keyword in the language, used to represent unrecognized object values. In other words, this is used to mean "no value", but you can decide when to get the expected value.
Although similar, undefined actually represents non-existence of a value, which means you have something missing. Both are completely immutable, have no properties and methods, and their properties cannot be assigned values. In fact, a TypeError will be raised when you try to access or define a property that is null or undefined.
Boolean values represented by no value are false, which means they will evaluate to false in a conditional context, such as an if statement. Use the equality operator (==) to compare these two values with other false values, they are not equal except themselves:
null == 0; // false undefined == ""; // false null == false; // false undefined == false; // false null == undefined; // true
However, and other similarities, null and undefined are not equivalent. Each is a unique member of its own type, undefined is of type Undefined and null is of type Object. Compare these two values using the equality operator (===), which requires that both types and values are equal, as shown below:
null === undefined; //false typeof null; //"object" typeof undefined; //"undefined"
The above description: null This is an object, but it is empty. And null is a JavaScript reserved keyword.
In addition, when null participates in numerical operations, its value will be automatically converted to 0. Therefore, the following expression will obtain the correct value after calculation:
123 + null; //123 123 * null; //0
undefined is a special property of the global object (window), and its value is undefined. But typeof undefined returns 'undefined' .
Although undefined has a special meaning, it is indeed a property, and it is a property of the global object (window). Please look at the code below:
alert('undefined' in window);//输出:true var anObj = {}; alert('undefined' in anObj); //输出:false
It can be seen from this that undefined is a property of the window object, but it is not a property of the anObj object.
Note:
- Although undefined is an attribute with special meaning, it is not a reserved keyword in JavaScript. When undefined participates in any numerical calculation, the result must be NaN. By the way, NaN is another special property of the global object (window), and so is Infinity. None of these special attributes are reserved keywords for JavaScript!
- When verifying that a value or object is null, you need to use "===" to determine. If you only use "==", you cannot determine whether it is null or undefined.
2. Undefined situation occurs
There are many ways to generate code with an undefined value. It is usually encountered when trying to access a value that does not exist. In this case, in a dynamic and weakly typed language like JavaScript, an undefined value will be returned by default instead of rising to an error.
1. Any variable declared without an initial value will have a default value of undefined:
var foo; // 默认值为 undefined
2. When trying to access a non-existent object property or array item, an undefined value is returned:
var array = [1, 2, 3]; var foo = array.foo; // foo 属性不存在, 返回 undefined var item = array[5]; // 数组中没有索引为5的项,返回 undefined
3. If the return statement of the function is omitted, or the return statement does not take any parameters and returns undefined:
var value = (function(){ })(); // 返回 undefined var value1 = (function(){ return; })(); // 返回 undefined
4. When calling the function, the parameter that should be provided is not provided, and the parameter is equal to undefined
function f(x){ console.log(x) } f(); // undefined
Finally, undefined is a predefined global variable (unlike the null keyword) initialized to the undefined value:
'undefined' in window; // true
ECMAScript 5中,这个变量是只读的,以前并非如此。
三、null的用例
null的用例是使他与众不同的主要方面,因为不像undefined,null被认为是更有用。这正是为什么typeof操作符作用于null值 时返回“object”。最初的理由是,现在仍然是,通常用作一个空引用一个空对象的预期,就像一个占位符。typeof的这种行为已经被确认为一个错 误,虽然提出了修正,出于后兼容的目的,这一点已经保持不变。
一般来说,如果你需要给一个变量或属性指定一个不变值,将它传递给一个函数,或者从一个函数返回null,null几乎总是最好的选择。简而言之,JavaScript使用undefined并且程序员应该使用null。
null的另一个可行的用例,也被认为是良好的实践是一个显式指定变量为无效(object= null)当一个引用不再是必需的。通过分配null值,有效地清除引用,并假设对象没有引用其他代码,指定垃圾收集,确保回收内存。
四、提高undefined性能
当我们在程序中使用undefined值时,实际上使用的是window对象的undefined属性。 同样,当我们定义一个变量但未赋予其初始值,例如:
var aValue;
这时,JavaScript在所谓的预编译时会将其初始值设置为对window.undefined属性的引用, 于是,当我们将一个变量或值与undefined比较时,实际上是与window对象的undefined属性比较。这个比较过程中,JavaScript会搜索window对象名叫‘undefined'的属性,然后再比较两个操作数的引用指针是否相同。
由于window对象的属性值是非常多的,在每一次与undefined的比较中,搜索window对象的undefined属性都会花费时 间。在需要频繁与undefined进行比较的函数中,这可能会是一个性能问题点。因此,在这种情况下,我们可以自行定义一个局部的undefined变 量,来加快对undefined的比较速度。例如:
function anyFunc() { var undefined; //自定义局部undefined变量 if(x == undefined) //作用域上的引用比较 while(y != undefined) //作用域上的引用比较 };
其中,定义undefined局部变量时,其初始值会是对window.undefined属性值的引用。新定义的局部undefined变 量存在与该函数的作用域上。在随后的比较操作中,JavaScript代码的书写方式没有任何的改变,但比较速度却很快。因为作用域上的变量数量会远远少 于window对象的属性,搜索变量的速度会极大提高。
这就是许多前端JS框架为什么常常要自己定义一个局部undefined变量的原因!
以上就是本文的全部内容,希望对大家的学习有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

If you often encounter the error message "TypeError: Cannotreadproperty'$XXX'ofundefined" when developing with Vue.js, how should you deal with it? This article explains the causes of this error and how to fix it. The cause of the problem is that when using Vue.js, we often use this to call methods of Vue components, such as: exportdefault{data()

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).
