Safe defaults and optional data
This lesson applies Operators concepts to code you can run and adapt.
✓ What you will learn in this topic
- Explain key Operators concepts.
- Read and adapt the examples.
- Apply the idea to a small real interface or data task.
Concept explanation
Arithmetic, assignment, comparisons, logic, increment/decrement, ternaries, nullish coalescing, optional chaining, and precedence.
These concepts appear in everyday interfaces and data transformations; understanding the trade-offs helps you choose a reliable implementation.
Syntax
The examples use standard ECMAScript syntax. Run console examples in a browser console or Node.js; DOM examples require a browser page containing the referenced elements.
Example 1: a small experiment
Run this compact example to observe the core rule before applying it to a larger feature.
const settings = { volume: 0 };
const volume = settings.volume ?? 5;
console.log(volume);Expected output: 0
Why it is useful: A small experiment makes the value or behavior easy to inspect.
Example 2: a practical feature
This example models a small piece of application behavior. Adapt its values and inspect what changes.
console.log(7 % 4);Expected output: 3
Why it is useful: The same pattern can be extended into a real feature without tying the entire application to one large block of code.
Common mistakes
Do not use || when zero or an empty string is a valid value; it treats both as missing. Use ?? for nullish defaults.
Best practices
Prefer === and parentheses when precedence is not obvious. Use optional chaining only for genuinely optional paths.
Practice exercise
Why does this example preserve a volume of zero?
Lesson summary
Arithmetic, assignment, comparisons, logic, increment/decrement, ternaries, nullish coalescing, optional chaining, and precedence.
Knowledge check
Which practice best avoids the common mistake in Operators?
Show explanation
Prefer === and parentheses when precedence is not obvious. Use optional chaining only for genuinely optional paths.
Practical example
javascriptconsole.log(7 % 4);
Expected result:
3
Hands-on practice task
Why does this example preserve a volume of zero?
In this section
Other lessons in Operators
Broaden your knowledge
Related learning topics
CSS
Learn to style, lay out, and adapt interfaces with a complete course from CSS foundations through advanced responsive architecture.
HTML
Learn to structure accessible, meaningful web pages with a complete HTML course from first document to professional application patterns.