search
HomeWeb Front-endJS TutorialBasic types and reference types in js

Basic types and reference types in js

Apr 10, 2018 pm 02:10 PM
javascriptQuotetype

The content shared with you in this article is about the basic types and reference types in js. It has certain reference value. Friends in need can refer to it


Basic types and reference types in js


Reprinted from https://blog.csdn.net/shuidinaozhongyan/article/details/72520842
Basic type: Number, String,Boolean,Null,undefined.

Reference types: Object, Array, Date, RegExp, Function

The difference between null and undefined.

Reference: http://www.ruanyifeng.com/blog/2014/03/undefined-vs-null.html

1. Similarity

1. In JavaScript, assigning a variable to undefined or null, to be honest, there is almost no difference.

var a=null;  
var b=undefined;

2. Undefined and null will be automatically converted to false in the if statement, and the equality operator will even directly report that they are equal.

if (!undefined) 
    console.log('undefined is false');// undefined is falseif (!null) 
    console.log(&#39;null is false&#39;);// null is falseundefined == null// true<span style="font-family:Georgia, serif;color:#111111;"><span style="font-size:16px;letter-spacing:-.12px;word-spacing:2.4px;background-color:rgb(245,245,213);"><strong>
</strong></span></span>

The above code illustrates how similar the behaviors of the two are!

Since the meanings and usage of undefined and null are similar, why do we need to set two such values ​​at the same time? Doesn't this increase the complexity of JavaScript for no reason and trouble beginners? The Dart language, a replacement for the JavaScript language developed by Google, clearly stipulates that there is only null and no undefined!

2.

Recently, when I was reading the new book "Speaking JavaScript", I accidentally discovered the answer to this question!

It turns out that this is related to the history of JavaScript. When JavaScript was born in 1995, initially like Java, only null was set as the value representing "nothing".

According to the tradition of C language, null is designed to be automatically converted to 0.

Number(null)// 05 + null// 5

However, JavaScript designer Brendan Eich feels that this is not enough, for two reasons.

First of all, null is treated as an object just like in Java. However, JavaScript data types are divided into two categories: primitive types (primitive) and composite types (complex). Brendan Eich feels that the value representing "none" is best not an object.

Secondly, the initial version of JavaScript did not include an error handling mechanism. When a data type mismatch occurs, the type is often automatically converted or fails silently. Brendan Eich feels that if null is automatically converted to 0, it will be difficult to find errors.

Therefore, Brendan Eich designed another undefined.

3. Initial design
The initial version of JavaScript is distinguished as follows: null is an object that represents "none" and is 0 when converted to a numerical value; undefined is a representation of " The original value of "None" is NaN when converted to a numerical value.

Number(undefined)// NaN5 + undefined// NaN

4. Current usage
However, the above distinction quickly proved to be unfeasible in practice. Currently, null and undefined are basically synonymous, with only some subtle differences.

null means "no object", that is, there should be no value there. Typical usage is:

(1) As a parameter of a function, it means that the parameter of the function is not an object.

(2) As the end point of the object prototype chain.

Object.getPrototypeOf(Object.prototype)
// null

undefined means "missing value", that is, there should be a value here, but it has not been defined yet. Typical usage is:

(1) When the variable is declared but not assigned a value, it is equal to undefined.

(2) When calling the function, the parameter that should be provided is not provided, and the parameter is equal to undefined.

(3) The object has no assigned attribute, and the value of this attribute is undefined.

(4) When the function does not return a value, it returns undefined by default.

var i;
i // undefinedfunction f(x){console.log(x)}
f() // undefinedvar  o = new Object();
o.p // undefinedvar x = f();
x // undefined

Is Object a reference type?

 Object是一个基础类型,其他所有类型都从Object继承了基本行为。比如原型链中它的原型为null。

What is the difference between reference types and basic types? Which one is on the heap and which one is on the stack?

1. Basic type variables are stored in the stack area (the stack area refers to the stack memory in the memory)

Then its storage structure is as follows:

Basic types and reference types in js

The stack area includes variable identifiers and variable values.

2.

Javascript is different from other languages. It does not allow direct access to the location in the memory, which means that the memory space of the object cannot be directly manipulated. Then we operate What? In fact, it is a reference to the operating object,
so the value of the reference type is accessed by reference.
To be precise, the storage of reference types requires the stack area and the heap area of ​​the memory (the heap area refers to the heap memory in the memory). The stack area memory stores the variable identifier and the pointer to the object in the heap memory.
It can also be said to be the address of the object in the heap memory.
If there are the following objects:

var person1 = {name:&#39;jozo&#39;};var person2 = {name:&#39;xiaom&#39;};var person3 = {name:&#39;xiaoq&#39;};

The situation of these three objects saved in memory is as follows:

Basic types and reference types in js

in js Basic types and reference types

Reprinted from https://blog.csdn.net/shuidinaozhongyan/article/details/72520842
Basic types: Number, String, Boolean, Null, undefined.

Reference types: Object, Array, Date, RegExp, Function

The difference between null and undefined.

Reference: http://www.ruanyifeng.com/blog/2014/03/undefined-vs-null.html

1. Similarity

1.在JavaScript中,将一个变量赋值为undefined或null,老实说,几乎没区别。

var a=null;  
var b=undefined;

2.undefined和null在if语句中,都会被自动转为false,相等运算符甚至直接报告两者相等。

if (!undefined) 
    console.log(&#39;undefined is false&#39;);// undefined is falseif (!null) 
    console.log(&#39;null is false&#39;);// null is falseundefined == null// true<span style="font-family:Georgia, serif;color:#111111;"><span style="font-size:16px;letter-spacing:-.12px;word-spacing:2.4px;background-color:rgb(245,245,213);"><strong>
</strong></span></span>

上面代码说明,两者的行为是何等相似!

既然undefined和null的含义与用法都差不多,为什么要同时设置两个这样的值,这不是无端增加JavaScript的复杂度,令初学者困扰吗?Google公司开发的JavaScript语言的替代品Dart语言,就明确规定只有null,没有undefined!

二、

最近,我在读新书《Speaking JavaScript》时,意外发现了这个问题的答案!

原来,这与JavaScript的历史有关。1995年JavaScript诞生时,最初像Java一样,只设置了null作为表示”无”的值。

根据C语言的传统,null被设计成可以自动转为0。

Number(null)// 05 + null// 5

但是,JavaScript的设计者Brendan Eich,觉得这样做还不够,有两个原因。

首先,null像在Java里一样,被当成一个对象。但是,JavaScript的数据类型分成原始类型(primitive)和合成类型(complex)两大类,Brendan Eich觉得表示”无”的值最好不是对象。

其次,JavaScript的最初版本没有包括错误处理机制,发生数据类型不匹配时,往往是自动转换类型或者默默地失败。Brendan Eich觉得,如果null自动转为0,很不容易发现错误。

因此,Brendan Eich又设计了一个undefined。

三、最初设计
JavaScript的最初版本是这样区分的:null是一个表示”无”的对象,转为数值时为0;undefined是一个表示”无”的原始值,转为数值时为NaN。

Number(undefined)// NaN5 + undefined// NaN

四、目前的用法
但是,上面这样的区分,在实践中很快就被证明不可行。目前,null和undefined基本是同义的,只有一些细微的差别。

null表示”没有对象”,即该处不应该有值。典型用法是:

(1) 作为函数的参数,表示该函数的参数不是对象。

(2) 作为对象原型链的终点。

Object.getPrototypeOf(Object.prototype)
// null

undefined表示”缺少值”,就是此处应该有一个值,但是还没有定义。典型用法是:

(1)变量被声明了,但没有赋值时,就等于undefined。

(2) 调用函数时,应该提供的参数没有提供,该参数等于undefined。

(3)对象没有赋值的属性,该属性的值为undefined。

(4)函数没有返回值时,默认返回undefined。

var i;
i // undefinedfunction f(x){console.log(x)}
f() // undefinedvar  o = new Object();
o.p // undefinedvar x = f();
x // undefined

Object是引用类型嘛?

 Object是一个基础类型,其他所有类型都从Object继承了基本行为。比如原型链中它的原型为null。

引用类型和基本类型有什么区别?哪个是存在堆哪一个是存在栈上面的?

1.基本类型的变量是存放在栈区的(栈区指内存里的栈内存)

那么它的存储结构如下图:

Basic types and reference types in js

栈区包括了 变量的标识符和变量的值。

2.

javascript和其他语言不同,其不允许直接访问内存中的位置,也就是说不能直接操作对象的内存空间,那我们操作啥呢? 实际上,是操作对象的引用,
所以引用类型的值是按引用访问的。
准确地说,引用类型的存储需要内存的栈区和堆区(堆区是指内存里的堆内存)共同完成,栈区内存保存变量标识符和指向堆内存中该对象的指针,
也可以说是该对象在堆内存的地址。
假如有以下几个对象:

var person1 = {name:&#39;jozo&#39;};var person2 = {name:&#39;xiaom&#39;};var person3 = {name:&#39;xiaoq&#39;};

则这三个对象的在内存中保存的情况如下图:

Basic types and reference types in js

相关推荐:

JS引用类型的介绍

The above is the detailed content of Basic types and reference types in js. 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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

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.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

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 the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

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 vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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 vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment