Chapter 6 of 28 · JavaScript for Beginners — Complete Free Tutorial
Conditionals & Control Flow
Real programs make decisions: show the error message or the success one, allow the checkout or ask for login. JavaScript gives you if/else, the ternary, switch and logical guards to express those decisions. This chapter covers each form and when each one reads best.
if / else if / else
const score = 87;
if (score >= 90) {
console.log('A');
} else if (score >= 80) {
console.log('B');
} else if (score >= 70) {
console.log('C');
} else {
console.log('F');
}
// Expected output: B
Conditions evaluate top to bottom — the first truthy branch wins, so order matters: >= 80 must come after >= 90 or every high score would print “B”.
Braces are non-negotiable
// Works for one statement — but a trap waiting to spring
if (x > 0) console.log('positive');
// Always use braces: safe under diffing, linters and future edits
if (x > 0) {
console.log('positive');
}
Truthiness in conditions
const username = 'asha';
if (username) { // '' would be falsy
console.log(`Hi ${username}`);
}
let user = null;
if (!user) { // negated guard
console.log('Please log in');
}
Remember the falsy list from Data Types: 0, '', null, undefined, NaN, false. Everything else — including [] and {} — is truthy.
Guard clauses: fail fast, nest less
// Nested version — hard to read
function process(order) {
if (order) {
if (order.paid) {
if (order.items.length) {
ship(order);
}
}
}
}
// Guard clauses — flat and clear
function process(order) {
if (!order) return;
if (!order.paid) { warn('Unpaid'); return; }
if (!order.items.length) { warn('Empty'); return; }
ship(order);
}
Expected output: identical behaviour, dramatically better readability — the happy path stays at the left margin. This is the single most valuable control-flow habit in real codebases.
The ternary for one-liners
const status = stock > 0 ? 'In stock' : 'Sold out';
const greeting = hour < 12 ? 'Good morning' : hour < 18 ? 'Good afternoon' : 'Good evening';
Use it for single expressions in output; switch to if/else when a branch has more than one statement.
switch
function roleLabel(role) {
switch (role) {
case 'admin':
return 'Full access';
case 'editor':
return 'Can publish';
case 'viewer':
return 'Read only';
default:
return 'Unknown role';
}
}
console.log(roleLabel('editor')); // → Can publish
- Comparison is
===(strict —switch (5)will not match'5'). - Every non-empty
caseneedsbreakorreturn, otherwise execution “falls through” to the next case (occasionally useful, usually a bug). defaultruns when nothing matches — likeelse.- Group cases by stacking:
case 'y': case 'Y': ….
function typeName(v) {
switch (typeof v) {
case 'string':
case 'boolean': return 'text-ish';
case 'number': return 'numeric';
default: return 'other';
}
}
if vs switch — choosing
| Situation | Use |
|---|---|
| Two branches (yes/no) | if / else or ternary |
Range checks (>= 90) | if / else if (switch cannot compare ranges) |
| Many equality checks on one value | switch or an object lookup |
| Dispatching by string key | Object map: { admin: fn1, viewer: fn2 }[role]() |
Common mistakes
- Missing
break—switchfalls through and executes the next case too. - Wrong branch order — overlapping ranges must be checked from most specific to least.
=instead of===inside conditions —if (x = 5)assigns and evaluates truthy.- Deep nesting — more than two levels of
ifmeans guard clauses or a helper function. - Using
switchon ranges — it compares equality only.
Practice checklist
- Write a shipping-cost function with guards: no items → 0, subtotal ≥ 100 → free, else → 9.99.
- Convert a nested
ifpyramid into flat guard clauses. - Build a
switchover days of the week that groups weekend days into one case.
Decisions pick branches — loops repeat them. Next: Loops & Iteration.
Frequently Asked Questions
JavaScript is the programming language of the web. It adds behaviour to pages: responding to clicks and input, validating forms, fetching data from APIs, updating the DOM without reloading, and much more. It also runs on servers (Node.js), in desktop and mobile apps, and in build tooling.
They are unrelated languages that share a similar name for historical marketing reasons. Java is a statically-typed compiled language; JavaScript is a dynamically-typed interpreted language designed for the browser. Knowing one does not imply knowledge of the other.
Helpful but not mandatory — HTML gives you the structure JavaScript manipulates and CSS the styling it toggles. If you know basic tags, classes and selectors, you have enough to start; the DOM chapters assume only that much.
Use const by default and let when the value must change. Avoid var entirely in modern code: it is function-scoped instead of block-scoped, hoists differently, and can create accidental globals. This course uses const and let throughout.
The Document Object Model is the browser’s in-memory tree of objects representing your HTML. JavaScript reads and modifies that tree — selecting elements, changing text, adding nodes, attaching event listeners — and the browser re-renders the page to match.
== compares after converting types (so 5 == "5" is true), while === requires the same value AND the same type (5 === "5" is false). Loose equality has famously confusing rules — use === and !== everywhere unless you have a specific reason not to.
JavaScript is single-threaded, so long-running work (timers, fetches, events) is handled by the browser and its callbacks are queued. The event loop moves queued callbacks onto the call stack only when it is empty, with promise callbacks (microtasks) taking priority over timers. It is why asynchronous code never freezes the page.
A Promise is an object representing a future value — pending, fulfilled or rejected — that can be chained and combined (Promise.all). async/await is syntax sugar over promises that lets asynchronous code read top-to-bottom with ordinary try/catch error handling.
Yes. Frameworks are built on exactly these fundamentals — components are functions, state is your variable discipline, effects are events, rendering is DOM work. Developers who learn vanilla first understand what the framework is doing and debug far faster.
Type out the examples instead of copying, build small end-to-end projects (expense tracker, weather app, quiz), handle every UI state (loading, empty, success, error), and revisit fundamentals while reading real code. Consistency beats volume — a little most days outpaces occasional marathons.