search
HomeWeb Front-endJS TutorialWhat are the javascript arithmetic operators?

What are the javascript arithmetic operators?

Jul 16, 2021 am 11:22 AM
javascriptarithmetic operators

Javascript arithmetic operators include: addition operator " ", subtraction operator "-", multiplication operator "*", division operator "/", remainder operator "%", increment operator " ", decrement operator "--", power operator "**".

What are the javascript arithmetic operators?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Arithmetic operators are used to perform arithmetic operations on numbers (literal or variables). The standard arithmetic operators are addition , subtraction -, multiplication *, and division /. It is very similar to addition, subtraction, multiplication and division in mathematics. Let’s take a look at it together.

Addition operator

Addition operator is used to sum the values, which should be very simple.

Example:

The following is a simple sum of two numbers:

var a = 8;
var b = a + 5;
console.log(b);  // 13

In addition to calculating the sum of two numbers, we can activate the operator by Concatenate strings and the result is a new string.

Example:

Use to connect the three defined variables:

str1 = "hello";
str2 = "xkd";
str3 = " ";
console.log(str1 + str3 + str2);  // 输出: hello xkd

In addition, the numbers and A string can also be connected by plus sign, and the returned result is also a string.

Example:

Look at the difference between adding numbers and numbers, and adding numbers and strings:

num1 = 10;
num2 = 15;
str1 = "15"

console.log(num1 + num2 );  // 输出: 25
console.log(num1 + str1 );  // 输出:1015

Note that in some programming Different types in languages ​​​​(such as Python) cannot be added. For example, adding numbers to strings will result in an error. In JavaScript, numbers and strings are added and a string is returned.

Subtraction operator

Subtraction operator - can be used to subtract two operands, and the result is their difference.

Example:

var c = 8;
var d = c - 5;
console.log(d);  // 3

In the subtraction operation, if the operand is a string, try to convert it to a numerical value before performing the operation. If one of the operands is not a number, NaN is returned.

Example:

console.log(2 - "1");  //返回1
console.log(2 - "a");  //返回NaN

Quickly convert a value to a number by subtracting 0 from the value. For example, query strings in HTTP requests are generally string numbers. You can first subtract 0 from these parameter values ​​to convert them into numerical values. This has the same result as calling the parseFloat() method, but the subtraction is more efficient and faster. Implicit conversions with the subtraction operator return NaN if they fail, which is different from the return value when performing the conversion using the parseFloat() method.

For example, for the string "100aaa", the parseFloat() method can parse out the first few numbers, but for the subtraction operator, it must be a complete number before it can be converted.

console.log(parseFloat("100aaa"));  //返回100
console.log("100aaa" - 0);  //返回NaN

For Boolean values, the parseFloat() method can convert true to 1 and false to 0, while the subtraction operator treats it as NaN.

For objects, the parseFloat() method will try to call the object's toString() method for conversion, while the subtraction operator first tries to call the object's valueOf() method for conversion, and then calls toString() after failure. Make the conversion.

Pay attention to the subtraction operation of special operands.

var n = 5;  //定义并初始化任意一个数值
console.log(NaN - n);  //NaN与任意操作数相减,结果都是NaN
console.log(Infinity - n);  //Infinity与任意操作数相减,结果都是Infinity
console.log(Infinity - Infinity);  //Infinity与Infinity相减,结果是NaN
console.log((-Infinity) - (-Infinity));  //负Infinity相减,结果是NaN
console.log((-Infinity) - Infinity);  //正负Infinity相减,结果是-Infinity

Inversion operation

Pay attention to the inversion operation of special operands

console.log(- 5);  //返回-5。正常数值取负数
console.log(- "5");  //返回-5。先转换字符串数字为数值类型
console.log(- "a");  //返回NaN。无法完全匹配运算,返回NaN
console.log(- Infinity);  //返回-Infinity
console.log(- (- Infinity));  //返回Infinity
console.log(- NaN);  //返回NaN

Multiplication operator

The result of the multiplication operator* is the product of the operands.

Example:

var e = (8 + 5) * 3;
var f = 'xkd' * 3;
console.log(e);  // 输出:39
console.log(f);  // 输出:NaN

If we use a string to multiply a number, it will eventually return a NaN, which is an illegal number.

Division operator

The result of division operator/ is the quotient of the operands. The left operand is the dividend and the right operand is the divisor. .

Example:

var g = (9 - 3) / 3;
var h = 3.0 / 1.0;
var i = 1 / 2;

console.log(g);  //输出:2
console.log(h);  //输出:3
console.log(i);  //输出:0.5

What we need to pay attention to is that in JavaScript, 1 / 2 This kind of operation with a decimal point will result in Decimal point, for example 0.5. In languages ​​such as Java, numbers are not required to be clear floating-point numbers, and the return result of 1 / 2 is 0.

Remainder operator

Percent sign% is the remainder operator, returning the first operand to the second operand Modulo (remainder), for example x % y, the result is the integer remainder of x divided by y. Everyone should know that the remainder, which we have also learned in mathematics, refers to the part of the dividend that is not divided by the integer trigger.

Example:

For example, the following code:

var m = 9;
var n = 2;
var mn = m % n;
console.log(mn);  //输出: 1

The output result is 1, which is actually easy to understand, 9 % 2 Just find the remainder of 9 divided by 2, which is 1.

So if it is 12 % 5, what will the output be? Dividing 12 by 5 leaves a remainder of 2, so the result is 2. Now you should know how to use %.

Increment operator

Increment operator Increases its operand by 1 and returns a numeric value. If you use a postfix, such as x , the value will be returned before incrementing. If preceded, such as x, the value will be returned after incrementing.

Example:

假设我们定义了一个变量 i,然后使用自增运算符对 i 进行递增运算,将递增后的 i 赋值给了变量 j,最终j 的输出结果为 6:

var i = 5;
i++;
var j = i;
console.log(j);  // 6

那为什么结果会是6呢,i++ 其实就是表示在 i 的基础上加一,相当于i + 1

然后我们看一下递增运算符前置和后置,到底有什么区别,例如下面这个代码:

var a = 9;
console.log(a++);  // 输出:9

console.log(a);    // 输出:10

console.log(++a);  // 输出:11
  • 变量 a 的值为9,然后使用后置递增运算符a++,第一次输出会在递增之前就返回数值,即输出结果还是 9。
  • 然后此时输出 a 的值,可以看到 a 的值已经为10了,因为已经执行了一次递增运算符,所以加 1。
  • 接着第三次输出时,使用前置递增运算符,这会在递增之后才返回数值,即输出结果为11。

递减运算符

递减运算符 -- 为其操作数减去1,并返回一个数值。递减运算符和递增运算符的使用方法差不多,一个是减、一个是加,正好相反。

如果后置使用递减运算符,则在递减之前返回数值。如果前置使用,则在递减之后返回数值。

示例:

var b = 7;
console.log(b--);  // 输出:7

console.log(b);    // 输出:6

console.log(--b);  // 输出:5
  • 变量b的值为7,然后使用后置递减运算符b--,会在递减之钱返回数值,即7。
  • 然后第二次输出变量b,此时已经成功执行b-- ,会在此基础上减1,所以输出6。
  • 第三次输出--b,使用后置递减运算符,会在递减之后返回数值,所以会输出5。

幂运算符

幂运算符 ** 返回第一个操作数做底数,第二个操作数做指数的乘方。例如5 ** 2 表示 5 的 2 次方,根据所学数学知道就能得出结果为25。

示例:

下面这个代码表示求 6 的 3 次方,相当于 6 * 6 * 6,结果为216:

var x = 6;
var y = x ** 3;
console.log(y);  // 216

上面的运算出的结果与 Math.pow(x, y) 是相同的,例如:

var x = 6;
var y = Math.pow(x,3);
console.log(y);  // 216

pow()方法可返回 x 的 y 次幂的值。

【推荐学习:javascript高级教程

The above is the detailed content of What are the javascript arithmetic operators?. 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 Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

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.

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

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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.