Reference · module 1
First lines
Everything this module explains, on one page.
console.log
Make a program print something, and know why the quotes are there.
- console.log("Hello") prints Hello to the console. console is an object, log is what it can do, and the brackets hold what to print. Almost every call in JavaScript looks like this.
- Text goes in quotes: "Hello", 'Hello' and `Hello` are all strings. Without quotes Hello is a variable name, and JavaScript stops with a ReferenceError when it cannot find it.
- A program runs top to bottom. Each console.log prints its own line, in the order the lines are written. The semicolon at the end of a line is optional, but most code keeps it.
The mistake you are about to make
console.log(Hello)
console.log("Hello")
The word inside looks like plain text. Without quotes Hello is a variable name: JavaScript looks for it and stops with ReferenceError: Hello is not defined.
Numbers and strings
Tell a number from text, and predict what + does with them.
- JavaScript has numbers and strings. 7 is a number you can calculate with; "7" is text that happens to contain a digit. The quotes decide which one it is, not what is inside.
- The + sign adds numbers but joins strings. 2 + 3 is 5, "2" + "3" is "23", and if either side is a string, JavaScript turns the other into a string too: "2" + 3 is "23".
- typeof tells you what a value is: typeof 7 is "number", typeof "7" is "string". Number("7") turns text into a number, and String(7) turns a number into text.
The mistake you are about to make
"2" + 3
Number("2") + 3
It feels like the language will see a digit as a digit. With a string on one side + joins instead of adding, and there is no error — just "23" instead of 5.
let and const
Store values under names, and pick let or const on purpose.
- let count = 3; creates a variable named count holding 3. Later you can write count = 4; without let, and the same variable now holds 4.
- const name = "Ana"; creates a variable that cannot be reassigned. Trying name = "Bo"; stops the program with TypeError: Assignment to constant variable.
- Use const by default and let only when the value really changes, like a counter. A reader then sees at a glance which names stay put. The old var still works, but modern code avoids it.
The mistake you are about to make
const total = 0; total = total + 5;
let total = 0; total = total + 5;
const sounds like it is only for constants such as pi. It forbids reassigning the name, so any counter or running total declared with const stops with a TypeError.