Arrays

  • Javascript has a special type of object called an array.
  • Arrays are objects that store lists of data values.
  • Array are indexed by integers. The integer that represents a particular item is called an index. Basically it just means the position in the list.
  • After creation, values may be retrieved or added using []

.

var names = ["Jim", "Jimmy", "Jill"];
log( names[1] );

names[2] = "Jan";
log( names );

Iterating Over Arrays

Arrays have a built-in property called length. The length property will always equal the number of objects in the array.

var names = ["Jim", "Jimmy", "Jill"];

log( names );
log( names.length );

The length property is useful when you want to iterate over each item in the array.

var numOfNames = names.length;
for (var i=0; i < numOfNames; i++) {
    log( names[i] );
}

Dictionaries

  • Dictionaries (like arrays) also store data values.
  • Instead of indexing by integers, dictionaries index by strings. We call those strings keys.
  • The key can be any string (including the empty string).
  • The value can be anything that can be stored in a variable: number, string, boolean, null, object, array, function, regular expression.
  • Each key corresponds to one value.

Sometimes dictionaries are also called key-value stores or hash maps.

Dictionaries

The simplist way to make a dictionary is using the object literal syntax.

var cat = {
    name: 'sprinkles',
    age: 2,
    gender: 'female'
};

Surprise!

In Javascript, dictionaries are just objects.

Key Names

  • You can actually have keys that aren't valid variable identifiers!
  • To do this when initializing an object, use quotes around your key name.

.

var person = {
    age: 24,
    "first-name": "Joe",
    "last-name": "Shmoe"
};

[] Notation

  • The . operator that we used for accessing object properties earlier only works if the property name (aka key) is a valid variable identifier.
  • To access or set properties whose names are not valid variable identifiers, we use the square bracket syntax:

.

var person = {};
person["age"] = 24;
person["first-name"] = "Joe";
person["last-name"] = "Shmoe";

log( person["first-name"] );

This is similar to the [] syntax we use with arrays.

Note: The . notation is preferred when you can use it (i.e. the key is a valid identifier)

[] Notation

One other nifty use of [] when dealing with dictionaries:

var person = {
    age: 24,
    "first-name": "Joe",
    "last-name": "Shmoe"
};

var nameKey = "first-name";

log( person[nameKey] );

This is particularly useful on the next slide...

For In Loop

  • There is a special looping construct for objects that allows you to iterate over their properties.
  • It is called a for in loop

The for in loop looks like this:

var shape = { width: 25, height: 50 };
for (var key in shape) {
    log("Key: " + key);
    log("Value: " + shape[key]);
    log("----------------------");
}
  • Notice that the key variable simply holds a string containing the property name.
  • key is not a special name. Call the variable whatever you want (propertyName for example).

Objects and Arrays

What can be stored as a property value in an object?

Anything that you can put into a variable!

What can be stored in an array?

Anything that you can put into a variable!

Objects in Objects

Remember how we can have objects as properties of an object?

var worker = {
  name: 'Johnny',
  position: 'Software Engineer',
  boss: {
    name: 'Fred',
    position: 'TPM'
  }
};

var bossOfWorker = worker.boss;
log(bossOfWorker.name);

// Or write it like this:
log( worker.boss.name );

Arrays in Arrays

Just like we can have objects in objects, we can have arrays of arrays

var ticTacToe = [
    ['X', 'O', 'O'],
    ['O', 'O', 'X'],
    ['X', 'X', 'O']
];

var secondRow = ticTacToe[1];
log( secondRow[1] );

// or write it like this:
log( ticTacToe[1][1] );

Arrays of Objects

We can have an array that stores objects.

var people = [
    {
        firstName: 'Brandon',
        lastName: 'Carpenter'
    },
    {
        firstName: 'Kaiti',
        lastName: 'Carpenter'
    },
    {
        firstName: 'Genevieve',
        lastName: 'Carpenter'
    }
];

var secondPerson = people[1];
log( secondPerson.firstName );

// or write it like this
log( people[1].firstName );

Objects with Arrays

We can have an object that stores arrays.

var allGrades = {
    introToProgramming: [97, 67, 84, 92],
    webDev2: [89, 95, 98, 79],
    design1: [94, 82, 59, 100]
};

var myWebDev2 = allGrades.webDev2;
log( myWebDev2[3] );

// or write it like this
log( allGrades.webDev2[3] );

Arrays of Objects with Arrays

var students = [
    {
        name: 'Julie',
        grades: [ 100, 69, 92, 88 ]
    },
    {
        name: 'Timothy',
        grades: [ 77, 79, 86, 92 ]
    }
];

log( students[0]['grades'][1] );

// or
log( students[0].grades[1] );

A More Complicated Example

var tweet = {
    "created_at": "Wed Dec 05 18:17:16 +0000 2012",
    "id": 276389793724784640,
    "text": "I'm pretty sure Genevieve needs this. @kaiticarp https:\/\/t.co\/tLVoSbVY via @scoutmob",
    "user": {
        "id": 23104052,
        "name": "Brandon Carpenter",
        "screen_name": "bhcarpenter",
        "location": "Atlanta, GA",
        "statuses_count": 549
    },
    "coordinates": null,
    "retweet_count": 0,
    "geo": {
        "type": "Point",
        "coordinates": [ 33.80940075, -84.43679675 ]
    }
};

My Recent Posts Feed

JSON

Creating arrays and objects using [] and {} is so easy (and easy to read) that people have started organizing data this way all over the place. They even gave it a name: JavaScript Object Notation.

Here are some places that you may run across JSON:

  • Embedded into HTML on a web page by a backend programmer. (Web Dev 3 for Developers)
  • As a response from a web service API, such as Twitter, Facebook, etc. (Web Dev 4)
  • If you ever do any backend programming, sometimes people write configuration options in JSON format.
  • And really a lot more.

jQuery

jQuery

jQuery is a library of functions and objects that provide an *abstraction* for working with the DOM.

var el = jQuery('#testParagraph');

// el is now a jQuery object that *represents* 
// the DOM element of the paragraph above.

el.css('color', '#0000ff')

jQuery "objects"

jQuery objects are objects returned by the jQuery() function. They represent (i.e. they "are an abstraction for") DOM elements. This means that you can manipulate these objects and the resulting DOM objects will reflect the change.

Note: To save typing, the jQuery() function is also aliased to $() by default. Going forward, we're just going to type $() instead of jQuery().

Selecting elements

Instead of just finding elements by their ID, jQuery actually lets you find DOM elements using CSS selectors.

var allH1Elements = $('h1');
allH1Elements.css('text-decoration', 'underline');

You can even target elements like this:

var el = $('h1.slide15');
el.css('color', '#3465A4')

DOM Manipulation using jQuery

jQuery provides a replacement for most DOM manipulations.

  • el.attr('attrName'); // Retrieve an attribute
  • el.attr('attrName', 'new content'); // Set an attribute to a new value.
  • el.css('background', '#ff0000'); // Changes a CSS property
  • el.css('background'); // Retrieves the current value of a CSS property.
  • el.append('<p>Some HTML <strong>content</strong></p>')
  • el.val(); // Returns the value of an input, textarea, or select
  • el.val("A value"); // Sets the value of an input, textarea, or select

Events

Finally, jQuery also provides a way to register event listeners. Test Link

var el = $('#testLink4');

var handler = function(event) {

  // Don't actually follow the link:
  event.preventDefault();

  // Instead print out what the link URL is.
  var url = el.attr('href');
  log(url);
}

el.on('click', handler);

You can also fake events! Check this out.

var el = $('#testLink4');
el.trigger('click');

$(document).on('ready')

jQuery also creates a special event on the document object called "ready". It is triggered after all of the elements of the DOM have been created.

If you put your JavaScript tags in the <head> tag, there's a good chance that the DOM events you want to work with haven't been loaded yet, because your web browser creates the DOM elements as it reads the HTML top-to-bottom. If you put all of your DOM code inside of an event listener attached to the "ready" event of the document object, all of the DOM elements are guaranteed to exist.

We haven't been worrying about this because we include all of our JavaScript at the very bottom of the page, but you'll see this a lot as you work with other people's JavaScript code. See the jQuery documentation for more information about the "ready" event.

Do your research!

We've only touched the surface of what jQuery can do.

There are numerous tutorials that you can follow to hone your jQuery skills. Also, the online documentation is excellent.

For any future DOM-type stuff on your homework, feel free to use jQuery instead of document.getElementById(), addEventListener(), etc.