Working with Data in JavaScript

@elliotecweb

What's Data?

  • Dictionary definition: "Facts and statistics collected together for reference or analysis."
  • Any information stored, manipulated, and displayed on the web is data

 

Data Structures

  • Special formats for organizing and storing data so that we can manipulate it with our code
  • Many different data structure types, the main ones we work with in JS are Objects and Arrays

Arrays

  • They're just lists of data
  • Can contain any data type JS understands (numbers, booleans, strings, objects and even additional arrays)
  • Index is the position of the element in the array (count starts at zero)
var emptyArray = [];

var oddNumbers = [1, 3, 5, 7, 9];

var nestedArrays = [[1, "Bob", false], [true, 7, "words"], ["data", 2, 5]];

var names = ["Mike", "Tiffany", "Dave", "Louise"];

names.indexOf("Dave"); // 2

oddNumbers.push(11); // oddNumbers -> [1, 3, 5, 7, 9, 11]

Objects

  • Key-Value pairs of data
    • Keys (properties) are kinda like variables, they are a reference that points to the actual value, and remain constant across similar objects
    • Values can contain any data type (numbers, booleans, strings, objects), and differ per individual object
var emptyObject = {};

var car = {make: "Toyota", model: "Prius", color: "Tangerine"};

var cars = [{make: "Toyota", model: "Prius", color: "Tangerine"}, 
            {make: "Subaru", model: "Outback", color: "Forest Green"}]

car.owner = "Mike"; // car -> {make: "Toyota", model: "Prius", color: "Tangerine", owner: "Mike"}

console.log(cars[1].model); // "Outback"

Algorithms

  • A repeatable set of instructions followed by a program to do something, like calculations
  • Used to do the same thing to different pieces of data repeatedly
  • For loops, while loops, repeated functions with boolean logic, map/reduce, can all be algorithms
  • We will focus on for loops here

For loops

  • Repeated set of instructions that is run until specified conditions are met
  • Used to iterate through data structures to do things with the data therein
for (i = 0; i <= 10; i++){
    console.log(i);
} // -> 1 2 3 4 5 6 7 8 9 10

var names = ["Mike", "Tiffany", "Dave", "Louise"];

for (i = 0; i < names.length; i++){
    console.log(names[i]);
} // -> Mike Tiffany Dave Louise

var car = {make: "Toyota", model: "Prius", color: "Tangerine"};

for (key in car){
    if (car.hasOwnProperty(key)){
        console.log(car[key]);
    }
} // -> Toyota Prius Tangerine

Demo time!

Thank You!

Questions?

@elliotecweb

http://elliotec.com