Give examples of binary operators in JavaScript and what are their differences?

👨‍💻 Frontend Developer 🟡 Often Asked 🎚️ Medium
#JavaScript #JS Basics #Operators

Brief Answer

Binary operators in JavaScript are operators that work with two operands. They are divided into several categories:

  • Arithmetic (+, -, *, /, %, **)
  • Comparison (==, ===, !=, !==, <, >, <=, >=)
  • Logical (&&, ||, ??)
  • Assignment (=, +=, -=, *=, /=, %=)
  • Bitwise (&, |, ^, <<, >>, >>>)

Complete Classification of Binary Operators

CategoryOperatorsPurposeExample
Arithmetic+, -, *, /, %, **Mathematical operations5 + 3 = 8
Comparison==, ===, !=, !==, <, >Value comparison5 > 3 = true
Logical&&, `, ??`
Assignment=, +=, -=, *=, /=Value assignmentx += 5
Bitwise&, `, ^, <<, >>`Bit operations

1. Arithmetic Operators

Basic Arithmetic Operators

// Addition
let sum = 5 + 3; // 8
let concat = "Hello" + " World"; // "Hello World"
 
// Subtraction
let diff = 10 - 4; // 6
 
// Multiplication
let product = 6 * 7; // 42
 
// Division
let quotient = 15 / 3; // 5
let decimal = 10 / 3; // 3.3333...
 
// Remainder (modulo)
let remainder = 17 % 5; // 2
 
// Exponentiation (ES2016)
let power = 2 ** 3; // 8

Features of the + Operator

// Type coercion
console.log(5 + "3"); // "53" (string)
console.log(5 + 3); // 8 (number)
console.log("5" + 3); // "53" (string)
console.log(+"5" + 3); // 8 (number, unary +)
 
// With boolean values
console.log(5 + true); // 6 (true = 1)
console.log(5 + false); // 5 (false = 0)

2. Comparison Operators

Strict and Non-strict Comparison

OperatorNameType CoercionExample
==EqualityYes"5" == 5true
===Strict equalityNo"5" === 5false
!=InequalityYes"5" != 5false
!==Strict inequalityNo"5" !== 5true
// Comparison examples
console.log(5 == "5"); // true (type coercion)
console.log(5 === "5"); // false (different types)
 
console.log(null == undefined); // true
console.log(null === undefined); // false
 
console.log(0 == false); // true
console.log(0 === false); // false
 
console.log("" == false); // true
console.log("" === false); // false

Order Operators

// Numeric comparison
console.log(5 > 3); // true
console.log(10 <= 10); // true
console.log(7 < 7); // false
 
// String comparison (lexicographic)
console.log("apple" < "banana"); // true
console.log("Apple" < "apple"); // true (uppercase letters are smaller)
 
// Mixed comparison
console.log("10" > 9); // true (string converted to number)
console.log("10" > "9"); // false (string comparison)

3. Logical Operators

Logical AND (&&)

// Returns first falsy value or last truthy
console.log(true && true); // true
console.log(true && false); // false
console.log(5 && 3); // 3
console.log(0 && 5); // 0
console.log("" && "hello"); // ""
 
// Short-circuit evaluation
let user = { name: "Alex" };
user && console.log(user.name); // "Alex"
 
let emptyUser = null;
emptyUser && console.log(emptyUser.name); // nothing printed

Logical OR (||)

// Returns first truthy value or last falsy
console.log(false || true); // true
console.log(0 || 5); // 5
console.log("" || "default"); // "default"
console.log(null || undefined || "fallback"); // "fallback"
 
// Setting default values
function greet(name) {
  name = name || "Guest";
  console.log(`Hello, ${name}!`);
}
 
greet(); // "Hello, Guest!"
greet("Alexander"); // "Hello, Alexander!"

Nullish Coalescing Operator (??)

// Returns right operand if left is null or undefined
console.log(null ?? "default"); // "default"
console.log(undefined ?? "default"); // "default"
console.log(0 ?? "default"); // 0
console.log("" ?? "default"); // ""
console.log(false ?? "default"); // false
 
// Difference from ||
let value = 0;
console.log(value || "default"); // "default"
console.log(value ?? "default"); // 0

4. Assignment Operators

Compound Assignment Operators

OperatorEquivalentDescription
x += yx = x + yAddition and assignment
x -= yx = x - ySubtraction and assignment
x *= yx = x * yMultiplication and assignment
x /= yx = x / yDivision and assignment
x %= yx = x % yRemainder and assignment
x **= yx = x ** yExponentiation and assignment
let x = 10;
 
x += 5; // x = 15
x -= 3; // x = 12
x *= 2; // x = 24
x /= 4; // x = 6
x %= 4; // x = 2
x **= 3; // x = 8
 
// With strings
let message = "Hello";
message += " World"; // "Hello World"
 
// With arrays (via +=)
let arr = [1, 2];
arr += [3, 4]; // "1,23,4" (converted to string!)

Logical Assignment Operators (ES2021)

// Logical AND assignment
let a = true;
a &&= false; // a = a && false → false
 
// Logical OR assignment
let b = false;
b ||= true; // b = b || true → true
 
// Nullish coalescing assignment
let c = null;
c ??= "default"; // c = c ?? "default" → "default"
 
let d = 0;
d ??= "default"; // d remains 0

5. Bitwise Operators

Basic Bitwise Operators

OperatorNameDescriptionExample
&Bitwise ANDReturns 1 if both bits are 15 & 3 = 1
``Bitwise ORReturns 1 if at least one bit is 1
^Bitwise XORReturns 1 if bits are different5 ^ 3 = 6
<<Left shiftShifts bits to the left5 << 1 = 10
>>Right shiftShifts bits to the right5 >> 1 = 2
>>>Unsigned right shiftShifts without sign consideration-5 >>> 1
// Bitwise operation examples
console.log(5 & 3); // 1
// 5 = 101, 3 = 011 → 001 = 1
 
console.log(5 | 3); // 7
// 5 = 101, 3 = 011 → 111 = 7
 
console.log(5 ^ 3); // 6
// 5 = 101, 3 = 011 → 110 = 6
 
console.log(5 << 1); // 10
// 5 = 101 → 1010 = 10
 
console.log(5 >> 1); // 2
// 5 = 101 → 10 = 2
 
// Practical applications
// Even number check
function isEven(n) {
  return (n & 1) === 0;
}
 
// Multiplication/division by powers of 2
let num = 8;
console.log(num << 1); // 16 (multiply by 2)
console.log(num >> 1); // 4 (divide by 2)

Operator Precedence

PrecedenceOperatorsAssociativity
15**Right to left
14*, /, %Left to right
13+, -Left to right
12<<, >>, >>>Left to right
11<, <=, >, >=Left to right
10==, !=, ===, !==Left to right
9&Left to right
8^Left to right
7``
6&&Left to right
5`
3=, +=, -=, etc.Right to left
// Precedence examples
console.log(2 + 3 * 4); // 14 (not 20)
console.log((2 + 3) * 4); // 20
 
console.log(2 ** 3 ** 2); // 512 (not 64, right to left)
console.log((2 ** 3) ** 2); // 64
 
console.log(true || false && false); // true
console.log((true || false) && false); // false

Practical Tasks

Task 1: What will the console output?

console.log("5" + 3 + 2);
console.log(3 + 2 + "5");
Answer

"532" and "55"

In the first case: "5" + 3"53", then "53" + 2"532"

In the second case: 3 + 25, then 5 + "5""55"

Task 2: What will happen?

let a = 5;
let b = a++ + ++a;
console.log(b);
console.log(a);
Answer

b = 12, a = 7

a++ returns 5, then a becomes 6 ++a increments a to 7 and returns 7 b = 5 + 7 = 12

Task 3: Comparison Result

console.log(null == 0);
console.log(null >= 0);
console.log(null > 0);
Answer

false, true, false

  • null == 0false (special rule)
  • null >= 0true (null is converted to 0)
  • null > 0false (null is converted to 0)

Task 4: Logical Operators

let result = "" || 0 || null || undefined || "default";
console.log(result);
 
let value = 0 ?? null ?? undefined ?? "fallback";
console.log(value);
Answer

"default" and 0

  • || returns the first truthy value
  • ?? returns the first non-null and non-undefined value

Task 5: Bitwise Operations

console.log(~5);
console.log(~~5.7);
console.log(5 & 1);
console.log(6 & 1);
Answer

-6, 5, 1, 0

  • ~5-6 (bitwise NOT)
  • ~~5.75 (double bitwise NOT = Math.floor for positive numbers)
  • 5 & 11 (5 is odd)
  • 6 & 10 (6 is even)

Advanced Examples

Usage in Real Code

// Setting default values
function createUser(name, age, role) {
  return {
    name: name || "Anonymous",
    age: age ?? 18,
    role: role || "user",
    isAdmin: role === "admin"
  };
}
 
// Conditional execution
function processData(data) {
  data && data.length > 0 && data.forEach(item => {
    console.log(item);
  });
}
 
// Boolean value toggling
let isVisible = true;
isVisible = !isVisible; // false
 
// Or via XOR (for toggling)
let flag = 1;
flag ^= 1; // 0
flag ^= 1; // 1
 
// Permission checking (bit masks)
const PERMISSIONS = {
  READ: 1,    // 001
  WRITE: 2,   // 010
  EXECUTE: 4  // 100
};
 
let userPermissions = PERMISSIONS.READ | PERMISSIONS.WRITE; // 011
 
// Permission check
function hasPermission(user, permission) {
  return (user & permission) === permission;
}
 
console.log(hasPermission(userPermissions, PERMISSIONS.READ)); // true
console.log(hasPermission(userPermissions, PERMISSIONS.EXECUTE)); // false

Optimization with Operators

// Fast floor rounding
Math.floor(5.7); // regular way
~~5.7; // bitwise way (faster)
 
// Even/odd check
function isEven(n) {
  return n % 2 === 0; // regular way
  // return (n & 1) === 0; // bitwise way
}
 
// Multiplication/division by powers of 2
let num = 16;
num * 4; // regular multiplication
num << 2; // bitwise shift (faster)
 
num / 4; // regular division
num >> 2; // bitwise shift (faster)
 
// Value swapping without temporary variable
let a = 5, b = 10;
a ^= b;
b ^= a;
a ^= b;
console.log(a, b); // 10, 5

Common Mistakes and Pitfalls

1. Type Coercion in Arithmetic

// Unexpected behavior
console.log("10" - "5"); // 5 (numbers)
console.log("10" + "5"); // "105" (string)
console.log("10" * "5"); // 50 (numbers)
console.log("10" / "5"); // 2 (numbers)
 
// Only + leads to string concatenation!

2. Comparison with Type Coercion

// Dangerous comparisons
console.log("" == 0); // true
console.log(false == 0); // true
console.log(null == undefined); // true
console.log(" \t\n" == 0); // true
 
// Always use strict comparison
console.log("" === 0); // false
console.log(false === 0); // false

3. Logical Operators and Short-circuit Evaluation

// May cause error
let user = null;
user && user.name.toUpperCase(); // TypeError if user.name is undefined
 
// Safe variant
user && user.name && user.name.toUpperCase();
 
// Or with optional chaining (ES2020)
user?.name?.toUpperCase();

4. Operator Precedence

// Unexpected result
let result = 5 + 3 * 2; // 11, not 16
let correct = (5 + 3) * 2; // 16
 
// With logical operators
let condition = true || false && false; // true, not false
let intended = (true || false) && false; // false

Modern Features (ES2020+)

Optional Chaining (?.)

// Safe property access
let user = { profile: { name: "Alex" } };
 
// Old way
let name = user && user.profile && user.profile.name;
 
// New way
let name2 = user?.profile?.name;
 
// With methods
user?.profile?.getName?.();
 
// With arrays
let firstItem = arr?.[0];

Nullish Coalescing Assignment (??=)

// Assignment only if null or undefined
let config = { theme: null, lang: "en" };
 
config.theme ??= "dark"; // will be assigned
config.lang ??= "ru"; // will not be assigned
 
console.log(config); // { theme: "dark", lang: "en" }

Summary

Binary operators in JavaScript are the foundation of the language. It’s important to understand:

Differences between operator types and their purpose
Type coercion and when it occurs
Operator precedence for correct execution order
Short-circuit evaluation in logical operators
Strict vs non-strict comparison (=== vs ==)
Bitwise operations for optimization and flag handling

In modern development, prefer:

  • === instead of ==
  • ?? instead of || for default values
  • Optional chaining (?.) for safe access
  • Explicit parentheses for complex expressions

Want more interview preparation articles? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪