This article brings you relevant knowledge about javascript. Null is a primitive type, which means it intentionally does not contain any object value. Let’s take a look at everything about null in JavaScript: What does it mean, how to detect it, the difference between null and undefined, and why extensive use of null can cause code maintenance difficulties, etc. I hope it will be helpful to everyone.
【Related recommendations: javascript video tutorial, web front-end】
JavaScript
There are two types: primitive types (strings, booleans, numbers, symbols
) and objects
Objects are a complex data structure. The simplest JavaScript
objects are ordinary objects - a collection of keys and related values
let myObject = { name: 'Eric Cartman' };
But in many cases it is not possible to create an object. In this case, JavaScript
provides a special value null
- indicating that the object is missing
let myObject = null;
In this article, you will learn about ## Everything about null
in #JavaScript: what it means, how to detect it, the difference between
null and
undefined, and why # is used a lot ##null
Will cause difficulty in code maintenance, etc.1. The concept of null
is described in the specificationnull
null is a primitive type that intentionally does not contain any object value
If you see
null (assigned to a variable or returned by a function), then at that location it should have is an object, but for some reason, an object was not createdFor example, the function
creates an object, but it can also returnnull## when the object cannot be created. #:
function greetObject(who) { if (!who) { return null; } return { message: `Hello, ${who}!` }; } greetObject('Eric'); // => { message: 'Hello, Eric!' } greetObject(); // => null
When a string parameter is passed in to the above function, as expected, the function returns an object
{ message: 'Hello, Eric!' }
However, when no parameters are passed in the function, the function returns
null
null because the
who parameter has no value, resulting in the
greeting object being unable to be created
1.1 A more appropriate metaphor for null
null
, you can think of a variable as a box. Just like variables can hold objects, boxes can hold items like teapots etc. But once you receive a box, open it, there's nothing! Someone made a mistake and gave you an empty box. The box does not contain any content, or in other words, it contains anull value
Check
null
const missingObject = null;
const existingObject = { message: 'Hello!' };
missingObject === null; // => true
existingObject === null; // => false
missingObject === null The result is
true
missingObject variable contains a
null value. If the variable contains a non-null value, such as an object, the expression
existingObject === null evaluates to
false2.1 null is a false value
null
false
, 0, ",undefined,
NaN are all false values. If they are encountered in a conditional statement , then
JavaScript will coerce them to
false
Boolean(null); // => false if (null) { console.log('null is truthy'); } else { console.log('null is falsy'); // logs 'null is falsy' }
2.2 typeof null
typeof value type operators can determine The type of value. For example, type 15 is number
,typeof { prop: 'Value' } is equal to
object.
Interesting Yes,
null What is the result of value type
typeof null; // => 'object'
objectis treated as? It turns out that
typoef null
object. This is a bug in the early
JavaScript implementation.
Do not use The
typeof operator detects
null
myVar === null if you want To use
typeof to check whether a variable is an object, you must exclude the
null
function isObject(object) { return typeof object === 'object' && object !== null; } isObject({ prop: 'Value' }); // => true isObject(15); // => false isObject(null); // => false
3. The trap of null
null usually appears unexpectedly in situations where you expect to use an object. Then, if you try to extract a property from null
,JavaScript will throw an error
Let's use the
greetObject() function again and try to access the
message
let who = ''; greetObject(who).message; // throws "TypeError: greetObject() is null"
because the
who variable is a empty string, so the function returns
null. When accessing the message property from
null, a TypeError error will be thrown
You can pass Use the optional chaining operator to handle
null
let who = ''; greetObject(who)?.message ?? 'Hello, Stranger!'; // => 'Hello, Stranger!'or use the two alternatives described in the next section.
4. null 的替代方案
当你不能构造一个对象时,很容易返回 null
。但这种做法也有缺点
一旦 null
出现在执行堆栈中,你总是必须检查它
我们尽量避免返回 null
:
- 返回默认对象而不是
null
- 抛出错误而不是返回
null
让我们回忆一下 greetObject()
函数返回 greeting
对象
当缺少参数时,可以返回一个默认对象,而不是返回 null
function greetObject(who) { if (!who) { who = 'Stranger'; } return { message: `Hello, ${who}!` }; } greetObject('Eric'); // => { message: 'Hello, Eric!' } greetObject(); // => { message: 'Hello, Stranger!' }
或者抛出一个错误
function greetObject(who) { if (!who) { throw new Error('"who" argument is missing'); } return { message: `Hello, ${who}!` }; } greetObject('Eric'); // => { message: 'Hello, Eric!' } greetObject(); // => throws an error
这些实践可以让你完全避免处理 null
5. null vs undefined
undefined
就是未初始化的变量或对象属性的值
例如,如果在声明变量时没有赋初值,那么访问该变量的结果为 undefined
let myVariable; myVariable; // => undefined
null
和 undefined
之间的主要区别是,null
表示丢失了的对象,而 undefined
表示未初始化的状态
严格相等运算符 === 区分 null
和 undefined
null === undefined; // => false
而松散相等运算符 ==
则认为 null
和 undefined
相等
null == undefined; // => true
我使用松散相等运算符检查变量是否为 null
或 undefined
function isEmpty(value) { return value == null; } isEmpty(42); // => false isEmpty({ prop: 'Value' }); // => false isEmpty(null); // => true isEmpty(undefined); // => true
6. 总结
null
是 JavaScript
中的一个特殊值,表示丢失的对象
严格相等运算符判断变量是否为空: variable === null
。
typoef
操作符用于确定变量的类型(number, string, boolean
)。但是,typeof
在 null
情况下会引起误解: typeof null
结果为 object
null
和 undefined
在某种程度上是等价的,但null
表示一个丢失的对象,而 undefined
表示未初始化状态
尽可能避免返回 null
或将变量设置为 null
。因为这种做法会导致 null
值的扩展和需要对 null
的验证。相反,尝试使用具有默认属性的对象,或者甚至抛出错误会是更好的实践
你会使用什么方法来检查 null
?
【相关推荐:javascript视频教程、web前端】
The above is the detailed content of Comprehensive analysis of null in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools