DEV Community

Cover image for JavaScript Tutorial Series: Operators.
The daily developer
The daily developer

Posted on • Edited on

JavaScript Tutorial Series: Operators.

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
Enter fullscreen mode Exit fullscreen mode
  • multi-line comment
/* this comment can 
span across 
multiple lines*/
Enter fullscreen mode Exit fullscreen mode

Assignment operator

You assign a value to a variable using the assignment operator.

let age = 25;
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

Increment and Decrement

Increment

The increment operator increases the value of a variable by 1.

let x = 1; 
x++;
console.log(x); //2
Enter fullscreen mode Exit fullscreen mode

Decrement

The decrement operator decreases the value of a variable by 1.

let y = 1; 
y--;
console.log(y); //0
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
mizouzie profile image
Sam

I never knew you could prefix OR postfix ++/--

Collapse
 
fullstackjo profile image
The daily developer

yes that is because postfix is more used than prefix