Skip to content
Programming contents

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 =:

JavaScript
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:

JavaScript
let age = 30;
age = age + 1;
console.log(age);
Console
31

let only goes the first time, when you create it. After that, the name is enough.

Types

PseudocodeJavaScriptExamples
Numbernumber30, 9.99, -4
Textstring"Ana" or 'Ana'
Booleanbooleantrue, false

typeof tells you a value's type:

JavaScript
console.log(typeof 30);
console.log(typeof "Ana");
console.log(typeof true);
Console
number
string
boolean

Operators

+, -, * and /, like in pseudocode. And a new one: %, the remainder of a division.

JavaScript
console.log(10 % 3);
console.log(8 % 2);
Console
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:

JavaScript
console.log(2 + 3);
console.log("2" + "3");
console.log("2" + 3);
Console
5
23
23

prompt() always returns text, even if you type a number. To calculate with it, convert it with Number():

JavaScript
const text = prompt("A number:");
const n = Number(text);
console.log(n + 1);

Try it

Exercise

Ask for two numbers with prompt() and write their sum.

Show the solution
JavaScript
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

  • const for what doesn't change, let for what does.
  • = stores a value.
  • Three types: number, string and boolean.
  • + with text joins; to calculate with what prompt() returns, use Number().