Operators are distinct symbols used to perform operations on operands such as values and variables.
We've seen an operator in the previous post, which is the assignment operator.
Before we start this lessons about operators let's talk about comments.
Comments
Comments are a small description that you can add to your code to make it readable. Comments are also used to stop the execution of a line of code since the compiler parses and then discards comments.
There are two types of comments:
- single-line comment
// this is a comment
- multi-line comment
/* this comment can
span across
multiple lines*/
Assignment operator
You assign a value to a variable using the assignment operator.
let age = 25;
In the example above we've assigned 25
to the variable age
.
Arithmetic operators
operator | description |
---|---|
+ | addition operator |
- | subtraction operator |
* | multiplication operator |
/ | division operator |
% | remainder operator |
** | Exponentiation operator |
++ | increment operator |
-- | decrement operator |
Here are some examples:
let x = 3;
x = x + 7 //10
let y = 10;
y = y / 2; //5
A shorthand can be used to do these operation:
This works the same with subtraction multiplication and division
Using the example above
let x = 3;
x = x + 7 //10
//instead of writing x = x + 7;
x += 7; //10
Increment and Decrement
Increment
The increment operator increases the value of a variable by 1.
let x = 1;
x++;
console.log(x); //2
Decrement
The decrement operator decreases the value of a variable by 1.
let y = 1;
y--;
console.log(y); //0
Prefix and postfix increment and decrement
Prefix
Prefix increment/decrement first increases or decreases the value then executes the statement.
Postfix
Postfix increment/decrement executes the statement then increases or decreases the value.
Exponentiation
Using this operator raises the first operand to the second operand's power.
let x = 5;
let y = 3;
let result = x ** y;
console.log(result); //125
Remainder operator
The remainder operator returns the remaining part of a division/
let x = 7
let y = 3
let result = x % y;
console.log(result); //1
Top comments (2)
I never knew you could prefix OR postfix ++/--
yes that is because postfix is more used than prefix