CS Basics: Operators in JavaScript Pt. 1
A breakdown of JavaScript's fundamental operators - arithmetic, assignment, comparison, and logical - with practical examples to understand how they work.
Originally written by Carl Mills · December 18, 2017
What Operators Do
Operators let you assign values, perform arithmetic, compare expressions, and control program logic. JavaScript shares many of these with languages like C and C++.
Arithmetic Operators
+ Addition → x = 5 + 2 // x = 7
* Multiplication → x = 8 * 2 // x = 16
/ Division → x = 10 / 2 // x = 5
++ Increment → x++ adds 1 to x (useful for loops)
-- Decrement → x-- subtracts 1 from x
% Modulus → x = 13 % 4 // x = 1 (remainder)
The modulus operator is especially useful in random number generation or cycling through fixed ranges.
Assignment Operators
= Assign → x = 4
+= Add/Concatenate → x += 4 // adds to existing value
-= Subtract → x -= 4 // subtracts from existing value
*= Multiply → x *= 9
/= Divide → x /= 3
%= Modulus → x %= 5
Compound assignment operators simplify repetitive arithmetic by combining the operation and assignment.
Comparison Operators
Given that x = 5:
== Equal to → x == 5 // true
=== Equal value & type → x === "5" // false
!= Not equal → x != 4 // true
!== Not equal value or type → x !== "5" // true
> Greater than → x > 4 // true
< Less than → x < 6 // true
>= Greater than or equal to → x >= 5 // true
<= Less than or equal to → x <= 5 // true
Use === and !== for strict equality to avoid unexpected type conversions.
Ternary Operator
The ternary operator is a concise way to perform conditional assignments.
variableName = (condition) ? valueIfTrue : valueIfFalse;
votable = (age < 18) ? "too young" : "too old";
Equivalent to an if...else statement but in a single line.
Logical Operators
Given that x = 5 and y = 7:
&& AND → (x == 5 && y == 7) // true
|| OR → (x == 4 || y == 7) // true
! NOT → !(x == 4) // true
Logical operators combine or negate expressions, forming the backbone of program decision logic.
Next in the Series
In the next article, we'll explore more advanced JavaScript operators - bitwise, logical chaining, and how operator precedence shapes expression results.
Continue to Part 2 →