search
HomeWeb Front-endJS TutorialJavaScript: data types

JavaScript: data types

Nov 26, 2016 pm 02:25 PM
JavaScript

I like JavaScript. It is a language that is both powerful and flexible. Of course, you have to know how to use it correctly. Once you really master JavaScript, you can use it to do almost anything, and you can Do it quickly and well.
If you think JavaScript is too simple or too low-level, then you have fallen into a trap. And you will find that many people have fallen into such a trap. These so-called JavaScript developers Maybe tell you that some other language "X" is better.
They might even say that it would be great if there was a system that would be able to convert language Mastering JavaScript requires a lot of effort and dedication. Trust me, because I have been learning JavaScript since 1997.
I have mastered all the advanced knowledge of JavaScript by studying the official standard documents, so you can also learn it through this A way to gain complete knowledge of the language. If your job title includes "JavaScript Developer", this is what you should do.

In this blog, I will give a short JavaScript code snippet, and then let you give the correct output of this code. If you are a JavaScript developer, you will find that this kind of question is really simple. If you are still in the process of learning the language, you may encounter some difficulties, but you can take a good look at the explanation section below the code.
The following JavaScript code displays a popup box. What does the popup box show?

var five = 5;
five.three = 3;
alert(five + five.three);
Skip to the end of this article to see the correct answer. Next is the explanation of why there is such a result.
In JavaScript, there are six data types: Object, Number, String, Boolean, Null, and Undefined. The Objects type includes arrays, functions, and other general objects. Numbers ( The Numbers type can be integers or floating point types as well as the special values ​​NaN and Infinity. The Strings type contains the empty string, "". The Booleans type has only two values :true and false. The last two basic data types are a bit special: the Null type has only one value: null, and the Undefined type has only one value: undefined. All types except Object are called "primitive values ​​(primitive)". JavaScript variables The type is not specified explicitly when it is defined, but is automatically inferred when the script is run. In the above code, the variable named five is of type Number because it is assigned a Number literal 5.
and Similar to other computer programming languages, JavaScript will also implicitly convert the type of a value into the type of the operator suitable for operating on the value. Unlike other languages, JavaScript will do these conversions very actively. For example The operation result of the expression "5" - "3" is the number 2, because the minus operator will convert all the operands on both sides into numbers before performing the operation. If an operand cannot be converted into a number, NaN ( "Not a Number"). For example, the expression "5" - "Fred" will be implicitly converted to 5 - NaN, and the result of the operation will also be NaN.
A complete set of implicit conversion rules is not very Complex, you only need to know what type of operand each operator requires.
Converting any value to a primitive value follows the rule "convert any value to a primitive value". The conversion of an object to a primitive value is more complicated: if the operand The type must be Number type, which means that the JavaScript engine will call the object's valueOf() method. If the returned result is still not a primitive value, it will call the object's toString() method to convert it to a String type value. If The type of the operand must be String type, then the object's toString() method will be called first. If the returned result is not a primitive value, then the object's valueOf() method will be called. Regardless of that situation, if the final conversion result is still not A primitive value, an exception is thrown.

If the type of the operand must be a number, but the actual type of the operand is:
Object:
The value is first converted to a primitive value, if the result of the conversion is not a number , it will enter the following conversion branch.

String:
The string type value will be converted into a numeric type according to the usual JavaScript rules

Boolean:
If the value is true, it is converted to 1, otherwise it is converted to 0

Null :
0

Undefined:
NaN

If the type of the operand must be a string, but the actual type of the operand is:

Object:
The value is first converted to the original value, if the result of the conversion is not A string, it will enter the following conversion branch.

Number:
Numbers are directly converted to strings, such as “123″ or “12.34″

Boolean:
converted to “true” or “false”

Null:
“null”

Undefined:
“undefined”

If the type of the operand must be a Boolean value, but the actual type of the operand is:

Object:
true

Number:
If the value is 0, If the value is an empty string "", it will be converted to false, otherwise it will be converted to true

Null:
false

Undefined:
false

If the type of the operand must be an object value, but the actual type of the operand is:

Number:
Use the wrapping object type Number to wrap the original value, new Number(value)

String:
Use the wrapping object type String to wrap the original value, new String(value)

Boolean:
Use the wrapping object type Boolean to wrap the original value, new Boolean(value)

Null:
Throw an exception

Undefined :
Throw an exception

Now that all the conversion rules are clear, let’s go back to the original example.

var five = 5;
five.three = 3;
alert(five + five.three);
As we mentioned earlier, the first line of code creates a variable named five, of type Number.
When a property accessor is used on the variable five, its value is converted to type Object. This operation is called "wrapping" and relies on the Number constructor, which produces an object rather than a primitive value. The second line of code is actually equivalent to the following code:

(new Number(five)).three=3;
As you can see, we are not saving a reference to the newly generated Number object into a variable . After the expression runs, the object with the three attribute added will be discarded. The value of the five variable will not change.
The expression five.three in the third line of code will create a Number object again. This The new object does not have three attributes, so the special value undefined is returned. The result is equivalent to:

alert(5+undefined); The addition operator will convert all operands on both sides into numbers. In this case, undefined will is converted to NaN, it becomes:

alert(5+NaN);
This also explains why the final pop-up box only displays one NaN.
(Translator's Note: There is still the last step of implicit conversion , NaN will be automatically converted to "NaN" when alert() is performed)


Comments:

jerone:
The content of your article is only part of JavaScript, to be precise, it only includes ECMAScript. In addition to these, JavaScript also contains DOM, which means there are more data types such as Node, Element, HTMLElement, etc.
Author's reply:
Node, Element and HTMLElement are not data types, just like Array, Date and RegExp. They all belong to the object type.

Marcus Pope:
I think we should point out the correct way of writing so that the following code can run normally

var five = new Number(5);
alert(five); // 5
five.three = 3;
alert(five + five.three); //8
I also think it is better to use "number" to refer to the original value of the number, and "Number" to refer to the numeric type Wrap objects to reduce confusion for readers. This is also the string displayed when using the typeof operator in JavaScript to view the inner class properties of these values. (Translator's Note: This refers to typeof 5 === "number" )
ACRESTAN:
Yeah, this article is very confusing because the author uses type strings starting with capital letters to describe primitive values...
For example, this sentence "the first line creates a variable called five whose type is Number ", this is wrong! Because your code proves it.

metadings:
There is also a seventh data type, the most important type in JavaScript: Function. In JavaScript, using functions can create New object, so there is still a difference between primitive value type and function type.

var Project = function () { };
// Project instanceof Function === true
// Project instanceof Object === true
// (typeof Project === 'function') === true

var o = new Project();
// o instanceof Project === true
// o instanceof Object === true
// (typeof Project === 'object') === true
Please read this link http://metadea.de/V/ carefully to see how I write a real JavaScript class function. (Translator's Note: There is another sentence There is no translation, I can’t understand it, I think this person is talking nonsense.)
Author’s reply:
Obviously functions are very important in JavaScript, and it’s worth using a separate article to explain them, but functions are not another data type. Functions are just A special kind of object. Although special, it is still an object.
Objects created by many different constructors all inherit the same type: Object. This is easy to detect: if Object(a) === a, then a is an object type, not other primitive value types.

ulu:
This article just further proves that JavaScript is not only the most powerful language, but also the most confusing language. It should be done at all costs Avoid using it at all costs. One day, there will be a more user-friendly language integrated into all major browsers, and I hope to catch up in my lifetime.
Author reply:
When you have a hammer in your hand, Everything looks like a nail. When you think JavaScript is confusing, any feature will prove it.

Dave Chapman:
This type of coding error is exactly why we need a better tool that can This is because of the IDE that performs syntax checks before running the code while we are coding. For example, running the code in the example in the closure compiler will generate the following warning message:
"JSC_INEXISTENT_PROPERTY: Property three never defined on Number at line 4 character 13:
alert(five + five.three);”
(Translator’s Note: closure compiler is Google’s code compressor or compiler. https://developers.google.com/closure/compiler/)


simonleung:
A number can be of type "object" or "number".
When used in conditional statements or other places that need to be converted to Boolean values, these two types of numbers will produce different results. , for example.
Number(0) will get true, because Number(0) is an object, and 0 will obviously get false.
(Translator’s Note: He said it wrong here. Number as a function is just a type conversion function, returning is still the original value. Only when new Number(0) is used, Number is considered a constructor and what is returned is the object)
Another one, perform typeof operation on null, return "object", but it is not a real object, null is a false value and will be converted to false.


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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

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 vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

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.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

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 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.

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment