Arrays, objects & functions

A quick overview of how arrays, objects, and functions work within JavaScript.

Go fullscreen: ⌃⌥F

Arrays, objects & functions

Arrays

Collections of numbered things—in a specific order

Can put anything you want in an array: strings, numbers, arrays, objects, functions

Each item is accessed by a number—its index

Denoted with square brackets []

JavaScript
var trees = ['Maple', 'Oak', 'Birch', 'Pine'];  // Square brackets

console.log(trees[0]);                          // Get the first item
document.write('<h1>' + trees[2] + '</h1>');    // Put the third item into an <h1>

trees.push('Spruce');                           // Add a new item
console.log(trees.length);                      // Count the number of items

document.write('<ul>');
trees.forEach(function (item) {                 // Loop over every item in array
  document.write('<li>' + item + '</li>');
});
document.write('</ul>');

Objects

Collections of named things—order is irrelevant

Can put anything you want in an object: strings, numbers, arrays, objects, functions

Each item is accessed by its name

Denoted with curly braces {}

JavaScript
var latLong = {                                 // Curly braces
  latitude: 45.416667,
  longitude: -75.7
};

var dinos = [{                                  // Objects inside an array
    name: 'Apatosaurus',
    diet: 'Herbivore'
  }, {
    name: 'Microraptor',
    diet: 'Carnivore'
}];

document.write(latLong.longitude);              // Get the `longitude` item

// Write a sentence using the second object in the array
console.log('The ' + dinos[1].name ' is a feathered ' + dinos[1].diet + '.');

Functions

A chunk of reusable code—stored inside a variable

Can accept information to change its functionality

Can send information back to you when executed

Denoted with round brackets ()

JavaScript
var sayHello = function () {                    // Basic function
  console.log('Hello!');
};

var writeH1 = function (text) {                 // Accepts an argument
  document.write('<h1>' + text + '</h1>');
};

var getImg = function (src, alt) {              // Accepts two arguments and returns
  return '<img src="' + src + '" alt="' + alt + '">';
}

sayHello();
writeH1('Amaze-balls!');

// Return values can be stored in variables
var img = getImg('octopus.jpg', 'A big, goopy cephalopod');
document.write();
JavaScript
var document = {
  write: function (text) {
    // Do whatever with the `text` variable
  }
}

Where are they used?

  • Arrays — getting HTML elements
  • Objects — each single HTML element
  • Functions — whenever a user clicks
Start

Arrays, objects & functions

A quick overview of how arrays, objects, and functions work within JavaScript.