Operators

Operators in JavaScript are symbols or keywords that perform operations on values or variables. They are essential for performing calculations, comparisons, and manipulating data.

Types of Operators

  • Arithmetic Operators: Perform mathematical calculations.
  • Assignment Operators: Assign values to variables.
  • Comparison Operators: Compare two values and return a Boolean.
  • Logical Operators: Combine or invert Boolean values.
  • String Operators: Operate on strings (mainly concatenation).
  • Unary Operators: Operate on a single operand.
Common Arithmetic Operators
OperatorDescription
+Addition
-Subtraction
*Multiplication
/Division
%Remainder (modulus)
++Increment by 1
--Decrement by 1
Comparison Operators
OperatorDescription
==Equal to (loose equality)
===Equal to (strict equality)
!=Not equal to (loose inequality)
!==Not equal to (strict inequality)
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to
Logical Operators
OperatorDescription
&&Logical AND
||Logical OR
!Logical NOT
Illustration of operators
Illustration of operators

💡 Operator Precedence

Operators have precedence that determines the order in which expressions are evaluated. For example, multiplication (*) has higher precedence than addition (+).

Assignment Operators

Used to assign values to variables, often combined with arithmetic:

Common Assignment Operators
OperatorEquivalent To
=x = y
+=x = x + y
-=x = x - y
*=x = x * y
/=x = x / y
%=x = x % y

String Operator

The + operator concatenates (joins) strings:

📌 Deep Dive: String Concatenation

JAVASCRIPT
let greeting = "Hello, " + "world!";
console.log(greeting);
Output
Hello, world!

Unary Operators

Operate on a single operand. Common unary operators include:

  • typeof: Returns the data type of a value.
  • !: Logical NOT, negates a Boolean value.
  • +: Converts a value to a number (unary plus).
  • -: Converts to number and negates it (unary minus).

📌 Deep Dive: Unary Plus for Type Conversion

JAVASCRIPT
let str = "123";
console.log(typeof str); // string
let num = +str;
console.log(typeof num); // number
Output
string
number

⚠️ Beware of Loose Equality (==) vs Strict Equality (===)

Loose equality (==) compares values after type coercion, which can cause unexpected results. Strict equality (===) compares both value and type without coercion. Prefer === for reliable comparisons.

Operator Examples

📌 Deep Dive: Basic Usage

JAVASCRIPT
let x = 10;
x += 5;           // x = 15
let y = x * 2;    // y = 30
let isEqual = (y === 30); // true
let isNotEqual = (y != "30"); // false due to type coercion
let isGreater = (y > 10); // true
let hasAccess = true && false; // false
Output
15
30
true
false
true
false

💡 Summary

Operators let you perform calculations, comparisons, and logic checks in JavaScript. Understanding operator types and precedence is key to writing correct expressions.