search
HomeWeb Front-endFront-end Q&AWhat are the basic data types of javascript?

Javascript has 5 basic data types, namely: 1. Undefined type; 2. Null type; 3. Boolean type; 4. Number type; 5. String type.

What are the basic data types of javascript?

The operating environment of this article: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.

What are the basic data types of js? There are 5 simple data types (also called basic data types) in

ECMAScript: Undefined, Null, Boolean, Number and String. There is also 1 complex data type——Object, Object is essentially composed of a set of unordered name-value pairs.

Among them, Undefined, Null, Boolean, and Number all belong to basic types. Object, Array and Function are reference types. String is somewhat special and will be analyzed below.

Variables

ECMAScript uses the var keyword to define variables, because js is weakly typed, so it cannot Determine what value the variable will store, so you don't know what type the variable will be, and the type of the variable can change at any time.

This is why ECMAScript is a loose type. The so-called loose type can be used to save any type of data.

ps:
es6 has added the let command to declare variables, const The command declares a read-only constant. The usage of

let is similar to var, but the variables declared are only in the code where the let command is located Valid within the block.

#constOnce declared, the value of a constant cannot be changed.

About let, const will not be discussed here.

typeof operator

Since the variables in js are loosely typed, it provides a way to detect the data type of the current variable, and also It is the typeof keyword.
Through the typeof keyword, the following values ​​will be returned for the five data types (displayed in string form)
undefined --- ------- If the value is undefined                   Undefined

boolean                                                       ’ ’ ’ ’ ’ s ’ ’ s ‐ to Boolean ‐ ‐‐ ‐‐‐‐‐‐ ‐ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​Boolean

string ---------- If the value is a string String

##number

---------- If this value is a numeric type Number##object

------------ If This value is an object or

null ObjectIt should be noted that typeof null

is returned as

object because of the special value null is considered a null object reference. The Undefined

Undefined

type has only one value, the special

undefined. When a variable is declared using var but is not initialized, the value of the variable is undefined. However, it is generally recommended to initialize variables as much as possible, but in early js versions, the value undefined was not specified, so in some frameworks, in order to be compatible with older browsers, windowObject adds undefined value. The

window['undefined'] = window['undefined'];  
//或者
window.undefined = window.undefined;
Null

Null

type is the second data type with only one value. This special value is

null. From a logical point of view, the null value represents a null object pointer, which is why using the typeof operator to detect null will return object s reason.

  var car = null;
  console.log(typeof car); // "object"
If the defined variable is going to be used to hold objects in the future, it is best to initialize the variable to null rather than to another value. In this way, as long as the

null value is directly detected, you can know whether the corresponding variable has saved a reference to an object. For example: <pre class="brush:php;toolbar:false">  if(car != null){     //对car对象执行某些操作   }</pre>In fact, the undefined value is derived from the null value, so ECMA-262 stipulates that their equality test should return true.

console.log(undefined == null); //true
Although null and undefined have this relationship, their uses are completely different. Under no circumstances is it necessary to explicitly set the value of a variable to undefined, but the same rule does not apply to null. In other words, as long as a variable that is intended to hold an object does not actually hold an object, you should explicitly let the variable hold a null value. Doing so not only reflects the convention of null as a null object pointer, but also helps to further distinguish null and undefined.

Boolean

该类型只有两个字面值:true和false。这两个值与数字值不是一回事,因此true不一定等于1,而false也不一定等于0。

虽然Boolean类型的字面值只有两个,但JavaScript中所有类型的值都有与这两个Boolean值等价的值。要将一个值转换为其对应的Boolean值,可以调用类型转换函数Boolean(),例如:

    var message = 'Hello World';
    var messageAsBoolean = Boolean(message);

在这个例子中,字符串message被转换成了一个Boolean值,该值被保存在messageAsBoolean变量中。可以对任何数据类型的值调用Boolean()函数,而且总会返回一个Boolean值。至于返回的这个值是true还是false,取决于要转换值的数据类型及其实际值。下表给出了各种数据类型及其对象的转换规则。

数据类型 转换为true的值 转换为false的值
Boolean true false
String 任何非空的字符串 ""(空字符串)
Number 任何非0数值(包括无穷大) 0和NAN
Object 任何对象 null
Undefined 不适用 undefined
    var message = 'Hello World';
    if(message)
    {
        alert("Value is true");
    }

运行这个示例,就会显示一个警告框,因为字符串message被自动转换成了对应的Boolean值(true)。由于存在这种自动执行的Boolean转换,因此确切地知道在流控制语句中使用的是什么变量至关重要。

ps:使用!!操作符转换布尔值
!!一般用来将后面的表达式强制转换为布尔类型的数据(boolean),也就是只能是true或者false;

对null与undefined等其他用隐式转换的值,用!操作符时都会产生true的结果,所以用两个感叹号的作用就在于将这些值转换为“等价”的布尔值;

var foo;  
alert(!foo);//undifined情况下,一个感叹号返回的是true;  
alert(!goo);//null情况下,一个感叹号返回的也是true;  
var o={flag:true};  
var test=!!o.flag;//等效于var test=o.flag||false;  
alert(test);

这段例子,演示了在undifined和null时,用一个感叹号返回的都是true,用两个感叹号返回的就是false,所以两个感叹号的作用就在于,如果明确设置了变量的值(非null/undifined/0/”“等值),结果就会根据变量的实际值来返回,如果没有设置,结果就会返回false。

【推荐学习:javascript基础教程

Number

这种类型用来表示整数和浮点数值,还有一种特殊的数值,即NaN(非数值 Not a Number)。这个数值用于表示一个本来要返回数值的操作数未返回数值的情况(这样就不会抛出错误了)。例如,在其他编程语言中,任何数值除以0都会导致错误,从而停止代码执行。但在JavaScript中,任何数值除以0会返回NaN,因此不会影响其他代码的执行。

NaN本身有两个非同寻常的特点。首先,任何涉及NaN的操作(例如NaN/10)都会返回NaN,这个特点在多步计算中有可能导致问题。其次,NaN与任何值都不相等,包括NaN本身。例如,下面的代码会返回false。

alert(NaN == NaN);    //false

String

String类型用于表示由零或多个16位Unicode字符组成的字符序列,即字符串。字符串可以由单引号(')或双引号(")表示。

String类型的特殊性

string类型有些特殊,因为字符串具有可变的大小,所以显然它不能被直接存储在具有固定大小的变量中。由于效率的原因,我们希望JS只复制对字符串的引用,而不是字符串的内容。但是另一方面,字符串在许多方面都和基本类型的表现相似,而字符串是不可变的这一事实(即没法改变一个字符串值的内容),因此可以将字符串看成行为与基本类型相似的不可变引用类型

Boolean、Number、String 这三个是Javascript中的基本包装类型,也就是这三个其实是一个构造函数,他们是Function的实例,是引用类型,至于这里的String与以上说的String是同名,是因为其实上文说的String是指字符串,这里的String指的是String这个构造函数,上面那么写,是为了更好的理解,因为Javascript是松散类型的。我们可以看下String实例化的例子:

var name = String("jwy");
alert(typeof name);//"string"
var x=new String('12345')
typeof x //object
x='12345'
typeof x //string
var author = "Tom";
alert(typeof name);//"string"

至于author这个会有length,substring等等这些方法,其实string只是String的一个实例,类似于C#中的String,和string.

注意,typeof 变量  如果值是"string" 的话,也就是这个变量是字符串,在Javascript中,字符串是基本类型,而在C#或Java中,字符串是引用类型,但是Javascript中的String是引用类型,因为它是Javascript中定义好的基本包装类型,在C#中,String跟string其实是一样的。

本帖只是简要的copy了一些JavaScript高级程序设计(第三版)内容,外加了自己侧重的角度,看本帖的朋友还是要看书啊,这里只是做个参考。

The above is the detailed content of What are the basic data types of javascript?. 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
Frontend Development with React: Advantages and TechniquesFrontend Development with React: Advantages and TechniquesApr 17, 2025 am 12:25 AM

The advantages of React are its flexibility and efficiency, which are reflected in: 1) Component-based design improves code reusability; 2) Virtual DOM technology optimizes performance, especially when handling large amounts of data updates; 3) The rich ecosystem provides a large number of third-party libraries and tools. By understanding how React works and uses examples, you can master its core concepts and best practices to build an efficient, maintainable user interface.

React vs. Other Frameworks: Comparing and Contrasting OptionsReact vs. Other Frameworks: Comparing and Contrasting OptionsApr 17, 2025 am 12:23 AM

React is a JavaScript library for building user interfaces, suitable for large and complex applications. 1. The core of React is componentization and virtual DOM, which improves UI rendering performance. 2. Compared with Vue, React is more flexible but has a steep learning curve, which is suitable for large projects. 3. Compared with Angular, React is lighter, dependent on the community ecology, and suitable for projects that require flexibility.

Demystifying React in HTML: How It All WorksDemystifying React in HTML: How It All WorksApr 17, 2025 am 12:21 AM

React operates in HTML via virtual DOM. 1) React uses JSX syntax to write HTML-like structures. 2) Virtual DOM management UI update, efficient rendering through Diffing algorithm. 3) Use ReactDOM.render() to render the component to the real DOM. 4) Optimization and best practices include using React.memo and component splitting to improve performance and maintainability.

React in Action: Examples of Real-World ApplicationsReact in Action: Examples of Real-World ApplicationsApr 17, 2025 am 12:20 AM

React is widely used in e-commerce, social media and data visualization. 1) E-commerce platforms use React to build shopping cart components, use useState to manage state, onClick to process events, and map function to render lists. 2) Social media applications interact with the API through useEffect to display dynamic content. 3) Data visualization uses react-chartjs-2 library to render charts, and component design is easy to embed applications.

Frontend Architecture with React: Best PracticesFrontend Architecture with React: Best PracticesApr 17, 2025 am 12:10 AM

Best practices for React front-end architecture include: 1. Component design and reuse: design a single responsibility, easy to understand and test components to achieve high reuse. 2. State management: Use useState, useReducer, ContextAPI or Redux/MobX to manage state to avoid excessive complexity. 3. Performance optimization: Optimize performance through React.memo, useCallback, useMemo and other methods to find the balance point. 4. Code organization and modularity: Organize code according to functional modules to improve manageability and maintainability. 5. Testing and Quality Assurance: Testing with Jest and ReactTestingLibrary to ensure the quality and reliability of the code

React Inside HTML: Integrating JavaScript for Dynamic Web PagesReact Inside HTML: Integrating JavaScript for Dynamic Web PagesApr 16, 2025 am 12:06 AM

To integrate React into HTML, follow these steps: 1. Introduce React and ReactDOM in HTML files. 2. Define a React component. 3. Render the component into HTML elements using ReactDOM. Through these steps, static HTML pages can be transformed into dynamic, interactive experiences.

The Benefits of React: Performance, Reusability, and MoreThe Benefits of React: Performance, Reusability, and MoreApr 15, 2025 am 12:05 AM

React’s popularity includes its performance optimization, component reuse and a rich ecosystem. 1. Performance optimization achieves efficient updates through virtual DOM and diffing mechanisms. 2. Component Reuse Reduces duplicate code by reusable components. 3. Rich ecosystem and one-way data flow enhance the development experience.

React: Creating Dynamic and Interactive User InterfacesReact: Creating Dynamic and Interactive User InterfacesApr 14, 2025 am 12:08 AM

React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function