Understand JavaScript statements (variables, operators, functions)
21 Programming for the web
Variables – Your Digital Storage Boxes
Variables are like digital storage boxes that hold data. Think of them as labeled jars where you can keep different kinds of items – numbers, words, or even whole lists. In JavaScript you can create a variable with let, const or var (the last one is older, so we’ll focus on let and const).
let age = 15;– age can change later.const PI = 3.14159;– PI stays the same.- Variable names can include letters, numbers,
$and_but must start with a letter,$or_.
You can update a variable: age = age + 1; – now age becomes 16. This is like moving a toy from one box to another and changing its label.
Operators – The Digital Toolbox
Operators are the tools that let you manipulate data. They can add, subtract, compare, or even combine strings. Below is a quick reference table.
| Operator | Meaning | Example |
|---|---|---|
| + | Addition / Concatenation | 5 + 3 = 8 or 'Hi' + ' there' = 'Hi there' |
| - | Subtraction | 10 - 4 = 6 |
| * | Multiplication | 7 * 6 = 42 |
| / | Division | 20 / 4 = 5 |
| % | Modulus (remainder) | 10 % 3 = 1 |
| === | Strict equality (value & type) | 5 === 5 ✓ |
| !== | Strict inequality | 5 !== '5' ✓ |
Remember: Operator precedence decides the order of operations. Use parentheses () to group calculations, just like you’d group ingredients in a recipe.
Functions – Your Reusable Recipes
Functions are like recipes that you can reuse whenever you need them. They take inputs (called parameters), do something, and may give you a result (return value). A function looks like this:
function greet(name) {
return 'Hello, ' + name + '!';
}
Calling the function: greet('Alice'); gives 'Hello, Alice!'. 🎉
- Define the function with
functionkeyword. - Give it a name that describes what it does.
- List any parameters inside parentheses.
- Write the code block inside curly braces
{}. - Use
returnto send back a value.
You can also create anonymous functions (without a name) and assign them to variables:
const square = function(x) {
return x * x;
};
Now square(4) returns 16. 🔢
Key points:
- Functions keep your code organized and reusable.
- They can be nested – a function inside another function.
- JavaScript functions are first-class citizens, meaning you can pass them around like any other value.
Revision
Log in to practice.