What an array is
A program often has to handle many related values: the names of friends, the prices in a cart, the ages of a group. Creating one variable per value doesn't scale, and the code can't loop over them. An array stores an ordered list of values under one name. Each value is an element, and the elements keep the order in which you wrote them.
Creating an array
An array literal starts with [, ends with ] and separates the elements with commas:
let sandwich = ["peanut butter", "jelly", "bread"];
console.log(sandwich);
[ 'peanut butter', 'jelly', 'bread' ]
This array has three strings. Node prints strings inside an array with single quotes, and puts spaces just inside the brackets. The variable sandwich lets you use the array later. The number of elements is available as sandwich.length, here 3. An empty array is written [].
Array types
TypeScript adds a type to an array: the element type followed by [].
string[]is an array of strings.number[]is an array of numbers. There is one numeric type,number, for whole numbers and decimals alike.boolean[]is an array of booleans.
You can write the type yourself, or leave it out and let TypeScript infer it from the literal. let sandwich = ["peanut butter", "jelly", "bread"]; is inferred as string[]. Writing the annotation makes the intent explicit and gives clearer errors when the contents are wrong. Once an array has the type string[], adding a number is a compile error:
let fruits: string[] = ["mango", "kiwi", "grapefruit"];
fruits.push(5);
error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.
This check exists only at compile time. The annotation disappears in the JavaScript that tsc writes. Because tsc still writes the file after reporting an error, a program with such a mistake would run, and the number would end up in the array. Treat compiler errors as problems to fix, even when the program appears to run.
Mixed arrays
JavaScript arrays can mix types, and so can TypeScript's. For let myArray = ["Hello world!", 32, false];, TypeScript infers an array whose elements are a string, a number or a boolean, written (string | number | boolean)[]. Note that the boolean literal is lowercase: false, not False. Mixed arrays are legal, but most arrays you write hold one kind of value, because values that are part of the same family are easier to process together. When you do need a fixed shape, such as a string followed by a number, TypeScript has tuple types like [string, number], which are a separate topic.
Gotchas
- Brackets after the type, not before. The type is
number[]. An annotation like[]numberis a syntax error. - Commas, not spaces. Elements are separated by commas. A missing comma is a syntax error.
constdoes not freeze the contents. Withconst list = [1, 2]you can't reassignlist, but you can still change what is inside it. That comes up in the later lessons.- Arrays are objects.
typeof sandwichis"object". UseArray.isArray(sandwich)to ask whether something is an array.
The lesson's exercise
The exercise has two declarations.
- Create
fruits. Declare astring[]namedfruitsholding"mango","kiwi"and"grapefruit". The annotation: string[]tells TypeScript that every element is a string. - Create
ages. Declare anumber[]namedagesholding14,32,50and21. All four ages are now managed as one unit.
let fruits: string[] = ["mango", "kiwi", "grapefruit"];
let ages: number[] = [14, 32, 50, 21];
The exercise prints nothing. The two arrays are used in the next lessons, where you read and change their elements.
Key takeaways
- An array stores an ordered list of values in one variable, written with square brackets and commas.
- The type of an array is the element type followed by
[]:string[],number[]. - TypeScript infers the type from the literal, and checks it at compile time only.
- Arrays can mix types, but most of the time the elements share one type.
- The size of an array is its
lengthproperty.