GDI Logo

JavaScript 201

Class 1: Variables, Arrays, and Objects

View the slides at gdila.org/js201.

Thank You

Welcome!

Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.

Some "rules"

  • Every question is important.
  • Help each other.
  • Have fun.
  • Learn and return.

Tell us about yourself

  • What's your name?
  • What do you hope to get out of the class?
  • Where would you most like to go on a vacation?

About Me

  • What's my name?
  • What's my favorite language?
  • What do I do?
  • Where would I most like to go on a vacation?

JavaScript 201

Wifi network: Build With Code

Wifi password: ilovetesting

 

Class Slides

gdila.org/js201

Let's Develop It!

Let's get set up to write and test a little JavaScript. Make a folder called gdi. Inside, make an HTML page called index.html and a JavaScript file called mycode.js. Then set up your index.html file like this:

<!DOCTYPE html>
<html>
<head>
	<meta chartset="UTF-8"/>
	<title>Test Page</title>
</head>
<body>
	<p>This is my awesome JavaScript code.</p>

	<script src="mycode.js"></script>
</body>
</html>

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);

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);

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()");

Questions?

Questions about variables, scope, or precedence?

Arrays

var coolClasses = ['HTML 101', 'HTML 201', 'JS 101', 'JS 201'];
  • How long is the array?
  • What is the index of JS 101?
  • 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 classes = [];

classes[0] = 'HTML 101';
classes[1] = 'HTML 201';

classes.push('JS 101');

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

var classes = new Array();

Accessing items

var classes = ['HTML 101', 'HTML 201', 'JS 101', 'JS 201'];

var firstClass = classes[0];
var lastClass = classes[3];

Removing items

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

var classes = ['HTML 101', 'HTML 201', 'JS 101', 'JS 201'];

console.log(classes);

var removed = classes.pop();

console.log(classes);
console.log(removed);

Array review

var classes = ['HTML 101', 'HTML 201', 'JS 101', 'JS 201'];

var i = 0;

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

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

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

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

Iterating over arrays

var classes = ['HTML 101', 'HTML 201', 'JS 101', 'JS 201'];

for(var i = 0; i < classes.length; i++) {
	console.log(classes[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()

var classes = ['HTML 101', 'HTML 201', 'JS 101', 'JS 201'];

console.log(classes.join());
console.log(classes.join(', '));
console.log(classes.join(' + '));
console.log(classes.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.

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.

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

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'
	}
};
  • 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"]);

Iterating over properties of objects

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

for(var key in zoo) {
	console.log(zoo[key] + ' ' + key);
}

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?

Homework

Two things for you to do before next week's class:

  1. Work through the homework problems.

 

If you have questions, post in our Facebook group.