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

7 Key excerpts on "Javascript Arithmetic Operators"

  • Clean Code in JavaScript
    eBook - ePub

    Clean Code in JavaScript

    Develop reliable, maintainable, and robust JavaScript

    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 +
  • JavaScript from Beginner to Professional
    • Laurence Lars Svekis, Maaike van Putten, 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 NaN
    The 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 *
  • Beginning HTML and CSS
    • 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
    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.)
    Table 10-2:
    JavaScript’s Arithmetic Operators

    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. 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
  • Professional JavaScript for Web Developers
    • 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, however, one of the operands is a string, then the following rules apply:
    • 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"
  • Professional JavaScript for Web Developers
    • Nicholas C. Zakas(Author)
    • 2011(Publication Date)
    • Wrox
      (Publisher)
    The divide operator, like the multiply operator, has special behaviors for special values. They are as follows:
    • If the operands are numbers, regular arithmetic division is performed, meaning that two positives or two negatives equal a positive, whereas operands with different signs yield a negative. If the result can’t be represented in ECMAScript, it returns either Infinity or –Infinity .
    • If either operand is NaN , the result is NaN .
    • If Infinity is divided by Infinity , the result is NaN .
    • If zero is divided by zero, the result is NaN .
    • If a nonzero finite number is divided by zero, the result is either Infinity or –Infinity , depending on the sign of the first operand.
    • If Infinity is divided by any number, the result is either Infinity or –Infinity , depending on the sign of the second operand.
    • If either operand isn’t a number, it is converted to a number behind the scenes using Number() and then the other rules are applied.
    Modulus
    The modulus (remainder) operator is represented by a percent sign (% ) and is used in the following way:
    var result = 26 % 5; //equal to 1
    Just like the other multiplicative operators, the modulus operator behaves differently for special values, as follows:
    • If the operands are numbers, regular arithmetic division is performed, and the remainder of that division is returned.
    • If the dividend is an infinite number and the divisor is a finite number, the result is NaN .
    • If the dividend is a finite number and the divisor is 0, the result is NaN .
    • If Infinity is divided by Infinity , the result is NaN .
    • If the dividend is a finite number and the divisor is an infinite number, then the result is the dividend.
    • If the dividend is zero and the divisor is nonzero, the result is zero.
    • If either operand isn’t a number, it is converted to a number behind the scenes using Number() and then the other rules are applied.
    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.
  • Quick JavaScript
    eBook - ePub
    === , which is always safe.
    Caution: As in almost all languages, it is unwise to compare two floating point numbers for equality. For example, 11*(100/11) is not equal to 100 , as these differ in the 14th decimal place. One potential workaround is to use the method .toFixed( n) , which will return a string with n digits after the decimal point, then do string comparisons.
    String concatenation:
    • + concatenate (join together) two strings, or a string and any other value.
    The arithmetic comparison operators can also be used on strings, giving lexicographic ordering. All capital letters precede all lowercase letters, thus "Cat" < "cat" .
    Assignment:
    • = assignment operator—can be used as an expression; the value of the expression is the value that is assigned.
    JavaScript also has the + and - unary operators. The + operator, when applied to a non-numeric value (such as a string), attempts to convert that value into a number, returning NaN (“not a number”) if it cannot.
    • ?: The ternary operator: In the expression test ? valueIfTrue: valueIfFalse, the test determines which of the two succeeding values is used.
    If you are familiar with Java, most of the Java operators can also be used in JavaScript, including all of the bit-manipulation operators. The bit-manipulation operators convert their operands to integers, do the operation on integers, and convert the results back to (floating-point) numbers.
    Order of precedence is the same as in most languages: Unary plus and minus are done first, then exponentiation, then multiplication and division, then addition and subtraction, then assignment.

    2.7 Equality and Identity

    The == and != comparison operators try to convert their operands to the same type. The results may be surprising. For example, 123 , "123" , [123] , and even ["123"] are all considered equal when using ==
  • Advanced Data Communications and Networks
    • 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 operand
    The 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.1
    summarizes the arithmetic operators.
    Table 23.1
    Arithmetic operators
    Operator 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.