Change a value, watch the code run, copy what you need. Every result on this page comes from real JavaScript running in your browser, so what you see here is exactly what your own code will do.
A variable is a box with a name on it. let makes a box you can refill later. const makes a box that is sealed once you fill it. The kind of thing inside is its type, and typeof tells you which type it is.
A string is text in quotes. You can glue strings together with + (concatenation) or drop variables straight into backtick text with ${ } (a template literal, also called interpolation). Template literals are the modern way and much harder to mess up.
+ with any string glues. Every other math sign turns strings into numbers first. Convert on purpose with Number() and String().
Declare a function once, then call it as often as you want. The names in the parentheses of the declaration are parameters (empty slots). The values you hand it when you call it are arguments. return is the chute that sends the answer back out.
JavaScript checks conditions from the top down and runs the first one that is true, then skips the rest. That order matters more than people expect. Drag the score and watch which branch wins.
| Compare | Result |
|---|
== converts types before comparing, which causes surprises. Always use ===.
if (value) run?Green values are truthy and the if block runs. Red values are falsy and it gets skipped. There are only a handful of falsy values, so learn the red ones and everything else is truthy.
An array is a numbered list, and the numbering (the index) starts at 0, not 1. A loop visits every item so you don't write the same line ten times. Change the cart, then step through the loop one pass at a time.
The DOM is the browser's live copy of your HTML, and JavaScript can grab any piece of it and change it. Always two steps. First select an element, then change it. The mini page below is the same one from the intro to the DOM class.
An event is something that happens on the page, like a click or a key press. addEventListener says "when this happens to this element, run this function." The function is handed an event object with details about what happened.
Type any JavaScript and press Run (or Ctrl and Enter together). Everything you console.log shows up on the right, and so does any error with its real message. The Run in scratchpad buttons in Labs 1 to 5 drop their code in here so you can poke at it.
A loop that never ends will freeze this tab. If that happens, close the tab and open the page again.