JavaScript Coding Day 12 | JavaScript Operators: Arithmetic, Unary, and Assignment

JavaScript Operators: Arithmetic, Unary, and Assignment

Watch the lesson tutorial  ðŸ”»


1. Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations between variables or values. While most are familiar from basic math class, JavaScript includes a few powerful tools like Exponentiation (power) and Modulus (remainder).

  • Addition (+): Adds numbers.

  • Subtraction (-): Subtracts the right operand from the left.

  • Multiplication (*): Multiplies two numbers.

  • Exponentiation (**): Raises the first number to the power of the second (e.g., $6^2$).

  • Division (/): Divides the left operand by the right.

  • Modulus (%): Returns the remainder left over after division.

Practical Code Example

JavaScript
<script>
    var x = 6;
    var y = 2;

    console.log(x + y);  // Output: 8
    console.log(x - y);  // Output: 4
    console.log(x * y);  // Output: 12
    console.log(x ** y); // Output: 36 (6 to the power of 2)
    console.log(x / y);  // Output: 3
    console.log(x % y);  // Output: 0 (6 divides by 2 perfectly, no remainder)
</script>

2. Unary Operators

Unary operators work on only one value (or operand). These are very popular in loops and counters.

  • Pre-Increment (++a): Increases the value of the variable by 1 before using it.

  • Pre-Decrement (--a): Decreases the value of the variable by 1 before using it.

Practical Code Example

JavaScript
<script>
    var a = 6;
    
    // a is currently 6. 
    // ++a adds 1 immediately, making it 7, then prints it.
    console.log(++a); // Output: 7

    // a is currently 7 (from the step above).
    // --a subtracts 1 immediately, making it 6, then prints it.
    console.log(--a); // Output: 6
</script>

3. Assignment Operators

Assignment operators are used to assign values to variables. The basic one is =, but JavaScript offers "shorthand" operators that perform a math operation and save the result in one step.

  • Addition Assignment (+=): Adds the value on the right to the variable on the left and saves the new result.

  • Subtraction Assignment (-=): Subtracts the value on the right from the variable on the left and saves the new result.

Practical Code Example

JavaScript
<script>
    var c = 6;
    var d = 2;
    
    // Equivalent to: c = c + d
    // c becomes 6 + 2, which is 8
    console.log(c += d); // Output: 8
    
    // NOTE: c is now 8 (it changed in the line above)
    // Equivalent to: c = c - d
    // c becomes 8 - 2, which is 6
    console.log(c -= d); // Output: 6
</script>


- by Chirana Nimnaka

Comments

Popular posts from this blog

Python Coding Day 1 | The print() Function and Comments

What is Python?

Set Up an Environment to Code in Python