Byte clears out the attic
Variables, let and const, types of values and typeof.
A program remembers things all the time: the user's name, the cart total, whether dark mode is on. That's what variables are for. A variable is a box with a label: the name is on the label, the value is inside. When you need the value, you say the name, and JavaScript takes it out of the box.
const owner = "Byte";
let boxes = 3;
console.log(owner);
console.log(boxes);
boxes = boxes + 2; // two more boxes arrived
console.log(boxes);There are two words for making a box:
- const — the box is taped shut: a value goes in once, and you can't swap it for another;
- let — the box stays open: the value can be replaced, like
boxesabove.
The = sign here doesn't mean "equals" — it means "put into the box": boxes = boxes + 2 reads as "take what's in boxes, add 2 and put it back".
The boxes hold values of different types:
number— numbers:5,-3,98.6;string— strings, text in quotes:"meow";boolean— yes or no:trueandfalse;- undefined — "nothing has been put in yet";
- null — "deliberately empty".
There are compound values too — objects { name: "Byte" } and arrays [1, 2, 3]: boxes that hold other boxes. They get chapters of their own.
console.log(typeof 42);
console.log(typeof "meow");
console.log(typeof true);
let mystery;
console.log(mystery, typeof mystery);
console.log(typeof null);typeof peeks into a box and tells you the type. The last line will surprise you.typeof null is "object". No, that's not a typo. It's a bug from 1995 that has never been fixed — I'll explain why in the next lesson.Types matter because they decide what an operator does. With two numbers, + adds; if at least one value is a string, it glues them together into text.
console.log(2 + 3);
console.log("2" + 3);
console.log("Boxes: " + 5);
console.log(Number("2") + 3);
console.log("5" - 2);const is taped shut, let is open, and typeof is my nose for checking what's inside. Usually it's fish. Type: "fish". Kidding — there's no such type.Pop quiz
Mistakes are fine: keep trying until you find the right answer, and Byte explains why it's right.