Arithmetic operators are fundamental elements in JavaScript programming, facilitating mathematical calculations within scripts. They enable you to perform basic arithmetic operations such as addition, subtraction, multiplication, division, and more. In this chapter, we'll explore these operators comprehensively, from the basics to advanced usage, with ample examples to solidify your understanding.
JavaScript offers a rich set of operators specifically designed for performing mathematical computations. These operators manipulate numerical values to produce a new result.
Arithmetic operators are fundamental building blocks for various programming tasks, including calculations, data manipulation, and creating dynamic web content.
let sum = 10 + 5;
console.log(sum); // Output: 15
let difference = 20 - 7;
console.log(difference); // Output: 13
let product = 3 * 4;
console.log(product); // Output: 12
let quotient = 16 / 4;
console.log(quotient); // Output: 4
let remainder = 11 % 3;
console.log(remainder); // Output: 2 (11 divided by 3 leaves a remainder of 2)
++x
): Increments the value and then returns the new value.x++
): Returns the current value of x
and then increments it.
let count = 5;
console.log(count++); // Output: 5 (post-increment returns the current value)
console.log(count); // Output: 6 (count is now incremented to 6)
let num = 1;
console.log(++num); // Output: 2 (pre-increment increments first and returns the new value)
--x
) and post-decrement (x--
) forms.
let points = 10;
console.log(points--); // Output: 10 (post-decrement returns the current value)
console.log(points); // Output: 9 (points is now decremented to 9)
let lives = 3;
console.log(--lives); // Output: 2 (pre-decrement decrements first and returns the new value)
let base = 2;
let exponent = 3;
let result = base ** exponent;
console.log(result); // Output: 8 (2 raised to the power of 3)
()
to override the default precedence and force calculations to be done in a specific order.
let expr1 = 10 + 20 * 3; // Evaluates to 70 (multiplication first)
let expr2 = (10 + 20) * 3; // Evaluates to 90 (
In essence, arithmetic operators empower you to perform essential mathematical computations within your JavaScript programs. By mastering these operators, you can manipulate numerical data, create dynamic calculations, and solve problems effectively. Remember operator precedence to ensure your expressions are evaluated correctly, and leverage parentheses for finer control over calculation order. With this knowledge, you're well-equipped to harness the power of arithmetic operations in JavaScript! Happy coding !❤️