GDI Logo

Intermediate JavaScript

Class 1: Variables, Arrays, and Objects

View the slides at github.com/gdiseattle/gdi-intermediate-js.

Let's Develop It


alert('Hello World!');
console.log('Secret message');
						

Variables

A variable is a place to store values

Review:

  • Declaring variables
  • Initializing variables
  • What variables can contain
  • Naming rules for variables

Scope

The scope of a variable is how long the computer will remember it.

Local Scope

function func() {
	var local = true;
	console.log(local);
};

func();

console.log(local);
http://bit.ly/intermediate-js-local-scope

Global Scope

var global = "I'm available everywhere!";

function func() {
	var local = "I'm available inside this function.";
	console.log(local, global);
};

func();

console.log(global);
http://bit.ly/intermediate-js-global-scope

Sneaky global scope

Be careful to properly declare and initialize your variables to avoid unexpected global scope.

var global = "I'm available everywhere.";

function func() {
	local = "I'm available everywhere, too!";
};

func();

console.log(local);

Precedence

var g = "global";

function go() {
	var l = "local";
	var g = "in here!";
	console.log(g + " inside go()");
}

go();
alert(g + " outside go()");
http://bit.ly/intermediate-js-precedence

Questions?

Questions about variables, scope, or precedence?

Arrays

var coolLadyCoders =
  [
    'Grace Hopper',
    'Ada Lovelace',
    'Dorothy Vaughan',
    'Margaret Hamilton',
  ];
http://bit.ly/intermediate-js-coolLadyCoders

  • How long is the array?
  • What is the index of 'Dorothy Vaughan'?
  • What is at the 0th index?
  • How do we find the length of an array?
  • When would we use an array?

Assignment and expanding arrays

var coolLadyCoders =
  [
    'Grace Hopper',
    'Ada Lovelace',
    'Dorothy Vaughan',
    'Margaret Hamilton',
  ];

coolLadyCoders[0] = 'Ada Lovelace';
coolLadyCoders[1] = 'Grace Hopper';

coolLadyCoders.push('Anita Borg');

We can also use the new keyword to create a new array:

var coolLadyCoders = new Array();

Accessing items

var coolLadyCoders =
  [
    'Grace Hopper',
    'Ada Lovelace',
    'Dorothy Vaughan',
    'Margaret Hamilton',
  ];

var firstLady = coolLadyCoders[0];
var lastLady = coolLadyCoders[3];

Removing items

The pop() method removes the last item from the array and returns it

var coolLadyCoders =
  [
    'Grace Hopper',
    'Ada Lovelace',
    'Dorothy Vaughan',
    'Margaret Hamilton',
  ];

console.log(coolLadyCoders);

var removed = coolLadyCoders.pop();

console.log(coolLadyCoders);
console.log(removed);

Array review

var coolLadyCoders =
  [
    'Grace Hopper',
    'Ada Lovelace',
    'Dorothy Vaughan',
    'Margaret Hamilton'
  ];

var i = 0;

console.log(coolLadyCoders[i]); // What will this display?

console.log(coolLadyCoders[1]; // What will this display?

console.log(coolLadyCoders.pop()); // What will this display?

console.log(coolLadyCoders.length); // what will this display?

Iterating over arrays

for(var i = 0; i < coolLadyCoders.length; i++) {
	console.log(coolLadyCoders[i]); // What will this display?
}

Let's Develop It!

Starting with this array:

var noisesArray = ["quack", "sneeze", "boom"];

Output “quack! sneeze! boom!” to the console.

The join() method of arrays

Converts an array to a string.

Takes a single argument - the string that should separate the individual items.

array.join()


console.log(coolLadyCoders.join());
console.log(coolLadyCoders.join(', '));
console.log(coolLadyCoders.join(' + '));
console.log(coolLadyCoders.join(''));

Let's Develop It! (again)

Starting with this array:

var noisesArray = ["quack", "sneeze", "boom"];

Output “quack! sneeze! boom!” to the console.

The filter() method of arrays

var numbers = [12, 5, 8, 44, 53, 130, 44, 4];

function isBigEnough(element) {
	return element >= 10;
}

var bigNumbers = numbers.filter(isBigEnough);

console.log(numbers);
console.log(bigNumbers);

The filter() method creates a new array with all elements that pass the test implemented by the provided function.


http://bit.ly/intermediate-js-filter

filter()

The filter() method requires one argument - a callback function that returns a Boolean

If the function returns true, the item is added to the new array.

var numbers = [12, 5, 8, 44, 53, 130, 44, 4];

function isBigEnough(element) {
	return element >= 10;
}

var bigNumbers = numbers.filter(isBigEnough);

The filter() callback function can take up to three arguments. They are: element, index, and array

Let's Develop It!

Given this array:

var cats = [
	{ name: "Maru", status: "hungry" },
	{ name: "Hana", status: "playful" },
	{ name: "Lil Bub", status: "sleepy" },
	{ name: "Grumpy Cat", status: "hungry" }
];

Filter the array to create a new array of just the cats who are hungry.


http://bit.ly/intermediate-js-cats

The map() method of arrays

The map() method creates a new array with the results of calling a function on each item in the array.

map()

The map() method requires one argument - a callback function that takes an item from the current array and returns an item that will be included in the new array.

var numbers = [57, 12, 13, 5, 143, 8, 17, 43];

var numbersPlusFive = numbers.map(function(num){
	return num + 5;
});

console.log(numbers);
console.log(numbersPlusFive);

The map() callback function can take up to three arguments. They are: element, index, and array


http://bit.ly/intermediate-js-map

Let's Develop It!

Given this array:

var cats = [
	{ name: "Maru", status: "hungry" },
	{ name: "Hana", status: "playful" },
	{ name: "Lil Bub", status: "sleepy" },
	{ name: "Grumpy Cat", status: "hungry" }
];

Use the map() method to create a new array of strings representing the cats names. Like this:

var catNames = ["Maru", "Hana", "Lil Bub", "Grumpy Cat"];

Questions?

Questions about join(), filter(), or map() before we move on?

Objects Review

var ollieTheCat = {
	furColor: 'gray',
	age: 2,
	personality: 'wild',
	likes: ['catnip', 'food', 'naps', 'cuddles', 'attention'],
	adopted: {
		month: 'february',
		day: '11',
		year: '2015'
	}
};
http://bit.ly/intermediate-js-ollie

  • How many keys are in the object?
  • What are the key names?
  • What are the values?

Creating objects

So far, we've learned how to create an object by doing this:

var ollieTheCat = {};

Or by doing this:

var ollieTheCat = {
	furColor: 'gray',
	age: 1
};

These are called object literals - a pair of curly braces with 0 or more property/value pairs.

The new keyword

We can also create new objects by using the new keyword, like this:

var ollieTheCat = new Object();

Assigning properties

We can assign properties inside an object literal:

var ollieTheCat = {
	furColor: 'gray'
};

or by using dot notation:

var ollieTheCat = {};
ollieTheCat.furColor = 'gray';

or by using bracket notation:

var ollieTheCat = new Object();
ollieTheCat['furColor'] = 'gray';

Accessing properties

We can access properties with dot notation:

var furVariable = ollieTheCat.furColor;

...or we can use bracket notation:

var furVariable = ollieTheCat['furColor'];

Changing properties

Given an object:

var ollieTheCat = {
	furColor: 'gray',
	age: 1
};

We can change the value of a property with dot notation:

ollieTheCat.furColor = 'hot pink';

...or we can change the value with bracket notation:

ollieTheCat['furColor'] = 'hot pink';

Variables

We can also use variables to store references to property names

var ollieTheCat = {
	furColor: 'gray'
};

var keyVariable = 'furColor';

console.log(ollieTheCat[keyVariable]);

Note that you can only use variables with bracket notation.

Let's Develop It!

Create an animal object, and define these properties on it:

  • name - a string
  • description - a string
  • noises - an array of strings

Arrays of Objects

var myCats = [
	{ name: 'Ollie', age: 2, furColor: 'gray' },
	{ name: 'Mabel', age: 7, furColor: 'gray' }
];

What would be the result?

console.log(myCats[0].name);
console.log(myCats[1]furColor);
console.log(myCats[1]["Fur Color"]);

http://bit.ly/intermediate-js-array-of-objects

Iterating over properties of objects

var zoo = {
	birds: 3,
	bears: 5,
	cats: 12
};

for(var key in zoo) {
	console.log(zoo[key] + ' ' + key);
}
http://bit.ly/intermediate-js-zoo

Let's Develop It!

Exercise instructions

Nested Objects

var doll = {
	size: 'large',
	innerDoll: { size: 'medium'}
};

doll.innerDoll.innerDoll = {size: 'small'};

console.log(doll);

Let's Develop It!

Start with your array of animals from the previous exercise.

Add an outfit property to each animal, which contains an object that describes different parts of their outfit, for example, shirt: "blue".

Log out the outfit of each animal to make sure it worked.

Bonus: Modify your loop from the last exercise to include the animal's outfit in the output, e.g. "Daffy Duck is wearing blue pants and a white shirt."

Questions?

Questions on objects?

Break time!