404 Not Found

404 Not Found


nginx

JavaScript Operators

Operators are symbols that tell JavaScript what operation to perform. You use + for addition every day, but JS operators go far beyond arithmetic — assignment, comparison, and logical evaluation all rely on them. This lesson covers the most commonly used operators in one go.

Arithmetic Operators

Operator Meaning Example
+ Addition 5 + 38
- Subtraction 5 - 32
* Multiplication 5 * 315
/ Division 6 / 32
% Remainder 7 % 31
** Exponentiation 2 ** 38
++ Increment x++ or ++x
-- Decrement x-- or --x

The remainder operator % is especially useful — checking odd/even, wrapping around in loops, and more. ** is the exponentiation operator added in ES2016, equivalent to Math.pow() but more concise.

The difference between prefix and postfix ++ / --: prefix changes first then returns, postfix returns first then changes. Don't chain multiple ++ on the same line — the code becomes an unreadable riddle.

Example: Arithmetic Operators Basics

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Arithmetic Operators</title>
</head>
<body>
  <h3>Arithmetic Operators Demo</h3>
  <pre id="output"></pre>
  <script>
    var out = document.getElementById('output');
    var a = 17, b = 5;

    var lines = [];
    lines.push('a = ' + a + ', b = ' + b);
    lines.push('a + b  = ' + (a + b));
    lines.push('a - b  = ' + (a - b));
    lines.push('a * b  = ' + (a * b));
    lines.push('a / b  = ' + (a / b));
    lines.push('a % b  = ' + (a % b));
    lines.push('a  b = ' + (a  b));

    var x = 10;
    lines.push('');
    lines.push('x = 10');
    lines.push('x++  = ' + (x++) + '  (postfix: returns old value, x becomes ' + x + ')');
    lines.push('++x  = ' + (++x) + '  (prefix: changes first, x becomes ' + x + ')');

    out.textContent = lines.join('\n');
  </script>
</body>
</html>
▶ Try it Yourself

Assignment Operators

= is assignment, not "equals" in the mathematical sense. This is one of the most common pitfalls for beginners — if (x = 5) won't throw an error; it assigns 5 to x and returns 5 (truthy), so the condition is always true.

Compound assignment is shorthand:

Shorthand Equivalent
x += 5 x = x + 5
x -= 3 x = x - 3
x *= 2 x = x * 2
x /= 4 x = x / 4
x %= 3 x = x % 3

Example: Assignment Operators

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Assignment Operators</title>
</head>
<body>
  <h3>Assignment Operators Demo</h3>
  <pre id="output"></pre>
  <script>
    var out = document.getElementById('output');
    var lines = [];

    var score = 80;
    lines.push('Initial score = ' + score);

    score += 10;
    lines.push('score += 10 → ' + score);

    score -= 25;
    lines.push('score -= 25 → ' + score);

    score *= 2;
    lines.push('score *= 2  → ' + score);

    score /= 3;
    lines.push('score /= 3  → ' + score.toFixed(1));

    score %= 30;
    lines.push('score %= 30 → ' + score.toFixed(1));

    out.textContent = lines.join('\n');
  </script>
</body>
</html>
▶ Try it Yourself

Comparison Operators

Operator Meaning
== Loose equality (performs type coercion)
=== Strict equality (no type coercion)
!= Loose inequality
!== Strict inequality
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal

⚠️ The == vs === trap: This is the most classic JavaScript pitfall, bar none. == silently performs type coercion — "5" == 5 is true! Meanwhile === requires both type and value to match — "5" === 5 is false. Always use === unless you specifically need type coercion. Likewise, use !== instead of !=.

Example: The == vs === Trap

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>== vs ===</title>
</head>
<body>
  <h3>Loose Equality vs Strict Equality</h3>
  <pre id="output"></pre>
  <script>
    var out = document.getElementById('output');
    var lines = [];

    lines.push('"5" == 5   → ' + ("5" == 5));
    lines.push('"5" === 5  → ' + ("5" === 5));
    lines.push('');
    lines.push('0 == false   → ' + (0 == false));
    lines.push('0 === false  → ' + (0 === false));
    lines.push('');
    lines.push('"" == false  → ' + ("" == false));
    lines.push('"" === false → ' + ("" === false));
    lines.push('');
    lines.push('null == undefined  → ' + (null == undefined));
    lines.push('null === undefined → ' + (null === undefined));
    lines.push('');
    lines.push('5 != "5"   → ' + (5 != "5"));
    lines.push('5 !== "5"  → ' + (5 !== "5"));

    out.textContent = lines.join('\n');
  </script>
</body>
</html>
▶ Try it Yourself

See that? 0 == false and "" == false are both true — completely counterintuitive. It's like comparing apples and oranges: == says "both are fruit, close enough"; === says "they're not the same, period." Stick with === and you'll avoid half your bugs.

Logical Operators

Operator Meaning Description
&& AND True only when both sides are truthy
|| OR True when either side is truthy
! NOT Negates the value

&& and || have a useful feature called short-circuit evaluation: && stops at the first falsy value, || stops at the first truthy value — the rest is never evaluated. This is commonly used for concise conditional assignments:

HTML
<script>
var name = userInput || 'Anonymous';
</script>

Example: Logical Operators and Short-Circuit Evaluation

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Logical Operators</title>
</head>
<body>
  <h3>Logical Operators Demo</h3>
  <pre id="output"></pre>
  <script>
    var out = document.getElementById('output');
    var lines = [];

    var age = 20;
    var hasTicket = true;

    lines.push('age = ' + age + ', hasTicket = ' + hasTicket);
    lines.push('age >= 18 && hasTicket → ' + (age >= 18 && hasTicket));
    lines.push('age >= 18 || hasTicket → ' + (age >= 18 || hasTicket));
    lines.push('!hasTicket          → ' + (!hasTicket));
    lines.push('');

    lines.push('--- Short-Circuit Evaluation ---');
    lines.push('1 && "hello"  → ' + (1 && "hello"));
    lines.push('0 && "hello"  → ' + (0 && "hello"));
    lines.push('1 || "hello"  → ' + (1 || "hello"));
    lines.push('0 || "hello"  → ' + (0 || "hello"));
    lines.push('');

    var username = '';
    var displayName = username || 'Guest';
    lines.push('Empty string || "Guest" → ' + displayName);

    out.textContent = lines.join('\n');
  </script>
</body>
</html>
▶ Try it Yourself

The + Operator with Strings

When + encounters a string, it becomes a concatenation operator: as long as one side is a string, the other side is converted to a string and they're joined together.

HTML
<script>
"Hello" + " " + "World"   // "Hello World"
"Number: " + 42            // "Number: 42"
3 + 4 + "px"              // "7px" (3+4=7 first, then concatenated)
"px" + 3 + 4              // "px34" (left to right: "px"+3="px3", then +4)
</script>

That "px" + 3 + 4 giving "px34" instead of "px7" is a classic interview trap — + evaluates left to right, and once the left side is a string, everything after it becomes concatenation.

Ternary Operator Overview

The ternary operator is shorthand for if...else, with the syntax: condition ? value1 : value2.

HTML
<script>
var status = age >= 18 ? 'Adult' : 'Minor';
</script>

If the condition is truthy, it returns value1; otherwise value2. Simple conditions work elegantly with the ternary operator, but don't nest them — a ? b ? c : d : e is a recipe for confusion. Detailed usage is covered in Lesson 10.

Operator Precedence

JavaScript determines evaluation order based on precedence, following the same rules you learned in math class: multiplication and division before addition and subtraction, parentheses first.

HTML
<script>
2 + 3 * 4     // 14, not 20
(2 + 3) * 4   // 20
</script>

Common precedence from highest to lowest: ()!*** / %+ -> < >= <=== === != !==&&||?:=.

When in doubt, add parentheses. Parentheses are free, but bugs are expensive.


📖 Summary

❓ FAQ

Q Why does "1" + 2 + 3 give "123" instead of "15"?
A + evaluates left to right. "1" + 2 produces the string "12", then "12" + 3 gives "123". To add the numbers first, use parentheses: "1" + (2 + 3) gives "15".
Q Why is 0 == false true?
A == performs type coercion before comparing. Both 0 and false are converted to the number 0, so they're equal. This is why === is recommended — it doesn't coerce, so 0 === false is false.
Q What's the difference between x++ and ++x?
A When used alone, both increment x by 1. The difference is in the expression's return value: x++ returns the old value before incrementing, ++x returns the new value after incrementing. For example, var a = 5; var b = a++; gives a=6, b=5; while var a = 5; var b = ++a; gives a=6, b=6.

📝 Exercises

  1. Write a program that takes a three-digit number (e.g., 371) and extracts its hundreds, tens, and ones digits using % and /, then prints them.
  2. Without using if...else, write a single line using the ternary operator to determine whether a year variable year is a leap year, and assign the result to isLeap (hint: divisible by 4 and not by 100, or divisible by 400).
  3. Predict the results of the following expressions, then verify in the browser console: [] == false, [] == ![], null == 0. Explain why — if you can't, it means you need to review the implicit coercion rules of ==, and then firmly embrace ===.
100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏