DEV Community

Cover image for JavaScript Math Operators
joan?
joan?

Posted on

JavaScript Math Operators

JavaScript math operators are fundamental components of the language, enabling developers to perform various mathematical computations within their code. These operators allow the manipulation of numerical values, making it possible to perform addition, subtraction, multiplication, division, and more. JavaScript's math operators provide a versatile set of tools for handling numeric data, facilitating the creation of dynamic and interactive web applications. In this article, we will discuss the basics of JavaScript math operators, breaking down concepts like basic arithmetic, modulus and exponentiation, increment and decrement, and comparison operations.

Table of Contents

  1. Basic Arithmetic Operations

  2. Modulus and Exponentiation

  3. Increment and Decrement

  4. Assignment with Arithmetic Operators

  5. Comparison Operations

  6. Conclusion

1. Basic Arithmetic Operations

At its core, JavaScript is capable of performing basic arithmetic operations just like your calculator. These operations include addition, subtraction, multiplication, and division. Let's explore each of them using simple examples.

1.1 Addition

In JavaScript, the + operator is used for addition. Consider the following example:

let sum = 5 + 3;
console.log(sum); // Output: 8
Enter fullscreen mode Exit fullscreen mode

In this example, the value of sum is calculated by adding 5 and 3.

1.2 Subtraction

The - operator is used for subtraction. Here's an example:

let difference = 10 - 4;
console.log(difference); // Output: 6
Enter fullscreen mode Exit fullscreen mode

In this case, the value of difference is the result of subtracting 4 from 10.

1.3 Multiplication

For multiplication, you can use the * operator. Let's see an example:

let product = 6 * 7;
console.log(product); // Output: 42
Enter fullscreen mode Exit fullscreen mode

Here, the product variable holds the result of multiplying 6 and 7.

1.4 Division

The / operator is used for division. Check out this example:

let quotient = 20 / 4;
console.log(quotient); // Output: 5
Enter fullscreen mode Exit fullscreen mode

In this example, quotient is the result of dividing 20 by 4.

2. Modulus and Exponentiation

2.1 Modulus

The modulus operator (%) returns the remainder of a division. It's handy for tasks like checking if a number is even or odd. Here's an example:

let remainder = 15 % 4;
console.log(remainder); // Output: 3
Enter fullscreen mode Exit fullscreen mode

In this case, remainder is 3 because it's the remainder of dividing 15 by 4.

2.2 Exponentiation

The exponentiation operator (**) raises the left operand to the power of the right operand. Consider the following:

let result = 2 ** 3;
console.log(result); // Output: 8
Enter fullscreen mode Exit fullscreen mode

In this example, result is 8 because 2 raised to the power of 3 equals 8.

3. Increment and Decrement

JavaScript provides shorthand notations for increasing or decreasing the value of a variable by 1. These operations are known as increment and decrement.

3.1 Increment

The increment operator (++) adds 1 to the current value of a variable. Let's see it in action:

let count = 10;
count++;
console.log(count); // Output: 11
Enter fullscreen mode Exit fullscreen mode

Here, count is initially 10. After using the increment operator, it becomes 11.

3.2 Decrement

The decrement operator (--) subtracts 1 from the current value of a variable. Check out this example:

let score = 8;
score--;
console.log(score); // Output: 7
Enter fullscreen mode Exit fullscreen mode

In this case, score starts at 8 and decreases to 7 after using the decrement operator.

4. Assignment with Arithmetic Operators

JavaScript allows you to combine arithmetic operations with variable assignments for concise code.

4.1 Addition Assignment

The += operator adds the right operand to the left operand and assigns the result to the left operand. Here's an example:

let total = 5;
total += 3;
console.log(total); // Output: 8
Enter fullscreen mode Exit fullscreen mode

In this example, total is initially 5. After the addition assignment, it becomes 8.

4.2 Subtraction Assignment

The -= operator subtracts the right operand from the left operand and assigns the result to the left operand. Consider this example:

let balance = 15;
balance -= 7;
console.log(balance); // Output: 8
Enter fullscreen mode Exit fullscreen mode

Here, balance starts at 15 and is reduced to 8 after the subtraction assignment.

4.3 Multiplication Assignment

The *= operator multiplies the left operand by the right operand and assigns the result to the left operand. Check out this example:

let quantity = 4;
quantity *= 3;
console.log(quantity); // Output: 12
Enter fullscreen mode Exit fullscreen mode

In this case, quantity is initially 4 and becomes 12 after the multiplication assignment.

4.4 Division Assignment

The /= operator divides the left operand by the right operand and assigns the result to the left operand. See the following example:

let totalCost = 24;
totalCost /= 2;
console.log(totalCost); // Output: 12
Enter fullscreen mode Exit fullscreen mode

In this example, totalCost starts at 24 and is halved to 12 after the division assignment.

5. Comparison Operations

Comparison operators are used to compare values in JavaScript, resulting in a Boolean value of true or false.

5.1 Equal to (==)

The equality operator (==) checks if two values are equal. Here's an example:

let a = 5;
let b = 5;
console.log(a == b); // Output: true
Enter fullscreen mode Exit fullscreen mode

In this case, the expression a == b evaluates to true because both a and b have the same value.

5.2 Not Equal to (!=)

The inequality operator (!=) checks if two values are not equal. Consider the following:

let x = 8;
let y = 3;
console.log(x != y); // Output: true
Enter fullscreen mode Exit fullscreen mode

Here, the expression x != y is true because 8 is not equal to 3.

5.3 Greater than (>), Less than (<)

The greater than (>), and less than (<) operators compare numerical values. See the examples below:

let age1 = 20;
let age2 = 25;
console.log(age1 < age2); // Output: true
console.log(age1 > age2); // Output: false
Enter fullscreen mode Exit fullscreen mode

In this example, age1 < age2 evaluates to true because 20 is less than 25, while age1 > age2 is false.

5.4 Greater than or Equal to (>=), Less than or Equal to (<=)

These operators (>= and <=) check if a value is greater than or equal to, or less than or equal to another value. Let's see an example:

let apples = 10;
let oranges = 10;
console.log(apples >= oranges); // Output

: true
console.log(apples <= oranges); // Output: true
Enter fullscreen mode Exit fullscreen mode

Here, both expressions are true because the number of apples is equal to the number of oranges.

5.5. Strict Equality (===)

In addition to the equality operator (==), JavaScript provides a strict equality operator (===). While both operators are used for comparison, they behave differently in certain scenarios.

The strict equality operator compares both value and type, ensuring that not only the values but also the data types of the operands are identical.

let num1 = 5;
let num2 = '5';

console.log(num1 == num2); // Output: true
console.log(num1 === num2); // Output: false
Enter fullscreen mode Exit fullscreen mode

In the example above, num1 == num2 is true because the values are loosely equal. However, num1 === num2 is false because the strict equality operator considers the data types, and the type of num1 (number) is not the same as the type of num2 (string).

One significant advantage of the strict equality operator is that it avoids type coercion. Type coercion is the process of converting one data type to another during comparison, and it can lead to unexpected results.

let value1 = 5;
let value2 = '5';

console.log(value1 == value2); // Output: true (due to type coercion)
console.log(value1 === value2); // Output: false
Enter fullscreen mode Exit fullscreen mode

In the example above, value1 == value2 is true because JavaScript performs type coercion, converting the string '5' to the number 5. On the other hand, value1 === value2 is false because the strict equality operator does not perform type coercion.

When writing JavaScript code, it's generally considered a good practice to use the strict equality operator (===) by default. This helps avoid unexpected behaviors that may arise from type coercion.

let userInput = '42';
let secretNumber = 42;

console.log(userInput == secretNumber); // Output: true (due to type coercion)
console.log(userInput === secretNumber); // Output: false
Enter fullscreen mode Exit fullscreen mode

In this example, using === is safer because it explicitly checks for both value and type equality, reducing the chances of unexpected results.

Conclusion

Understanding JavaScript math operators is essential for anyone venturing into web development. This guide has covered the basics of basic arithmetic, modulus and exponentiation, increment and decrement, and comparison operations, using simple language and practical examples. As you continue to explore JavaScript, these foundational concepts will serve as building blocks for more advanced programming tasks. Practice these concepts by experimenting with code, and you'll find yourself becoming more confident in using JavaScript to create dynamic and interactive web applications. Happy coding!

Top comments (0)