Reference
โก JavaScript Cheat Sheet
The electricity of the house. Print me out!
Where it lives
<script>
...your JavaScript...
</script> <!-- at the END of <body>, after your HTML bricks -->
Why at the end? The browser reads top-to-bottom โ the bricks must exist BEFORE the script tries to find them.
The magic 3-line spell
const btn = document.getElementById("buy"); // 1. find the brick
btn.addEventListener("click", function () { // 2. when clicked...
document.getElementById("msg").textContent = "๐ Thanks!"; // 3. ...do this
});
| Piece | What it means |
|---|---|
const btn = ... | Make a name (btn) for something, so you can use it later |
document.getElementById("buy") | Find the ONE brick with id="buy" |
addEventListener("click", ...) | "When this gets clicked, run my function" |
function () { ... } | A recipe of steps, waiting to be run |
el.textContent = "..." | Replace the words inside a brick |
el.style.backgroundColor = "gold" | Change CSS from JavaScript |
Memory boxes (variables)
const price = 5; // a box that never changes
let coins = 0; // a box you can refill
const name = "Robo"; // quotes = words (a string)
coins = coins + 1; // refill: old value + 1
"Price: " + price // gluing words and numbers
5 + 5is10(math), but"5" + 5is"55"(gluing!). Quotes decide.
Decisions (if / else)
if (coins >= 10) { // ask a question
msg.textContent = "Rich!";
} else if (coins === 1) { // another question
msg.textContent = "One coin.";
} else { // everything else
msg.textContent = "Keep clicking!";
}
=PUTS a value in a box.===ASKS "are these equal?". One changes, three checks!- Comparers:
===equal,>bigger,<smaller,>=bigger-or-equal.
Functions (your own spells)
function cheer(name) { // DEFINE the spell (nothing happens yet)
return "Go " + name + "!"; // return = hand the answer back
}
cheer("Robo Sneakers"); // CAST the spell (now it happens)
- Defining is writing the recipe; calling is cooking it. A function that's never called does nothing.
- Forgot
return? You getundefinedโ "the box came back empty."
Lists & loops
const features = ["fast", "cool", "cheap"]; // a train of boxes
features[0] // "fast" โ counting starts at ZERO!
features.length // 3
let html = "";
for (const f of features) { // for each thing in the train...
html = html + "<li>" + f + "</li>";
}
list.innerHTML = html; // innerHTML reads the words as HTML bricks
Sneaky facts
- If the button does nothing: the id in
getElementById("...")probably doesn't match the id in the HTML. Letter for letter! - JavaScript DOES show errors โ but secretly. Right-click the page โ Inspect โ Console to see red error messages. Real engineers live in that console.
"click"must be spelled exactly โ"clik"listens for an event that never happens.