OSJavaScript.004: Operators, Expressions, and Type Coercion — ==, ===, ??, and ?.

Anime technical artwork showing JavaScript numeric and string data values passing through expression and equality comparison logic; no people

JavaScript Operators: What a Value Actually Means

JavaScript expressions combine values, variables, and operators to produce results. But similar-looking expressions can behave differently because JavaScript sometimes converts types automatically. OSJavaScript.004 teaches arithmetic, comparison, strict equality, truthy/falsy values, nullish defaults, and optional chaining. Every example uses modern JavaScript syntax.

This lesson follows OSJavaScript.003: Variables and Constants. If you need a refresher on the seven primitive types, review OSJavaScript.002: Primitive Values or the first JavaScript lesson.

Learning objectives

  • Distinguish numeric addition from string concatenation with +.
  • Compare ===, !==, ==, and Object.is().
  • Explain truthy, falsy, and short-circuit evaluation.
  • Choose ?? instead of || when zero or an empty string is valid.
  • Read nested properties using ?. without hiding other programming mistakes.
  • Use parentheses to make operator precedence clear.
  • Run and interpret a complete monitoring example with Node.js.

1. Arithmetic and type coercion

The common numeric operators are + (addition), - (subtraction), * (multiplication), / (division), % (remainder), and ** (exponentiation). Most numeric operators convert string operands when appropriate. The + operator has an additional use: if a primitive operand is a string, it concatenates text.

console.log(10 + 5 * 2); // 20 console.log((10 + 5) * 2); // 30 console.log(“5” + 2); // “52” console.log(“5” – 2); // 3 console.log(Number(“5”) + 2); // 7

Because + is also string concatenation, input from web forms and APIs must be interpreted deliberately. A text value like "120" should be checked and converted before numeric processing. Number("unknown") produces NaN; validate with Number.isFinite() when building systems that rely on measurement data.

See the MDN operators reference for the full operator list and precedence rules.

Web Dev Simplified explains implicit and explicit type coercion, including why automatic conversions can produce unexpected behavior. English-language video.

2. Strict equality versus loose equality

=== compares values without converting between different types; !== negates that result. By contrast, == may coerce operands before comparing, which can be surprising. Prefer strict equality unless you have a deliberate reason to use loose equality.

console.log(“120” === 120); // false console.log(“120” == 120); // true (coercion) console.log(0 === false); // false console.log(0 == false); // true (coercion) console.log(null == undefined); // true console.log(null === undefined); // false

Separate object values are compared by reference, not by matching object properties: {x: 1} === {x: 1} is false. Object.is(NaN, NaN) is true even though NaN === NaN is false. For detailed behavior, see MDN’s equality comparison guide.

Web Dev Simplified demonstrates JavaScript == versus === with concrete loose- and strict-equality examples. English-language comparison tutorial.

3. Truthiness, logical operators, and short-circuiting

JavaScript treats false, 0, -0, 0n, "", null, undefined, and NaN as falsy. Other values, including empty arrays and empty objects, are truthy. Logical operators && and || can return operands rather than necessarily producing a Boolean.

console.log(Boolean([])); // true console.log(0 || 5); // 5 console.log(“” || “N/A”); // “N/A” console.log(0 && “done”); // 0 console.log(true && “ok”); // “ok”

Both && and || short-circuit: if the left operand determines the answer, the right operand is not evaluated. The right side of ?? is evaluated only if its left operand is null or undefined.

4. Defaults: || is not the same as ??

If 0 and the empty string are meaningful values, use ?? for missing-data defaults. || instead substitutes its right side for any falsy value, potentially turning a legitimate zero into the wrong result.

const count = 0; console.log(count || 100); // 100 console.log(count ?? 100); // 0 const label = “”; console.log(label || “unknown”); // “unknown” console.log(label ?? “unknown”); // “”

The MDN nullish-coalescing guide explains this distinction. Remember: mixing ?? directly with || or && without parentheses causes a syntax error.

5. Optional chaining: ?. reads safely from missing data

The ?. operator returns undefined rather than throwing a property-access error when the value on its left is null or undefined. It does not make every programming error harmless: calling a non-function through ?.() can still fail, and an undeclared root identifier still causes a reference error.

const device = { sensor: { temp: 72 } }; console.log(device?.sensor?.temp); // 72 console.log(device?.gps?.latitude); // undefined console.log(device?.gps?.latitude ?? “N/A”); // “N/A”

When several nested properties are optional, apply the guard at each uncertain step. See MDN’s optional-chaining documentation.

Web Dev Simplified demonstrates nullish coalescing beginning around 00:41 and optional chaining around 06:19, alongside other modern JavaScript features.

6. Practice lab: validate an equipment API reading

Suppose an API returns voltage as a string, current as a number, and an optional warning threshold. Use explicit numeric conversion, strict equality, and nullish coalescing to process that data. An API is a software interface; see What Is an API? for background.

Create main.js and paste the complete program. This sample was syntax-checked and executed successfully with Node.js 22.16.0. The readings are simulated, not real electrical measurements or safety limits.

“use strict”; const reading = { volts: “120”, // text from a sample API amps: 8, warningLimit: null, sensor: { temperature: 72 }, }; const voltage = Number(reading.volts); const powerWatts = voltage * reading.amps; const limit = reading.warningLimit ?? 80; const temperature = reading.sensor?.temperature ?? “missing”; const withinLimits = powerWatts < 1100 && temperature < limit; console.log(“power:”, powerWatts, “W”); console.log(“string plus number:”, reading.volts + reading.amps); console.log(“strict match:”, reading.volts === 120); console.log(“loose match:”, reading.volts == 120); console.log(“warning limit:”, limit); console.log(“temperature:”, temperature); console.log(“within limits:”, withinLimits); console.log(“zero with OR:”, 0 || 5); console.log(“zero with nullish:”, 0 ?? 5);

Run node --check main.js first, then node main.js. The output from the tested program is:

power: 960 W string plus number: 1208 strict match: false loose match: true warning limit: 80 temperature: 72 within limits: true zero with OR: 5 zero with nullish: 0

Notice that the power calculation uses the converted numeric voltage, while the deliberately unconverted string is concatenated with 8. This demonstrates why type validation matters when processing JSON-style data. The 960-watt result is simply 120 × 8 for a hypothetical example.

7. Common mistakes

  • Using loose equality without intent: "0" == 0 returns true. Strict equality is usually easier to reason about.
  • Trusting implicit conversion: "5" + 2 concatenates, while "5" - 2 converts.
  • Replacing a legitimate zero: value || fallback treats zero as missing. Prefer value ?? fallback if only nullish values should default.
  • Ignoring NaN: invalid numeric input may not throw. Check Number.isFinite().
  • Assuming optional chaining catches all errors: it only short-circuits nullish property access in the guarded chain.
  • Forgetting parentheses: precedence and mixing ?? with logical operators need careful grouping.

8. Knowledge check

  1. What does "9" + 1 evaluate to, and why?
  2. What is the result of "9" === 9? What about "9" == 9?
  3. Why is 0 ?? 5 different from 0 || 5?
  4. What is the difference between device?.gps?.latitude and device.gps.latitude when gps is missing?
  5. How do you verify that Number("bad") produced a valid finite number?
  6. Change the lab’s volts to "110". Predict the new power output.

Answer guide: (1) "91" because one operand is a string; (2) false, then true; (3) nullish preserves zero but OR replaces any falsy value; (4) the optional chain returns undefined, the unguarded chain throws; (5) Number.isFinite() returns false; (6) 880 W.

Official references and next lesson

Use the MDN expressions/operators reference and the ECMAScript language specification for exact semantics. For a cross-language comparison, read OSGo.003: Operators and Expressions, but remember Go and JavaScript have different conversion rules. The next JavaScript lesson, OSJavaScript.005, can introduce conditional branches and loops. The complete 43-subject rotation now advances to HTML.

Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support our work and help further secure the integrity of our research initiatives, please scan the QR code below to donate 5,000 sats.

BitcoinVersus.Tech original Bitcoin donation QR for 5000 satoshis

For mobile scanning, open the lesson on a larger screen and scan the QR code with a compatible Bitcoin wallet. Verify the destination address before sending: 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb.

BitcoinVersus.tech is not a financial advisor. This media platform reports on financial subjects purely for informational purposes.

One response to “OSJavaScript.004: Operators, Expressions, and Type Coercion — ==, ===, ??, and ?.”

  1. […] a web form; MDN: validation; MDN: accessible names and labels. For JavaScript-side enhancements see OSJavaScript.004. The next HTML lesson can develop tables, media, or document accessibility in further detail […]

    Like

Leave a Reply