TEC-WEB46-02 · Lesson 7 · 15 clock hours · theory
JavaScript Fundamentals: Variables, Data Types, Operators, and Control Flow
Objective. Students write JavaScript using let/const, the six primitive data types, arithmetic and comparison operators, and if/else and switch control flow structures to solve defined logic problems.
⚠ Pending professional review
This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.
VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.
JavaScript Fundamentals: Variables, Data Types, Operators, and Control Flow
JavaScript is the programming language that makes web pages interactive. Before you manipulate the browser or build applications, you need a firm grip on how JavaScript stores data, performs calculations, and makes decisions. This lesson covers those foundations.
Declaring Variables: let and const
Modern JavaScript uses two keywords to declare variables: `let` and `const`.
- `let` declares a variable whose value can be reassigned later. Use it when the value will change — for example, a running total or a loop counter.
- `const` declares a variable that is bound to its initial value and cannot be reassigned. Use it for values that should stay fixed — for example, a tax rate or a configuration setting.
Avoid the older `var` keyword in new code. It has confusing scoping rules (function scope instead of block scope) that cause hard-to-find bugs.
```js
let score = 0; // can be reassigned
const TAX_RATE = 0.08; // must not change
score = 10; // OK
// TAX_RATE = 0.09; // TypeError — cannot reassign a const
```
Always declare variables before you use them. Reading an undeclared name throws a `ReferenceError`.
The Six Primitive Data Types
JavaScript has six primitive (non-object) data types:
| Type | Example | Notes |
|---|---|---|
| `number` | `42`, `3.14`, `NaN` | All numbers share one type; `NaN` means "Not a Number" |
| `string` | `"hello"`, `'world'`, `` `template` `` | Immutable sequence of characters |
| `boolean` | `true`, `false` | Logic values only |
| `undefined` | `undefined` | Variable declared but not yet assigned |
| `null` | `null` | Intentional absence of a value (assigned by the programmer) |
| `bigint` | `9007199254740993n` | Integers beyond the safe integer limit |
Use the `typeof` operator to check a value's type at runtime: `typeof 42` returns `"number"`. Note a well-known quirk: `typeof null` returns `"object"` — this is a historical bug in the language, not accurate type information.
Arithmetic and Comparison Operators
Arithmetic operators perform math: `+`, `-`, ``, `/`, `%` (remainder), and `*` (exponentiation). Operator precedence follows standard math rules — multiplication and division before addition and subtraction — and parentheses override that order.
Comparison operators produce a boolean result:
- `===` (strict equality) — compares value and type. Prefer this in all new code.
- `!==` (strict inequality)
- `==` (loose equality) — compares value after type coercion. Avoid it; coercion produces surprising results. For example, `0 == false` is `true`, and `"" == false` is also `true`.
- `<`, `>`, `<=`, `>=` — relational comparisons
Type coercion happens when JavaScript automatically converts one type to another to complete an operation. The `+` operator is especially tricky: if either operand is a string, it performs string concatenation instead of addition. For example, `"5" + 3` produces `"53"`, not `8`.
Logical operators combine boolean expressions: `&&` (AND), `||` (OR), `!` (NOT).
Control Flow: if/else
An `if` statement runs a block of code only when its condition is `true`. An optional `else if` chain tests additional conditions. A final `else` handles everything that did not match.
```js
const grade = 78;
if (grade >= 90) {
console.log("A");
} else if (grade >= 80) {
console.log("B");
} else if (grade >= 70) {
console.log("C");
} else {
console.log("Below C");
}
// Output: C
```
Always use curly braces `{}` around the block, even for single-line bodies. Omitting them is legal but causes errors when lines are added later.
Control Flow: switch
A `switch` statement compares one expression against multiple specific values (cases). It is cleaner than a long `if/else if` chain when you are checking one variable for many exact values.
```js
const day = "Monday";
switch (day) {
case "Saturday":
case "Sunday":
console.log("Weekend");
break;
default:
console.log("Weekday");
}
// Output: Weekday
```
Each `case` must end with `break` unless you intentionally want execution to fall through to the next case. A missing `break` is a common logical error. The `default` block runs when no case matches.
Reading Errors in the Console
The Chrome DevTools console reports errors with a type and a line number. Common types you will see in this lesson:
- ReferenceError — you used a name that has not been declared.
- TypeError — you used a value in a way its type does not allow (e.g., reassigning a `const`, or calling a non-function).
- SyntaxError — the code cannot be parsed (missing bracket, typo in keyword).
- Logic error — the code runs without crashing but produces the wrong output. The console will not flag this; you must read the output and compare it to what was expected.
When you see an error, read the message, note the line number, and check the line and the lines just before it.
Safe Practices in the Development Environment
JavaScript running in the browser is sandboxed, but good habits still matter:
- Never paste code from unknown sources into the DevTools console of a site where you are logged in. Malicious scripts can steal session data (a technique called self-XSS).
- Keep VS Code and Node.js updated to receive security patches.
- Save your work frequently and use version control (Git) even for practice files — accidental overwrites are the most common cause of lost work in this trade.
Key terms8
letA JavaScript keyword that declares a block-scoped variable whose value can be reassigned after its initial assignment.
constA JavaScript keyword that declares a block-scoped variable that cannot be reassigned; its binding is fixed from the point of declaration.
primitive data typeOne of JavaScript's six basic value types — number, string, boolean, undefined, null, and bigint — that are not objects and have no methods of their own.
type coercionJavaScript's automatic conversion of a value from one data type to another when an operator or context expects a different type, which can produce unexpected results.
strict equality (===)A comparison operator that returns true only when both the value and the data type of two operands are identical, with no type coercion performed.
operator precedenceThe rules that determine the order in which operators in an expression are evaluated; for example, multiplication is evaluated before addition unless parentheses override the order.
ReferenceErrorA JavaScript runtime error thrown when code attempts to read a variable name that has not been declared in the current scope.
switch statementA control flow structure that compares a single expression against a list of specific case values and executes the matching block, typically ended with a break statement.
Worked examples4
1. Predict the output of: console.log("5" + 3); and console.log("5" - 3);
- Step 1: Evaluate '"5" + 3'. The + operator checks both operands. The left operand is a string. When either operand of + is a string, JavaScript coerces the other operand to a string and concatenates. 3 becomes "3", so the result is "53" (a string).
- Step 2: Evaluate '"5" - 3'. The - operator has no string behavior; it always attempts numeric subtraction. JavaScript coerces "5" to the number 5, then computes 5 - 3 = 2 (a number).
- Step 3: Write the outputs in order.
Answer: "5" + 3 outputs 53 (string). "5" - 3 outputs 2 (number).
2. Write an if/else if/else block that classifies a numeric score: 90–100 = 'A', 80–89 = 'B', 70–79 = 'C', below 70 = 'F'. Test with score = 85.
- Step 1: Declare the variable. const score = 85;
- Step 2: Write the first condition. if (score >= 90) { console.log('A'); } — 85 >= 90 is false, so skip.
- Step 3: Write the second condition. else if (score >= 80) { console.log('B'); } — 85 >= 80 is true, so this block executes.
- Step 4: The remaining else if and else blocks are skipped because a true condition was already found.
- Step 5: Output is 'B'.
Answer: console.log outputs B.
3. Calculate the tip amount and total bill for a $47.50 meal at an 18% tip rate using JavaScript variables and arithmetic.
- Step 1: Declare the meal cost. const mealCost = 47.50;
- Step 2: Declare the tip rate. const tipRate = 0.18;
- Step 3: Calculate the tip amount. const tip = mealCost * tipRate; → 47.50 × 0.18 = 8.55.
- Step 4: Calculate the total. const total = mealCost + tip; → 47.50 + 8.55 = 56.05.
- Step 5: Log the results. console.log(tip); console.log(total);
Answer: tip = 8.55, total = 56.05.
4. Explain why (0 == false) evaluates to true but (0 === false) evaluates to false.
- Step 1: Evaluate 0 == false using loose equality. JavaScript performs type coercion: the boolean false is converted to the number 0. The comparison becomes 0 == 0, which is true.
- Step 2: Evaluate 0 === false using strict equality. No coercion occurs. The left operand is type number; the right is type boolean. Different types → the result is false immediately.
- Step 3: Conclusion: loose equality hides the type difference; strict equality exposes it.
Answer: (0 == false) is true due to coercion; (0 === false) is false because types differ.
In class: Typed code-along: students follow along as the instructor writes and runs ten short scripts in the browser console covering type coercion edge cases, loose vs. strict equality, and operator precedence — students predict output before each run. · Logic puzzle lab: students complete fifteen progressive coding challenges in a provided JS file (e.g., grade classifier, FizzBuzz variant, simple tip calculator) using only variables, operators, and control flow — no DOM yet. · Error-reading exercise: students are given five scripts each containing a runtime or logical error; they must identify the error type, explain the cause in a comment, and fix the code so it produces the specified output.
Materials: VS Code, Chrome DevTools console, MDN JavaScript Guide (Grammar and types, Control flow chapters), provided challenge file and error-drill file
Check: Auto-graded or instructor-checked output: all 15 logic challenges produce specified console output; all 5 error drills corrected; pass mark 17 of 20 items (85%) correct.
Practice check8
Answer each question, then check it. Nothing is recorded; this is your own practice.
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.