Printing things out
Before anything else, you need a way to see what your code is doing. In JavaScript that's console.log(). Whatever you put between the brackets gets printed.
console.log("Hello");
console.log(2 + 3);Hello 5
Text goes inside quotes. Numbers don't. JavaScript works out 2 + 3 first and prints the answer.
Making a variable with let
let makes a new variable. The = sign means "store this value in that name". It doesn't mean "is equal to" like it does in maths.
let age = 14;
console.log(age);
age = 15;
console.log(age);14 15
You only write let the first time. After that you use the name on its own, and you can store a new value in it whenever you want.
Try it
What does this print?
let x = 10;
x = x - 4;
console.log(x);
const for values that don't change
const works like let, except you can't store a new value in it later. Use it for things that should stay the same.
const name = "Sam";
name = "Alex";TypeError: Assignment to constant variable.
A good habit is to use const by default and only switch to let when you know the value will change.
Numbers and strings
Text in quotes is called a string. Strings and numbers look similar but behave differently. + adds numbers together, but it joins strings end to end.
console.log(2 + 3);
console.log("2" + "3");
console.log("2" + 3);5 23 23
In the last line, one side is a string, so JavaScript turns the 3 into text and joins them. If you're not sure what kind of value you have, typeof tells you.
console.log(typeof 42);
console.log(typeof "42");number string
Try it
What does this print?
console.log("5" + 5);
Putting values inside text
To mix variables into a sentence, use backticks instead of quotes and put the variable inside ${ }. This is called a template literal.
const name = "Sam";
const points = 30;
console.log(`${name} has ${points} points`);Sam has 30 points
Try it
What happens when this runs?
const score = 3;
score = 4;
Common mistakes
let name = Sam; makes JavaScript look for a variable called Sam. You get ReferenceError: Sam is not defined. Text needs quotes.
let x = 1; followed by let x = 2; gives a SyntaxError. Use let once, then just x = 2.
If you console.log(total) before the line that creates total, you get a ReferenceError. Code runs top to bottom.
Recap
- console.log() prints a value so you can see it.
- let makes a variable you can change. const makes one you can't.
- = stores a value. It does not check if two things are equal.
- + adds numbers but joins strings.