The Arithmetic,Comparison, Logical and String Operators in JavaScript. Operator precedence.

The Arithmetic,Comparison, Logical and String Operators in JavaScript. Operator precedence. iti

๐Ÿ”ข JavaScript Operators: Arithmetic, Comparison, Logical, String & Operator Precedence

JavaScript uses operators to perform various operations on variables and values. Understanding different types of operators is essential to building logic in any JavaScript-based web application. Let's explore Arithmetic, Comparison, Logical, and String operators along with their precedence. โš™๏ธ


โž• Arithmetic Operators

Arithmetic operators are used to perform mathematical operations:

OperatorDescriptionExample
+Addition5 + 3 = 8
-Subtraction5 - 3 = 2
*Multiplication5 * 3 = 15
/Division6 / 3 = 2
%Modulus (Remainder)5 % 2 = 1
++Incrementa++ or ++a
--Decrementa-- or --a

๐Ÿ” Comparison Operators

These operators compare two values and return a Boolean result (true or false):

OperatorDescriptionExample
==Equal to (loose comparison)5 == "5" // true
===Strict equal (value + type)5 === "5" // false
!=Not equal5 != "6" // true
!==Strict not equal5 !== "5" // true
>Greater than6 > 5 // true
<Less than4 < 5 // true
>=Greater than or equal to5 >= 5 // true
<=Less than or equal to4 <= 5 // true

๐Ÿ”— Logical Operators

Logical operators are used to combine multiple conditions or values:

OperatorDescriptionExample
&&Logical AND(a > 2 && b < 5)
||Logical OR(a > 2 || b < 5)
!Logical NOT!(a > 2)

๐Ÿ”ค String Operators

JavaScript uses the + operator to concatenate (join) strings:

let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName; // "John Doe"

If one operand is a string and the other is a number, JavaScript converts the number to a string before concatenating.

"The answer is " + 42; // "The answer is 42"

โš™๏ธ Operator Precedence

When multiple operators are used in an expression, JavaScript follows operator precedence rules to decide which operation to perform first. Operators with higher precedence are evaluated before those with lower precedence.

๐ŸŽฏ Example of Precedence Order:

  1. Parentheses ()
  2. Unary operators ++ -- + - !
  3. Multiplication, Division * / %
  4. Addition, Subtraction + -
  5. Comparison < > <= >=
  6. Equality == != === !==
  7. Logical AND &&
  8. Logical OR ||
  9. Assignment = += -=

๐Ÿงช Example:

let result = 3 + 4 * 2; // 3 + (4*2) = 11

Use parentheses () to change default precedence and make expressions more readable:

let result = (3 + 4) * 2; // (7) * 2 = 14

๐Ÿ“Œ Summary

  • Use arithmetic operators to perform basic math.
  • Use comparison and logical operators to build conditions.
  • Use the + operator for string concatenation.
  • Understand operator precedence to avoid logic errors.

Mastering these operators is essential to writing correct and efficient JavaScript code for your web applications! ๐Ÿ’ป๐Ÿš€