Lesson 1.8: Variables and types in JavaScript
The named boxes from 1.3, now in JavaScript: how to create them, which types exist and a trap worth knowing early.
The idea
In JavaScript, you create a variable with let or const, and give it a value with =:
let age = 30;
const name = "Ana";
let: the value can change.const: the value never changes.
Use const by default, and let only if you're going to change it.
= doesn't mean "equals"
= stores, like the arrow ← in pseudocode:
let age = 30;
age = age + 1;
console.log(age);
31
let only goes the first time, when you create it. After that, the name is enough.
Types
| Pseudocode | JavaScript | Examples |
|---|---|---|
| Number | number | 30, 9.99, -4 |
| Text | string | "Ana" or 'Ana' |
| Boolean | boolean | true, false |
typeof tells you a value's type:
console.log(typeof 30);
console.log(typeof "Ana");
console.log(typeof true);
number
string
boolean
Operators
+, -, * and /, like in pseudocode. And a new one: %, the remainder of a division.
console.log(10 % 3);
console.log(8 % 2);
1
0
If n % 2 is 0, n is even.
The + trap
With numbers, it adds. With text, it joins. And if you mix them, text wins:
console.log(2 + 3);
console.log("2" + "3");
console.log("2" + 3);
5
23
23
prompt() always returns text, even if you type a number. To calculate with it, convert it with Number():
const text = prompt("A number:");
const n = Number(text);
console.log(n + 1);
Try it
Ask for two numbers with prompt() and write their sum.
Show the solution
const a = Number(prompt("First number:"));
const b = Number(prompt("Second number:"));
console.log("The sum is " + (a + b));
- Without
Number(), 2 and 3 would give "23". - The brackets in
(a + b)make it add first and then join the result to the text.
Summary
constfor what doesn't change,letfor what does.=stores a value.- Three types:
number,stringandboolean. +with text joins; to calculate with whatprompt()returns, useNumber().