Operators in JavaScript
7.1 Operators and Expressions in JavaScript
Expression is any valid unit of code that evaluates to a value
3 + 5 = 8
"Hello" + "World" = "HelloWorld"
true && false = false
We write expressions using operators and values
Arithmatic Operators - Used for mathematical operations
Arithmatic Operators in code
Assignment Operators - Used to assign values to variables
Assignment Operators in code
Comparision Operators - Used to compare values then return true or false
Comparision Operators in code
Logical Operators - Used to combine conditions
Logical Operators in code
3 + 5 = 8
"Hello" + "World" = "HelloWorld"
true && false = false
We write expressions using operators and values
Arithmatic Operators - Used for mathematical operations
Operator | Description | Example | Result |
---|---|---|---|
+ | Addition | 10 + 5 | 15 |
- | Subtraction | 10 - 5 | 5 |
* | Multiplication | 10 * 5 | 50 |
/ | Division | 10 / 5 | 2 |
% | Modulus (Remainder) | 10 % 3 | 1 |
** | Exponentiation | 2 ** 3 | 8 |
Arithmatic Operators in code
arithmatic.js
1let a = 10
2let b = 3
3console.log("Addition:", a + b)
4console.log("Modulo:", a % b)
5console.log("Power:", a ** b)
Assignment Operators - Used to assign values to variables
Operator | Description | Example | Result |
---|---|---|---|
= | Assignment | x = 10 | x = 10 |
+= | Add and Assign | x += 2 | x = x + 2 |
-= | Subtract and Assign | x -= 3 | x = x - 3 |
*= | Multiply and Assign | x *= 2 | x = x * 2 |
/= | Divide and Assign | x /= 2 | x = x / 2 |
Assignment Operators in code
assignment.js
1let score = 20
2score += 5
3console.log("Score after bonus:", score)
Comparision Operators - Used to compare values then return true or false
Operator | Description | Example | Result |
---|---|---|---|
== | Equal (lose) | 5 == '5' | true |
=== | Equal (strict) | 5 === '5' | false |
!= | Not Equal (loose) | 5 != '5' | false |
!== | Not Equal (strict) | 5 !== '5' | true |
> | Greater than | 5 > 3 | true |
< | Less than | 3 < 5 | true |
>= | Greater than or equal to | 5 >= 5 | true |
<= | Less than or equal to | 4 <= 5 | true |
Comparision Operators in code
comparision.js
1console.log(10 > 5) // true
2console.log(10 === "10") // false
3console.log(10 == "10") // true
Logical Operators - Used to combine conditions
Operator | Description | Example | Result |
---|---|---|---|
&& | AND | true && false | false |
|| | OR | true || false | true |
! | NOT | !true | false |
Logical Operators in code
logical.js
1let isLoggedIn = true
2let hasPremium = false
3console.log(isLoggedIn && hasPremium) // false
4console.log(isLoggedIn || hasPremium) // true
5console.log(!isLoggedIn) // false