Hey everyone, I'm back with my fifth post on JavaScript. In the last post, we covered data types in JavaScript. Today, we'll dive into operators and conditionals used in JavaScript. Let's get started!
Operators in JavaScript
There are 7 types of operators in JavaScript:
-
Arithmetic Operators
- Perform arithmetic on numbers.
Common operators:
- Addition
+
- Subtraction
-
- Multiplication
*
- Division
/
- Modulus
%
(remainder of division) - Exponentiation
**
(e.g.,a ** b
orMath.pow(a, b)
)
Increment and Decrement:
- Pre-increment
++i
(increments before evaluation) - Post-increment
i++
(increments after evaluation) - Pre-decrement
--i
- Post-decrement
i--
-
Comparison Operators
- Compare two values and return a boolean.
Common operators:
- Equal
==
- Strict equal
===
- Not equal
!=
- Strict not equal
!==
- Greater than
>
- Less than
<
- Greater than or equal
>=
- Less than or equal
<=
-
Logical Operators
- Combine multiple conditions.
Common operators:
- AND
&&
- OR
||
- NOT
!
-
Bitwise Operators
- Work on 32-bit numbers.
Common operators:
- AND
&
- OR
|
- XOR
^
- NOT
~
- Left shift
<<
- Right shift
>>
-
Assignment Operators
- Assign values to variables.
Common operators:
- Simple assignment
=
- Addition assignment
+=
- Subtraction assignment
-=
- Multiplication assignment
*=
- Division assignment
/=
Bitwise assignment operators:
-
&=
,|=
,^=
,<<=
,>>=
Logical assignment operators:
-
&&=
,||=
,??=
-
Ternary Operator
- Shorter way to write
if-else
statements.
- Shorter way to write
Syntax:
condition ? expressionIfTrue : expressionIfFalse;
-
Type Operator
- Use
typeof
to find the data type of a variable.
- Use
Example:
let x;
console.log(typeof x); // "undefined"
Conditional Statements in JavaScript
JavaScript provides the following conditional statements:
-
if-else
- Checks a condition and executes code blocks based on the result.
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
-
else if
- Checks multiple conditions in sequence.
if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition2 is true
} else {
// code to execute if none of the above conditions are true
}
-
switch
- Performs different actions based on different conditions.
switch (expression) {
case value1:
// code to execute if expression === value1
break;
case value2:
// code to execute if expression === value2
break;
default:
// code to execute if no cases match
}
That's it for this post. In the next post, we will explore loops in JavaScript. Stay connected and don't forget to follow me!
Top comments (0)