Course page
Log in

You are watching a free preview. Enroll to open all 25 lessons, track progress and ask the course tutor.

Enroll for $29.99

Section 1: Language foundations

Values, variables and types

Article 12 min Lesson 2 of 25 Preview

Programs work with values. JavaScript has a few primitive types:

  • number: 42, 3.14, also NaN (not a number) and Infinity
  • string: text in quotes, "hello", 'hello' or ` hello `
  • boolean: true or false
  • undefined: a variable that has no value yet
  • null: an intentional "no value"
  • bigint and symbol, which you will rarely need at first

Everything else, including arrays and functions, is an object.

Declaring variables

Use const by default and let when the value must change:

const taxRate = 0.2;
let total = 0;
total = total + 19.99;

const does not make a value unchangeable, it means the variable name cannot be reassigned. You will still see var in older code. Avoid it in new code, because its scoping rules are confusing.

Template literals

Backtick strings can include values and span multiple lines:

const name = "Ana";
const items = 3;
console.log(`${name} has ${items} items in the list`);

Type surprises

JavaScript converts types automatically in some operations, which causes some famous surprises:

"5" + 1   // "51", the number becomes a string
"5" - 1   // 4, the string becomes a number
0.1 + 0.2 // 0.30000000000000004

The last one is not a JavaScript bug. It is how binary floating point numbers work in almost every language. For money, work in whole cents.

Equality

Use strict equality, === and !==. It compares both value and type without converting:

5 === "5"   // false
5 == "5"    // true, after conversion

Loose == has rules that are hard to remember, so most teams avoid it entirely.

Converting input

Values from form fields are always strings. Convert them explicitly:

const amount = Number("42.50");   // 42.5
Number.isNaN(Number("abc"))       // true

Exercise: in the console, create variables for a bill amount and tip percentage, calculate the tip and the total, and print a sentence with a template literal.

← → switch lessons