Reference article · Programming
Fundamentals: variables, conditions and loops
Programming means describing steps a computer can execute. Start by separating a problem into inputs, operations and a result you can check. Run these examples in your browser console.
Variables and data types
A variable associates a name with a value. JavaScript let allows reassignment; const prevents reassigning that reference. Numbers support calculations, strings represent text and booleans express true or false. The string "12" and the number 12 have different types.
Conditions: choosing a path
if evaluates an expression to select a block; else supplies an alternative. Strict equality === compares without converting operands to another type, so 12 === "12" is false. Choose names that explain what you are checking.
const stock = 3;
if (stock > 0) {
console.log("Available");
} else {
console.log("Sold out");
}Loops: repeating with a limit
for...of visits the values in a list. With while, ensure the condition can eventually become false; otherwise the program can enter an infinite loop.
const points = [4, 7, 2];
let total = 0;
for (const value of points) {
total += value;
}
console.log(total); // 13Reading the example
total starts at zero and accumulates one value per iteration. Check the output manually: 4 + 7 + 2 is 13. Resetting total inside the loop would discard the previous additions.
Practice and verification
- Replace the list with [5, 0, 5] and predict the output first.
- Try an empty list: the total should remain zero.
- Add a condition to include only positive values, then try a negative number.
References
Related articles
- Semantic HTML and page structure
- CSS: box model, Flexbox and Grid
- JavaScript: functions, parameters and scope
- JavaScript: arrays, objects and data transformations
- DOM and events: connect JavaScript to HTML
- Promises, async/await and fetch requests
- HTTP and web APIs: requests, responses and status codes
- JSON: format, parsing and data validation
- Git: changes, commits, branches and remotes
- Node.js and npm: project scripts and dependencies
- Debugging and tests: finding and checking errors
- Colour formats: HEX, RGB and HSL
- UUID identifiers
- Random values in JavaScript
