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
});
PieceWhat 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

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!";
}

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)

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