VICO 3420/5900

JavaScript + Data

Exercise 1: Functions and For Loops

w3schools: Functions w3schools: For Loops

Functions

Functions are the bread and butter of JavaScript programming. A function is a block of code that will perform a particular task. A function is executed when "something" calls it.

The concept of wrapping a piece of code in a value has many uses. It gives us a way to structure larger programs, to reduce repetition, to associate names with subprograms, and to isolate these subprograms from each other.

// simple function
let simple = function () {
  console.log('It worked!');
}

// same as...
function simple() {
  console.log('It worked!');
}

For Loops

For Loops can execute a block of code a number of times. They are a great way to work with arrays of data!

// simple 'for loop' function
let looper = function () {
  for (let i = 0; i < 10; i++) {
    console.log(i);
  }
};
Exercise 1

Open this HTML file in Visual Studio Code, scroll down to the scripts at the end of the body and 'call' each function to see exactly what it does.

To see your code changes in a browser, open this HTML file in Chrome and use the inspector console.

After you feel like you really understand what each example function does, write a new function on your own:

  • Name your function 'myDataLooper'
  • Head: 'Top 5 States for Retirees'
  • Subhead: 'By Pct. of Population Over 60'
  • Include just these properties from the data collection:
    • Each state's 'rank'
    • Each state's 'name'
    • Each state's 'pop60'
  • Enable the 'Test button' below to call your new function

Test button

Your scripted HTML will go in here.