Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
  1. JavaScript: Basics
    9Topics
    |
    10 Quizzes
  2. JavaScript: Variables
    9Topics
    |
    10 Quizzes
  3. JavaScript: Conditional Statements
    10Topics
    |
    11 Quizzes
  4. JavaScript: Functions
    10Topics
    |
    11 Quizzes
  5. JavaScript: Scope
    6Topics
    |
    7 Quizzes
  6. JavaScript: Arrays
    11Topics
    |
    12 Quizzes
  7. JavaScript: Loops
    8Topics
    |
    9 Quizzes
  8. JavaScript: High Order Functions
    3Topics
    |
    4 Quizzes
Lesson 2, Topic 5
In Progress

JavaScript: Mathematical Assignment Operators

Yasin Cakal 29 Oct 2021
Lesson Progress
0% Complete

Consider how variables and math operators can be used to compute new values and assign them to variables. Consider the following example:

let n = 3;
n = n + 1;
console.log(n); // Output: 4

In the above example, we created the variable n and assigned it the value 3. The line that follows, n = n + 1, raises the value of n from 3 to 4.

Another option would have been to use built-in mathematical assignment operators to reassign n after executing some mathematical operation on it. We may rewrite the previous code as:

let n = 3;
n += 1;
console.log(n); // Output: 4

In the second case, we reassigned n using the += assignment operator. We’re using the number to the right to execute the mathematical operation of the first operator +, then reassigning n to the calculated value.

We also have access to other mathematical assignment operators, such as -=, *=, and /=, which operate in a similar way.

let a = 15;
a -= 5; // Can be written as a = a - 5
console.log(a); // Output: 10
 
let b = 6;
b *= 2; // Can be written as b = b * 2
console.log(b); // Output: 12
 
let c = 16;
c /= 4; // Can be written as c = c / 2
console.log(c); // Output: 4

Let’s put these mathematics assignment operators to the test!

Responses

Leave a Reply

%d bloggers like this: