Computer Science
Javascript Arithmetic Operators
Javascript Arithmetic Operators are symbols used to perform mathematical operations on numerical values. These operators include addition (+), subtraction (-), multiplication (*), division (/), modulus (%), increment (++), and decrement (--). They are commonly used in programming to manipulate and calculate numerical data.
Written by Perlego with AI-assistance
Related key terms
1 of 5
10 Key excerpts on "Javascript Arithmetic Operators"
- eBook - ePub
Clean Code in JavaScript
Develop reliable, maintainable, and robust JavaScript
- James Padolsey(Author)
- 2020(Publication Date)
- Packt Publishing(Publisher)
Knowing every single operator's precedence and associativity is not necessarily vital, but knowing how these mechanisms underly every operation is very useful. Most of the time, as you've seen, it's preferable to split operations into self-contained lines or groups for clarity, even when the internal precedence or associativity of our operators does not demand it. Above all, we must always consider whether we are clearly communicating our intent to the readers of our code.The average JavaScript programmer will not have an encyclopedic knowledge of the ECMAScript specification, and as such, we should not demand such knowledge to comprehend the code we have written. Knowledge of the mechanisms underlying operators paves the way for us to now explore individual operators within JavaScript. We'll begin by exploring arithmetic and numeric operators.Passage contains an image
Arithmetic and numeric operators
There are eight arithmetic or numeric operators in JavaScript:- Addition : a + b
- Subtraction : a - b
- Division : a / b
- Multiplication : a * b
- Remainder : a % b
- Exponentiation : a ** b
- Unary plus : +a
- Unary minus : -a
Arithmetic and numeric operators will typically coerce their operands to numbers. The only exception is the + addition operator, which will, if passed a non-numerical operand, assume the function of string concatenation instead of addition.There is one guaranteed outcome of all of these operations that is worth knowing about beforehand. An input of NaN guarantees an output of NaN:1 + NaN; // => NaN1 / NaN; // => NaN1 * NaN; // => NaN-NaN; // => NaN+NaN; // => NaN// etc. Beyond that basic assumption, each of these operators behaves in a slightly different way, so it's worth going over each of them individually.Passage contains an image
The addition operator
The addition operator is a dual-purpose operator:- If either operand is String, then it'll concatenate both operands together
- If neither operand is String, then it'll add both operands as numbers
To accomplish its dual purpose, the + operator first needs to discern whether the operands you've passed can be considered strings. Obviously, a primitive String value is clearly a string, but for non-primitives, the + operator will attempt to convert your operands into their primitive representations by relying on the internal ToPrimitive procedure that we detailed in the last chapter, in the Conversion to a primitive section. If the output of ToPrimitive for either of our + - eBook - PDF
- Patrick Carey, Sasha Vodnik, Patrick Carey(Authors)
- 2021(Publication Date)
- Cengage Learning EMEA(Publisher)
CHAPTER 2 WORKING WITH FUNCTIONS, DATA TYPES, AND OPERATORS 52 JavaScript operators are binary or unary. A binary operator requires an operand before and after the operator. The equal sign in the statement myNumber = 100; is an example of a binary operator. A unary operator requires just a single operand either before or after the operator. For example, the increment operator (++), an arithmetic operator, is used to increase an operand by a value of one. The statement myNumber++; changes the value of the myNumber variable to 101. Another type of JavaScript operator, bitwise operators, operate on integer values; this is a fairly complex topic. Bitwise operators and other complex operators are beyond the scope of this book. Note The operand to the left of an operator is known as the left operand, and the operand to the right of an operator is known as the right operand. Note Arithmetic Operators Arithmetic operators are used in JavaScript to perform mathematical calculations, such as addition, subtraction, mul- tiplication, and division. You can also use an arithmetic operator to return the modulus of a calculation, which is the remainder left when you divide one number by another number. Figure 2-8 describes the arithmetic operators supported by JavaScript. You might be confused by the difference between the division ( / ) operator and the modulus (%) operator. The division operator performs a standard mathematical division operation so that the expression 15/6 returns a value of 2.5. The modulus operator returns the remainder after a division so that the expression 15%6 returns a value of 3 because that is the remainder when 15 is divided by 6. Arithmetic operations can also be performed on a single variable using unary operators. Figure 2-9 lists the arithmetic unary operators available in JavaScript. - eBook - ePub
JavaScript from Beginner to Professional
Learn JavaScript quickly by building fun, interactive, and dynamic web apps, games, and pages
- Laurence Lars Svekis, Maaike van Putten, Rob Percival, Laurence Svekis, Codestars By Rob Percival(Authors)
- 2021(Publication Date)
- Packt Publishing(Publisher)
After seeing quite a few data types and some ways to convert them, it is time for the next major building block: operators. These come in handy whenever we want to work with the variables, modify them, perform calculations on them, and compare them. They are called operators because we use them to operate on our variables.Arithmetic operators
Arithmetic operators can be used to perform operations with numbers. Most of these operations will feel very natural to you because they are the basic mathematics you will have come across earlier in life already.Addition
Addition in JavaScript is very simple, we have seen it already. We use + for this operation:let nr1 = 12 ; let nr2 = 14 ; let result1 = nr1 + nr2;However, this operator can also come in very handy for concatenating strings. Note the added space after "Hello" to ensure the end result contains space characters:let str1 = "Hello " ; let str2 = "addition" ; let result2 = str1 + str2;The output of printing result1 and result2 will be as follows:26 Hello addition As you can see, adding numbers and strings lead to different results. If we add two different strings, it will concatenate them into a single string.Practice exercise 2.2
Create a variable for your name, another one for your age, and another one for whether you can code JavaScript or not.Log to the console the following sentence, where name , age and true /false are variables:Hello, my name is Maaike, I am 29 years old and I can code JavaScript: true.Subtraction
Subtraction works as we would expect it as well. We use - for this operation. What do you think gets stored in the variable in this second example?let nr1 = 20 ; let nr2 = 4 ; let str1 = "Hi" ; let nr3 = 3 ; let result1 = nr1 - nr2; let result2 = str1 - nr3; console .log(result1, result2);The output is as follows: 16 NaNThe first result is 16 . And the second result is more interesting. It gives NaN , not an error, but just simply the conclusion that a word and a number subtracted is not a number. Thanks for not crashing, JavaScript!Multiplication
We can multiply two numeric values with the * - eBook - PDF
- Rob Larsen(Author)
- 2013(Publication Date)
- Wrox(Publisher)
OPERATORS The operator is a keyword or symbol that does something to a value when used in an expression. For example, the arithmetic operator + adds two values together. The symbol is used in an expression with either one or two values and performs a calculation on the values to generate a result. For example, here is an expression that uses the multiplication operator: var area = (width * height); An expression is just like a mathematical expression. The values are known as operands. Operators that require only one operand (or value) are sometimes referred to as unary operators, whereas those that require two values are sometimes called binary operators. The different types of operators you see in this section are ‰ ‰ Arithmetic ‰ ‰ Assignment ‰ ‰ Comparison ‰ ‰ Logical ‰ ‰ String You see lots of examples of the operators in action both later in this chapter and in the next two chapters. First, however, it’s time to learn about each type of operator. Arithmetic Operators Arithmetic operators perform arithmetic operations upon operands. (Note that in the examples in Table 10-2, x = 10.) 352 ❘ CHAPTER 10 LEARNING JAVASCRIPT TABLE 10-2: JavaScript’s Arithmetic Operators SYMBOL DESCRIPTION EXAMPLE ( x = 10) RESULT + Addition x+5 15 - Subtraction x-2 8 * Multiplication x*3 30 / Division x/2 5 % Modulus (division remainder) x%3 1 ++ Increment (increments the variable by 1—this technique is often used in counters) x++ 11 -- Decrement (decreases the variable by 1) x-- 9 Assignment Operators The basic assignment operator is the equal sign, but do not take this to mean that it checks whether two values are equal. Rather, it’s used to assign a value to the variable on the left of the equal sign, as you saw in the previous section, which introduced variables. The basic assignment operator can be combined with several other operators to allow you to assign a value to a variable and perform an operation in one step. - eBook - ePub
- Rob Larsen(Author)
- 2013(Publication Date)
- Wrox(Publisher)
The symbol is used in an expression with either one or two values and performs a calculation on the values to generate a result. For example, here is an expression that uses the multiplication operator:var area = (width * height);An expression is just like a mathematical expression. The values are known as operands . Operators that require only one operand (or value) are sometimes referred to as unary operators , whereas those that require two values are sometimes called binary operators .The different types of operators you see in this section are- Arithmetic
- Assignment
- Comparison
- Logical
- String
Arithmetic Operators
Arithmetic operators perform arithmetic operations upon operands. (Note that in the examples in Table 10-2 , x = 10.)Table 10-2:JavaScript’s Arithmetic OperatorsAssignment Operators
The basic assignment operator is the equal sign, but do not take this to mean that it checks whether two values are equal. Rather, it’s used to assign a value to the variable on the left of the equal sign, as you saw in the previous section, which introduced variables.The basic assignment operator can be combined with several other operators to allow you to assign a value to a variable and perform an operation in one step. For example, look at the following statement where there is an assignment operator and an arithmetic operator:total = total - profit; This can be reduced to the following statement: total -= profit;Although it might not look like much, this kind of shorthand can save a lot of code if you have many calculations like this to perform (see Table 10-3 - eBook - PDF
Web Programming
Building Internet Applications
- Chris Bates(Author)
- 2014(Publication Date)
- Wiley(Publisher)
To perform the selection, the script converts the input to an integer using a combination of Math.floor() and eval(). If an invalid input is encountered, the default behavior is triggered and an alert box is shown. 6.8 OPERATORS JavaScript has two types of operator: those used in tests of logic and those used to affect variables. All should be fairly easy to understand and are shown in Table 6.2. If you look Operator Meaning + If the arguments are numbers then they are added together. If the arguments are strings then they are concatenated 3 and the result returned. − If supplied with two operands this subtracts one from the other. If supplied with a single operand it reverses its sign. * Multiplies two numbers together. / Divides the first number by the second. % Modulus Division returns the integer remainder from a division. ! Logical NOT returns false if the operand evaluates to true. Otherwise it returns true. > Greater than returns true if the left operand is greater than the right. >= Returns true if the left operand is greater than or equal to the right. < Returns true if the left operand is less than the right. == Returns true if the two operands are equal. <= Returns true if the left operand is less than or equal to the right. != Returns true if the two operands are not equal. && Logical AND returns true if both operands are true. Otherwise returns false. || Logical OR returns true if one or both operands are true, otherwise returns false. = Assigns a value to a variable += Adds two numbers then assigns the result to the one on the left of the expression. −= Subtracts the term on the right from the term on the left, then assigns the result to the one on the left of the expression. *= Multiplies two values then assigns the result to the one on the left of the expression. /= Divides the term on the left by the term on the right and then assigns the result to the one on the left of the expression. - No longer available |Learn more
- Matt Frisbie(Author)
- 2019(Publication Date)
- Wrox(Publisher)
Additive Operators
The additive operators, add and subtract, are typically the simplest mathematical operators in programming languages. In ECMAScript, however, a number of special behaviors are associated with each operator. As with the multiplicative operators, conversions occur behind the scenes for different data types. For these operators, however, the rules aren't as straightforward.Add
The add operator (+ ) is used just as one would expect, as shown in the following example:let result = 1 + 2;If the two operands are numbers, they perform an arithmetic add and return the result according to the following rules:- If either operand is NaN , the result is NaN .
- If Infinity is added to Infinity , the result is Infinity .
- If –Infinity is added to –Infinity , the result is –Infinity .
- If Infinity is added to –Infinity , the result is NaN .
- If +0 is added to +0, the result is +0.
- If –0 is added to +0, the result is +0.
- If –0 is added to –0, the result is –0.
- If both operands are strings, the second string is concatenated to the first.
- If only one operand is a string, the other operand is converted to a string and the result is the concatenation of the two strings.
If either operand is an object, number, or Boolean, its toString() method is called to get a string value and then the previous rules regarding strings are applied. For undefined and null , the String() function is called to retrieve the values "undefined" and "null" , respectively.Consider the following:let result1 = 5 + 5; // two numbers console.log(result1); // 10 let result2 = 5 + "5"; // a number and a string console.log(result2); // "55"This code illustrates the difference between the two modes for the add operator. Normally, 5 + 5 equals 10 (a number value), as illustrated by the first two lines of code. However, if one of the operands is changed to a string, "5" , the result becomes "55" (which is a primitive string value) because the first operand gets converted to "5" - eBook - PDF
- Chris Minnick(Author)
- 2023(Publication Date)
- For Dummies(Publisher)
For example, if you try to add together two numbers and one of the operators is a string, the results may not be what you want: let sum = 1+"1"; // result: "11" To avoid this common problem, you can explicitly convert operands to the correct type: let sum = 1 + parseInt("1"); // result: 2 Logical operators Logical operators evaluate an expression for truthiness or falsiness. There are three logical operators, as shown in Table 4-3. TABLE 4-2 Arithmetic Operators Operator Description Example + Addition a = 1 + 1 – Subtraction a = 10 - 1 * Multiplication a = 2 * 2 / Division a = 8 / 2 % Remainder a = 5 % 2 ++ Increment a = ++b a = b++ a++ -- Decrement a = --b a = b-- a-- ** Exponentiation operator 2 ** 2 88 BOOK 1 JavaScript Fundamentals The logical AND and OR operators also have clever other uses. The || operator can be used to set a variable to a default value, like this: let language = userPreference.language || 'English'; This statement sets the language to the user-specified language if the user has set one; otherwise, it sets language to 'English'. The && operator can be used to choose between two paths, like this: let logInScreen = !loggedIn && showLogInScreen(); In this example, if the loggedIn variable is falsy, the showLogInScreen() function will run. This way of using && to switch between two paths is commonly used in JavaScript front-end libraries like React.js, Vue.js, and Svelte to do conditional rendering. Conditional rendering means that some piece of the user interface (such as a login form) should show only if a certain condition is true. In the preceding example, the condition you’re testing for is whether the value of loggedIn is falsy. The || and && operators are known as short-circuit operators because they stop executing and return a value when they find a truthy value (in the case of ||) or a falsy value (in the case of &&). - eBook - PDF
- Chris Minnick(Author)
- 2022(Publication Date)
- For Dummies(Publisher)
232 BOOK 3 Advanced Web Coding Listing 5-1 shows arithmetic operators at work. LISTING 5-1: Using Arithmetic Operatorsarithmetic operators Wild Birthday Game
- Enter the number 7
- Multiply by the month of your birth
- Subtract 1
- Multiply by 13
- Add the day of your birth
- Add 3
- Multiply by 11
- Subtract the month of your birth
- Subtract the day of your birth
- Divide by 10
- Add 11
- Divide by 100
- eBook - ePub
- Bill Buchanan(Author)
- 2023(Publication Date)
- CRC Press(Publisher)
Arithmetic operators operate on numerical values. The basic arithmetic operations are add (+), subtract (-), multiply (*), divide (/) and modulus division (%). Modulus division gives the remainder of an integer division. The following gives the basic syntax of two operands with an arithmetic operator.operand operator operandThe assignment operator (=) is used when a variable ‘takes on the value’ of an operation. Other shorthand operators are used with it, including add equals (+=), minus equals (-=), multiply equals (*=), divide equals (/=) and modulus equals (%=). The following examples illustrate their uses.Statement Equivalent x+=3.0 x=x+3.0 voltage/=sqrt(2) voltage=voltage/sqrt(2) bit_mask *=2 bit_mask=bit_mask*2 In many applications it is necessary to increment or decrement a variable by 1. For this purpose Java has two special operators; ++ for increment and -- for decrement. They can either precede or follow the variable. If they precede the variable, then a pre-increment/decrement is conducted, whereas if they follow it, a post-increment/decrement is conducted. Here are some.Statement Equivalent no_values++ no_values=no_values+1 i-- i=i-1 Table 23.1summarizes the arithmetic operators.Table 23.1Arithmetic operatorsOperator Operation Example - subtraction, minus 5-4→1 + addition 4+2→6 * multiplication 4*3→12 / division 4/2→2 % modulus 13%3→1 + = add equals x += 2 is equivalent to x=x+2 -= minus equals x -= 2 is equivalent to x=x-2 /= divide equals x /= y is equivalent to x=x/y *= multiplied equals x *= 32 is equivalent to x=x*32 = assignment x = 1 + + increment Count++ is equivalent to Count=Count+l -- decrement Sec-- is equivalent to Sec=Sec-1 23.5.2 Relationship
The relationship operators determine whether the result of a comparison is TRUE or FALSE. These operators are greater than (>), greater than or equal to (>=), less than (<), less than or equal to (<=), equal to (==) and not equal to (! =). Table 23.2
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.









