search
HomeWeb Front-endJS TutorialA brief overview of five unknown ways to declare Number in JS_javascript skills

I was chatting with a cute 90-year-old young man in the group who called himself Xiao Fangfang. I talked about the bad habits of IT men and got involved in technology. Xiao Fangfang suddenly asked
1. Declare a variable of numerical type. I saw Three types, what are the differences:

Copy code The code is as follows:

var num = 123; //Method 1
var num = Number(123);
var num = new Number(123);

2. Method 1 is obviously a numerical literal, which is normal for us Various methods can be called directly on it, as follows:
Copy code The code is as follows:

var num = 123;
console.log(num.toString());

I smiled slightly: Young man, you are still a bit young. There are not only three kinds, but I know at least five. kind! !
Smiling and smiling, the corners of his mouth began to twitch, and cold sweat began to break out on his forehead: There are at least five kinds, yes, but. . . What's the difference. . .
With the unique reserve and pride of an old rookie, I said disdainfully: I don’t know this, just look up the information myself. . . Turn around and start flipping through ECMAS - 262 (fifth edition)

1. Five ways to declare numeric type variables
Copy code The code is as follows:

//Method 1: The most common way, declare through numeric literals
var num = 123;
//Method 2: Occasionally used, in most cases to convert strings into numbers
var num = Number(123);
//Method 3: Rarely used, various sacred books, including Rhinoceros Books have listed it as a non-recommended method
var num = new Number(123);
//Method 4: God’s method, I haven’t seen anyone use it yet
var num = new Object(123) );
//Method 5: More bizarre and weird
var num = Object(123);

As you can see, among the above five declaration methods, method one needless to say, it is usually used like this; method three to method five are used for comparison, which will be explained separately below:
1.5 What is the difference between the two declaration methods? What happened when you typed the code with your trembling fingers?
2. What is declared in method 1 is obviously not an object, but why can we usually call methods on it, such as toString, etc.?

2. The difference between various declaration methods
Method 1: var num = 123
;
EC5 description:
A numeric literal stands for a value of the Number type. This value is determined in two steps: first, a mathematical value (MV) is derived from the literal; second, this mathematical value is rounded as described below
//....Personal summary summary:
1. Parse the value of the variable, such as taking out the integer part, decimal part, etc., because the number declaration method can also be in the form of num = .123, num = 123e4, etc.
2. Approximate the parsed value, For example, num = 123.33333333333333...33333333333333333333333333.... At this time, it is necessary to take the approximate value. If the specific approximation is taken, the rules will not be expanded
3. The variable declared in this way is just a simple numerical literal, not Object (as to why toString and other methods can be called on it, we will explain it later)
Method 2: var num = Number(123);
EC5 description:
15.7.1 The Number Constructor Called as a Function
When Number is called as a function rather than as a constructor, it performs a type conversion. 15.7.1.1 Number ( [ value ] )
Returns a Number value (not a Number object) computed by ToNumber(value) if value was supplied, else returns 0. Personal summary summary:
1. Here Number is just called as an ordinary function, not a constructor, so what is returned is not an object, but A simple value
2. The essence is the same as method 1; the difference from method 1 is that different type conversion processes need to be performed based on the type of the incoming parameter to try to parse the parameter into the corresponding value. The specific rules are as follows :

Method 3: var num = new Number(123);
EC5 description:
15.7.2 The Number Constructor
When Number is called as part of a new expression it is a constructor: it initialises the newly created object. 15.7.2.1 new Number ( [ value ] )
The [[Prototype]] internal property of the newly constructed object is set to the original Number prototype object, the one that is the initial value of Number.prototype (15.7.3.1).
The [[Class]] internal property of the newly constructed object is set to "Number".
The [[PrimitiveValue ]] internal property of the newly constructed object is set to ToNumber(value) if value was
supplied, else to 0.
The [[Extensible]] internal property of the newly constructed object is set to true.personal Summary summary:
1. The Number function constructor is called here, and an object of type Number is returned. This object can access the prototype properties and methods of Number; this may be a bit confusing, and I will talk about it later
Copy code The code is as follows:

var num = new Number(123);
console.log( typeof num); //Output: object
console.log(Object.prototype.toString.call(num)); //Output: [object Number]

3. The original value ([[PrimitiveValue]]) inside the returned Number type object is the numerical value obtained after type conversion. The specific conversion rules are consistent with those mentioned in method 2

Method 4: var num = new Object(123);
EC5 description:
15.2.2 The Object Constructor
When Object is called as part of a new expression, it is a constructor that may create an object.
15.2.2.1 new Object ( [ value ] )
When the Object constructor is called with no arguments or with one argument value, the following steps are taken:
1.If value is supplied, then
a. If Type(value) is Object, then
1.If the value is a native ECMAScript object, do not create a new object but simply return value.
2.If the value is a host object, then actions are taken and a result is returned in an implementation-dependent manner that may depend on the host object.
b. If Type(value) is String, return ToObject(value).
c. If Type(value) is Boolean, return ToObject(value).
d. If Type(value) is Number, return ToObject(value).
2.Assert: The argument value was not supplied or its type was Null or Undefined.
3.Let obj be a newly created native ECMAScript object.
4.Set the [[Prototype]] internal property of obj to the standard built-in Object prototype object (15.2.4 ).
5.Set the [[Class]] internal property of obj to "Object".
6.Set the [[Extensible]] internal property of obj to true.
7.Set all the internal methods of obj as specified in 8.12.
8.Return obj.
Personal understanding :
There is a lot of text posted above, which may give you a headache, because through new Object(param) declares variables in this way. The results obtained will be different depending on the specific type of the parameters passed in, such as the data type. The specific conversion rules here can be ignored. We only look at the part of our current relationship, that is, the text marked in red above. The key points are:
1. If a parameter is passed, and the parameter is a number, create and return a Number type object - yes, it is actually equivalent to method three
2. The value of the Number object is equal to the passed parameter, and the internal [[prototype]] attribute points to Number.prototype
Method five: var num = Object(123);
EC5 description:
15.2.1 The Object Constructor Called as a Function
When Object is called as a function rather than as a constructor, it performs a type conversion.
15.2.1.1 Object ( [ value ] )
When the Object function is called with no arguments or with one argument value, the following steps are taken:
1.If value is null, undefined or not supplied, create and return a new Object object exactly as if the standard built-in Object constructor had been called with the same arguments (15.2.2.1).
2.Return ToObject(value).
Personal understanding :
1. When the parameter passed in is empty, undefined or null, it is equivalent to new Object (param), param is the parameter passed in by the user
2. Otherwise, an object is returned. As for the specific conversion into The object type can be seen in the table below; specifically for the above example, it is essentially equivalent to new Number(123):

3. Simple test case
Copy code The code is as follows:

var num = Object(123);
console.log(typeof num); //Output: object console.log(Object.prototype.toString.call(num)); //Output: [object Number]

3. var num = 123; and var num = new Number( 123);
The sages and sages have warned us that it is best to use the first method. The reason is very convincing: it is inefficient and unexpected situations may occur when eval(num) is used. . . Balabala
Putting aside the noise above, what we want to focus on here is why the following statement will not go wrong:
Copy code The code is as follows:

var num = 123;
console.log(num.toString(num)); //Output: '123', no error occurred

Didn’t it mean that the literal declaration is just an ordinary numerical type, not an object? But the toString method call does not come from the object. This is unscientific!
Okay, I checked the Rhinoceros book and found the answer:
When the user declares a variable through literals and calls methods such as toString on the variable, the JS script engine will Secretly create a packaging object corresponding to the variable, and call the corresponding method on the object; when the call is completed, the object is destroyed; this process is invisible to the user, so many beginners will have this problem Puzzled.

Okay, I admit that the above paragraph is not the original text, it is just my personal understanding of the corresponding paragraph in the Rhinoceros book, and I deliberately added a quotation mark in order to appear more professional and authoritative. . . The example given above can be simply viewed as the following process:
Copy code The code is as follows:

var num = 123;
var tmp = num;
num = new Number(num);
console.log(num.toString(num));
num = tmp;

(Because I was flipping through the standard last night until almost 1 o'clock, I was really sleepy, so I was lazy. I believe Rhino Book will not trick me)

4. Write it at the back
I have always felt unable to complain about Javascript’s variable declaration method, type judgment, etc. The above content is tantamount to ruining the outlook for beginners; even for someone like me who has been working with Javascript for two years Many veteran rookies are often confused
A brief summary:
1. Method one and method two are essentially the same
2. Method three, method four and method five are essentially the same
The last Finally:
If there are any errors or omissions in the examples in the article, please point them out; if you think the article is useful to you, you can click "Recommend" :)
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

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.

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools