Javascript built-in data structure - Array, part 1/3

This tutorial is a part of the Learn everything about Javascript in one course.

Javascript built-in data structure - Array, part 1/3 (current) part 2/3, part 3/3.

What is array and what it's used for?

  • Array is an ordered collection of information.
  • Each information is called an element.
  • Each element can be a value of anything, such us: number, string, array ...
  • Each element has a numbered position called index.
  • Index starts with 0 and is used to access a single element in array.
const arr = ['a', 'b', 'c', 1, 2, 3, ] // An array with 6 elements
              ^    ^              ^
              |    |              |
              |    |              last element, index 5, value 3
              |    | ... 
              |    |
              |    second element, index 1, value 'b'
              |
              first element, index 0, value 'a'

Array is used for representing a collection of information. It's one of the most important and frequently used data structures in Javascript.

Ways to create an array

  1. Literal declaration
  2. With Array constructor
array.js
// Ways to create an array
const arr0 = [] // literal, empty array
console.log(arr0) // []

const arr1 = ['a', 'b', 'c', 1 ,2 , 3] // literal, with values
console.log(arr1) // [ 'a', 'b', 'c', 1, 2, 3 ]

const arr2 = new Array(3) // with constructor, specify length 3
console.log(arr2) // [ <3 empty items> ]

const arr3 = new Array('a', 'b', 'c', 1 ,2 , 3) // with constructor and values
console.log(arr3) // [ 'a', 'b', 'c', 1, 2, 3 ]

const arr4 = new Array(4).fill(0) // length 4, pre-filled with 0
console.log(arr4) // [ 0, 0, 0, 0 ]

Array global object

Array global object contains all properties and methods that any newly created array variable will inherit. Think of it as a blueprint.

Javascript constructor

Constructor is a class or object function that hold a blueprint to create new variable with a same set of properties and methods. For example, all Javascript global objects we learnt so far (Number, String, RegExp, Array) are constructors. We will learn to create custom Constructor and Class in later lectures.

Constructor name is conventionally starts with an uppercased character whereas variable name is conventionally starts with a lowercased character.

Syntax to create a variable using constructor const|let|var variableName = new Constructor().

Keyword new is an operator. The whole syntax is saying: create a new variable using Constructor blueprint and assign it to identifer called variableName.

array.js
// Array global object and its creating a variable using constructor
const myArray = new Array(1,2,3)
console.log(myArray) // [ 1, 2, 3 ]

Check if a variable is an array, method isArray()

Syntax: Array.isArray(variable)

Input Output Time complexity (worst)
(variable) true if variable is an array
false if variable is NOT an array
O(1)
array.js
// Check if a variable is an array, method isArray
console.log(Array.isArray('abc')) // false
console.log(Array.isArray([])) // true

Fill array with given value, method fill()

Syntax: array.fill(value[, start[, end]])

value is to fill array with. start and end are array indices.

Note: We use [ ... ] in syntax formula to refer to optional inputs. Optional inputs are both can and can NOT be provided.

Input Output Time complexity (worst)
(value) all array element filled with value O(n), n is array length
(value, start) element from start index to the rest are filled with value O(n), n is array length
(value, start, end) element from start index to end index are filled with value O(end - start)
array.js
// Fill array with given value, method fill
const arr5 = new Array(5)
console.log(arr5.fill(0)) // [ 0, 0, 0, 0, 0 ]
console.log(arr5.fill(1, 1)) // [ 0, 1, 1, 1, 1 ]
console.log(arr5.fill(2, 2, 5)) // [ 0, 1, 2, 2, 2 ]

Presentation of matrix with array

array.js
// Presentation of matrix with array

// 2 dimentions nxn matrix
const matrix3x3 = [[1,2,3], [4,5,6], [7,8,9]] // 3x3 matrix
console.log(matrix3x3) // [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
/*
  row 0 -->    [ [ 1, 2, 3 ],
  row 1 -->      [ 4, 5, 6 ],
  row 2 -->      [ 7, 8, 9 ] ]
                   ^  ^  ^
                   |  |  |
                   |  |  |
                   |  |  column 2
                   |  column 1
                   column 0
*/
// access to row 1, column 2 element
console.log(matrix3x3[1][2]) // 6,

Fun fact: the information used to display the screen you are looking at is stored by a 3x3x3 matrix. And we'll learn about it now.

Use array to contain information of screen display

How your laptop/TV screen (actually all screens) works:

  • your screen is made of tiny spots called pixel.
  • A pixel has 3 tiny light bulbs, each can only shine: RED, GREEN, BLUE.
  • Each light bulb brightness can be adjusted from (darkest) 0 to 255 (brightest)
  • A pixel also has a master nob called OPACITY to dim all 3 bulbs (no light) 0 - 225 (full light).

Display a pixel: pixel = [ RED, GREEN, BLUE, OPACITY]. Each element value is integer from 0 to 255.

There are 2 ways to represent a screen data, let say our screen has 2x2 resolution:

  1. An array of consecutive 4 elements
  2. A 2x2x4 array matrix
array.js
// Use array to contain information of screen display

// 2x2 screen information represented by an array of consecutive 4 elements

const screen1 = [255, 0, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255]
/*               ^            ^  ^            ^  ^            ^  ^            ^
                 |            |  |            |  |            |  |            |
                 |            |  |            |  |            |  |____________|
                 |            |  |            |  |            |        |
                 |            |  |            |  |____________|     4th pixel
                 |            |  |            |        |
                 |            |  |____________|     3rd pixel
                 |            |         |
                 |            |     2nd pixel, next 4 elements and so on...
                 |            | 
                 |____________| 
                       |
                   1st pixel, first 4 elements
*/


// 2x2 screen information represented by a 2x2x4 matrix
const creen2x2x4 = [ [[255, 0, 0, 255], [255, 0, 0, 255]], 
                     [[255, 0, 0, 255], [255, 0, 0, 255]] ] // 2x2x3 matrix
console.log(creen2x2x4)
/*
  row 0 -->    [ [[255, 0, 0, 255], [255, 0, 0, 255]], 
  row 0 -->      [[255, 0, 0, 255], [255, 0, 0, 255]] ]
                  ^                 ^
                  |                 |
                  |                 |
                  |                 |
                  |                 column 1
                  column 0
*/
// access to pixel at row 0, column 0
console.log(creen2x2x4[0][0]) // [ 255, 0, 0, 255 ]
/*
RED: 255
GREEN: 0
BLUE: 0
OPACITY: 255
=> this pixel display pure RED
*/

Open this html file comes along with the lecture in your browser and tweak to discover more about screen and array.

Get an element in array using index

array.js
// Get an element in array using index
const arr6 = [1,2, [3, 'a', ['b', 'c', 4]]] // mixed array
console.log(arr6[1]) // 2
console.log(arr6[2][1]) // a
// explanation: `arr6[2]` = [3, 'a', ['b', 'c', 4]]
//              `arr6[2][1]` = [3, 'a', ['b', 'c', 4]][1] = 'a'
console.log(arr6[2][2][2]) // 4
// explanation: `arr6[2]` = [3, 'a', ['b', 'c', 4]]
//              `arr6[2][2]` = ['b', 'c', 4]
//              `arr6[2][2][2]` = ['b', 'c', 4][2] = 4

Modify an element in array

Simply reassign element in array to modify it.

array.js
// Modify an element in array
const arr7 = [1, 2, 'a', 'b']
arr7[1] = arr7[1] + 1
console.log(arr7) // [ 1, 3, 'a', 'b' ]
arr7[2] = arr7[2] + ' and c'
console.log(arr7) // [ 1, 3, 'a and c', 'b' ]

Summary

  • Array has a lot of built-in methods. They are not there to overwhelm you. They are there so you can use them when you need to. And you will.
  • Remember what built-in methods can do while read/watch the lectures, syntax will become your muscle memory as you practice.

Continue to learn about array part 2/3.