We use square brackets to create an array:
const array = []; // empty array
console.log(array);
Array value types
We can put any values inside the array, separated by commas:
const numbers = [1, 2, 3, 4];
console.log(numbers);
const strings = ['this', 'array', 'contains', 'strings'];
console.log(strings);
const mixed = ['this', 1, 'has', 2, 'numbers'];
console.log(mixed);
Arrays from strings
There are a few other ways to create arrays.
We can split the characters in a string into an array:
const letters = 'Another String'.split();
console.log(letters);
Use const for arrays
We should always use const
to create an array.
We can still add and remove values from the array if we use const
, but we can't accidentally assign another array to the variable.