Lesson 1 of 6 · 5 min

Values and variables

Numbers, strings, booleans, null and undefined, let and const, template literals, and why you should always compare with ===.

On this page
  1. Adding JavaScript to a page
  2. Variables
  3. Types of values
  4. Strings
  5. Numbers and maths
  6. Comparisons: use ===
  7. Truthy and falsy
  8. Conditions
  9. Loops
  10. Try it

Adding JavaScript to a page

Put your code in a file and load it at the end of the <head> with defer, so it runs after the HTML is ready:

<script src="app.js" defer></script>

Use console.log() to print values to the developer tools console while you learn:

console.log("Hello from app.js")

Variables

A variable is a name for a value.

const siteName = "Khan Waseem"
let visits = 0
visits = visits + 1
  • const can't be reassigned. Use it by default.
  • let can be reassigned. Use it when the value really changes, such as a counter.
  • var is the old way. It has confusing scoping rules; you'll see it in older code, but don't write it.

Names are case-sensitive and usually written in camelCase.

Types of values

const count = 42              // number (integers and decimals are the same type)
const price = 19.99
const name = "Asha"           // string
const isAdmin = false         // boolean
const nothing = null          // deliberately empty
let notSet                    // undefined: declared, no value yet
const big = 9007199254740993n // bigint, for very large integers

typeof tells you the type:

typeof 42        // "number"
typeof "hi"      // "string"
typeof true      // "boolean"
typeof undefined // "undefined"
typeof null      // "object" (a famous old bug; null is not really an object)

Strings

Use single quotes, double quotes, or backticks. Backticks make template literals, which can include values and span lines:

const user = "Asha"
const lessons = 7
const message = `Hi ${user}, you have ${lessons} lessons left.`

message.length          // number of characters
message.toUpperCase()
message.includes("Asha") // true
"  padded  ".trim()      // "padded"
"a,b,c".split(",")       // ["a", "b", "c"]

Numbers and maths

10 / 3                 // 3.3333333333333335
Math.round(10 / 3)     // 3
(10 / 3).toFixed(2)    // "3.33" (a string)
0.1 + 0.2              // 0.30000000000000004
Number("42")           // 42
Number("abc")          // NaN, "not a number"

Decimal maths is approximate in every language that uses floating point numbers. For money, work in whole paise or cents.

Comparisons: use ===

5 === 5        // true
5 === "5"      // false: different types
5 == "5"       // true: == converts types first, which causes surprises
0 == ""        // true (!)

Always use === and !==. They compare without converting.

Truthy and falsy

In an if, every value counts as true or false. These six are falsy: false, 0, "", null, undefined, NaN. Everything else is truthy, including "0", [] and {}.

const name = ""
if (name) {
  console.log(`Hello, ${name}`)
} else {
  console.log("Hello, stranger")
}

Conditions

const score = 72

if (score >= 90) {
  console.log("Excellent")
} else if (score >= 60) {
  console.log("Pass")
} else {
  console.log("Try again")
}

const label = score >= 60 ? "pass" : "fail"  // the ternary operator

&& (and), || (or) and ! (not) combine conditions. ?? picks a fallback only when the left side is null or undefined:

const city = user.city ?? "Unknown"

Loops

for (let i = 1; i <= 3; i++) {
  console.log(`Lesson ${i}`)
}

let n = 3
while (n > 0) {
  console.log(n)
  n--
}

Try it

In the console, create const firstName and const lastName, then log a greeting with a template literal. Compare "10" == 10 and "10" === 10, and explain the difference to yourself in one sentence.

More from JavaScript Crash Course