Question

13.

What are Arithmetic Operators in JavaScript

Answer

In JavaScript, arithmetic operators are used to perform mathematical operations between numeric operands. These operators are fundamental to any programming language and allow you to carry out calculations, ranging from basic to complex. Here's an overview of the arithmetic operators available in JavaScript:

  1. Addition (+): Adds two operands.

    let result = 5 + 3; // result is 8
  2. Subtraction (-): Subtracts the second operand from the first.

    let result = 5 - 3; // result is 2
  3. Multiplication (*): Multiplies two operands.

    let result = 5 * 3; // result is 15
  4. Division (/): Divides the first operand by the second.

    let result = 15 / 3; // result is 5
  5. Remainder (%): Returns the remainder left over when one operand is divided by a second operand.

    let result = 5 % 3; // result is 2
  6. Exponentiation (**): Raises the first operand to the power of the second operand.

    let result = 5 ** 3; // result is 125 (5*5*5)
  7. Increment (++): Adds one to its operand. The increment operator can be used as a prefix or postfix operator.

    let a = 5;
    let b = a++; // b is 5, a is 6 after this line
    let c = ++a; // c is 7, a is 7 before c is assigned
  8. Decrement (--): Subtracts one from its operand. The decrement operator can also be used as a prefix or postfix operator.

    let a = 5;
    let b = a--; // b is 5, a is 4 after this line
    let c = --a; // c is 3, a is 3 before c is assigned
  9. Unary Negation (-): Returns the negation of its operand.

    let a = 5;
    let b = -a; // b is -5
  10. Unary Plus (+): Attempts to convert the operand into a number, if it isn't already.

    let a = "5";
    let b = +a; // b is now the number 5, not the string "5"

Special Cases

  • Addition with Strings: If one or both operands are strings, the + operator will concatenate the strings rather than performing arithmetic addition.

    let result = "Hello, " + "world!"; // result is "Hello, world!"
  • Division by Zero: Dividing a number by 0 does not throw an error in JavaScript but results in Infinity or -Infinity.

    let result = 5 / 0; // result is Infinity
  • NaN (Not a Number): Certain operations might result in NaN, indicating that the result is not a valid number.

    let result = "a" * 3; // result is NaN

Support us ❤️

Buy Us A Coffee