CSE326 Examples77 topics · one complete example each

All topics › Unit 4 · JavaScript Fundamentals

Topic 44 · 43 of 43

Operators and Expressions

All in one: every operator, side by side

What this example compares
  • Expressions: expression vs statement; operands and operators; unary vs binary vs ternary (? :)
  • Arithmetic: + - * / % **, Math.pow(); dividing with / vs % vs Math.floor(), Infinity and NaN
  • Add or take one: x++ vs ++x vs x-- vs --x
  • + with text: adds vs joins vs - * / converting; a chain of + left to right, brackets, template literal
  • Typed input: typed + 5 vs Number(typed) + 5 vs +typed, with a form box and prompt()
  • Storing: = vs += -= *= /= %= **=; one, two or three equals signs
  • Comparing: > < >= <= === !==; strict === vs loose ==; comparing strings
  • Logic: && vs || vs !; short-circuit, truthy and falsy; a default with || vs ??
  • typeof: typeof x vs typeof(x) vs typeof 5 + 5 vs typeof (5 + 5)
  • Order: precedence (who goes first) and associativity (left to right vs right to left)
  • Errors: SyntaxError vs TypeError vs ReferenceError, and Asha's result card with both precedence bugs

Point at any word in the code to see what it means (tap on a phone); click a word to keep its meaning on screen. Read the comment above each numbered panel, press Run, then Edit & experiment to try the TRY lines yourself.

The complete code

Loading the example…

What you should see

You should see 21 panels of cards; the result is long, so scroll inside the frame to reach the last ones. Panel 3 shows 7, 3, 10, 25, 2.5 and 1; panel 5 shows postfix giving the old value 5 and prefix the new value 6; panels 6 and 7 show "52", "523" and "Total: 23" next to their fixes; panel 12 shows == saying true (green) where === says false (red); panel 16 shows Meera's 0 replaced by || but kept by ??; panel 20 shows six SyntaxErrors, two TypeErrors and one ReferenceError, all caught; and panel 21 ends with PASS. The Console prints the same lines, one per card line, each starting with its panel number (for example 3. x + y -> 7), plus one extra line from panel 15: Right side ran (3). Each click on a panel 8 button adds one more line, such as 8. Add 5: box.value is "40" | typed + 5 = "405" | Number(typed) + 5 = 45.

Quick check: in panel 21 the wrong total is NaN. Which two operators are involved, and why do the brackets in total + (bonus ?? 0) fix it?

+ and ??. + outranks ??, so total + bonus runs first; bonus is undefined, so that gives NaN, and NaN ?? 0 stays NaN because NaN is not nullish. The brackets make bonus ?? 0 run first, giving 0, so the total is 195.