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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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 Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),