Chapter 13

JavaScript Variables and Data Types

Store values in variables and understand strings, numbers, booleans, arrays and objects.

JavaScript Variables and Data Types

A variable is a named container for a value. Understanding how to declare variables and what kinds of values they hold is the base for everything else in JavaScript.

Declaring variables

Use let for a value that may change and const for one that should not be reassigned. Avoid the old var keyword. Give variables clear, descriptive names.

let score = 0;
score = score + 5;      // allowed, let can change

const pi = 3.14159;
// pi = 3; would cause an error

A const cannot be reassigned, but if it holds an object or array you can still change what is inside it.

The main data types

  • String: text in single or double quotes, such as 'hello'.
  • Number: any number, whole or decimal, such as 42 or 3.5.
  • Boolean: true or false.
  • Undefined: a variable declared but not given a value.
  • Null: a deliberate empty value.
let name = 'Aisha';     // string
let age = 17;           // number
let isMember = true;    // boolean
let notSet;             // undefined

You can check a value type with the typeof operator, for example typeof age gives 'number'.

Arrays and objects

An array is an ordered list written with square brackets. Items are numbered from zero, so the first item is at index 0.

let fruits = ['apple', 'pear', 'mango'];
console.log(fruits[0]);      // apple
console.log(fruits.length);  // 3

An object groups related values as key and value pairs inside curly braces.

let student = {
  name: 'Aisha',
  age: 17
};
console.log(student.name);   // Aisha

Type conversion

Values read from a form are always strings. Convert text to a number with Number('42') or the other way with String(42). Adding a number to a string joins them as text instead of adding, a common source of bugs.

Remember: Reach for const by default and switch to let only when the value must change. Arrays start counting at index zero, so the first item is [0], not [1].

Stuck on this topic? A verified JomKelas tutor can walk you through it.

Find a verified tutor