General Assembly

Objects & JSON

Wilson Espina

Review

What did we do last lesson?

Objects & JSON

Learning Objective

Learning Objectives

At the end of this class, you will be able to:

  • Know what objects and methods are
  • Real World Scenarios
  • Understand what is JSON
  • Work with JSON-formatted data

Objects & JSON

Agenda

  • Homework Review
  • Hoisting
  • Objects
  • Real World Scenarios
  • Using JSON

Objects & JSON

Exit Ticket Questions

  1. Still don't really understand the utility of SSH.
  2. There's an information overload!

Objects & JSON

Classroom Resources

  1. Pull changes from the wilson-espina/jsd-9-resources repo to your computer:
    • Open the Terminal
    • cd to the Documents/JSD/jsd-9-resources directory
    • Type git pull origin master and press return
  2. In your editor, open the following folder: Documents/JSD/jsd-9-resources/06-objects-json

Objects & JSON

Homework Review

Scope & Variables

Hoisting

Scope & Variables

Hoisting

  • When JavaScript compiles all of your code, all variable declarations using var are lifted to the top of their function/local scope.
  • Hoisting doesn't happen in the code, rather the Compiler.
  • Google Chrome uses V8 Compiler / Interpreter.
Hoisting

Scope & Variables

Hoisting

Code written by developer


function celebrate() {

  console.log("Wahoo!");
  var x = 1;
}
								

Code as intrerpreted by parser


function celebrate() {
  var x; // top of function scope
  console.log("Wahoo!");
  x = 1;
}
								
  • Variable names declared with var are hoisted, but not their values.

Scope & Variables

Hoisting

Code written by developer


function celebrate() {
  console.log("Wahoo!");
  let x = 1;
}
								

Code as intrerpreted by parser


function celebrate() {
  console.log("Wahoo!");
  let x = 1;
}
								
  • Variable names declared with let or const are not hoisted.

Scope & Variables

Hoisting - Function Declarations

Code written by developer


foo()

function foo() {
  console.log("Hi!");
}
								

Code as intrerpreted by parser


function foo() {
  console.log("Hi!");
}

foo();
								
  • Function declarations are hoisted.
  • Your code can call a hoisted function before it has been declared.

Scope & Variables

Hoisting - Function Expressions

Code written by developer


foo()


var foo = function() {
  console.log("Hi!");
}
								

Code as intrerpreted by parser


var foo;

foo(); // error foo is not a function
foo = function() {
  console.log("Hi!");
}
								
  • Function expressions are treated like other variables

Scope & Variables

Hoisting - Function Expressions

Code written by developer


foo()

let foo = function() {
  console.log("Hi!");
}
								

Code as intrerpreted by parser


foo(); // foo is not defined

let foo = function() {
  console.log("Hi!");
}
								
  • Function expressions are treated like other variables

Scope & Variables

let, const and var

Keyword Scope Can Be Reassigned Hoisting
var Function scope

Yes

Yes

let Block scope

Yes

No

const Block scope

No

No

Quiz - Variables & Scope

Quiz

Objects & JSON

Objects

Objects & JSON

Objects are a data type

Data types post it

Objects & JSON

Objects store data

Objects in filing cabinet
  • Objects are a type of data structure that is nearly universal across programming languages.
  • Like arrays, objects can hold multiple pieces of data of varying types.
  • Objects store data and are accessed like files in a filing cabinet.

Objects & JSON

Objects


const myObject = new Object();

const myObject = {};
// Most common way is 'object literal syntax'							

Objects & JSON

Objects

Object example 01

Objects & JSON

Objects

Object example 02
  • Objects are a collection of properties.

Objects & JSON

Property = Key & Value

Object example 03
  • A property is an association between a key and a value.
  • key: name (often descriptive) used to reference the data.
    • A key can be either a name, a number or a string.
  • value: the data stored in that property.
    • Can be any value including arrays, null or undefined and even another object.

Objects & JSON

Key-value pair

Object example 04
  • A property is a know as a key-value pair.

Objects & JSON

Objects are not ordered


	[
	  "Dave", 		// 0
	  "Benson-Phillips",	// 1
	  55			// 2
	]
									

Array

Ordered


{
  name: "Dave",
  lastName: "Benson-Phillips",
  age: 55
}
								

Object

Not ordered

Objects & JSON

A method is a function property


const animal = {
  type: 'dog',
  speak: function() {
	console.log("Woof!");
  }
}
							

Objects & JSON

A method is a function property

Object example 05

Objects & JSON

Get / Set Properties

Dot notation and square brackets

Objects & JSON

Dot Notation


const person = {
  name: 'Wilson',
  location: 'London',
  shout: function() {
	console.log("I hate lockdown");
  }
};
							


person.name // getting a value
=> "Wilson"

							

person.name = 'Steven'; // setting a value
=> "Steven"
							

person.shout() // calling a method
=> "I hate lockdown"
							

Objects & JSON

Bracket Notation


const person = {
  name: 'Wilson',
  location: 'London',
  shout: function() {
	console.log("I hate lockdown");
  }
};
							

person['name']
=> "Wilson"
							

person['name'] = 'Steven';
=> "Steven";
							

person['whisper'] = function() {
  console.log("Social distancing is my jam");
};
							

Objects & JSON

Using a variable as a property


const name = 'Jayne';
const object = {
    name: name
};

object;
=> { name: "Jayne" }
							
  • When the key and value are the same value, this can be shortened:

const object = { name }; // ES6 syntax
								

Objects & JSON

Property value shorthand


const name = 'Adrianna';
const nationality = 'Polish';
const dob = '1990-10-10';

const person = { name, nationality, dob };

person;
=> Object { name: "Adrianna", nationality: "Polish", dob: "1990-10-10" };
							

Objects & JSON

Destructuring

  • The opposite of this is known as destructuring. We can create variables based on the properties of an object:

const person = { name: 'Adrianna', nationality: 'Polish', dob: '1990-10-10' };
const { name, dob, nationality } = person;

name;
=> "Adrianna";

nationality;
=> "Polish";

dob;
=> "1990-10-10";
							

Objects & JSON

Deleting Properties

  • If you want to delete a property of an object (and by extension, the value attached to the property), you need to use the delete operator:

const classroom = {
  name: 'JSD 9',
  type: 'Remote',
  start: '11/05/2020'
};

delete classroom.start;

classroom
=> Object { name: "WDI 2", type: "Remote" }
							

Code along

Code Along

Open up: 1-object-codealong

Code Along

Exercise - Intro to Objects

Exercise

Key Objective

  • Create JavaScript objects using object literal notation

Type of Exercise

  • Individual

Location

  • starter code > 2-objects-intro

Timing

5 mins

  1. Write code to create a variable whose name corresponds to any one of the following things: (cloud ☁️, houseplant 💐, car 🚙, or airplane ✈).
  2. Write code to add a property to the object and specify a value for the property.
  3. Write code to add a method to the object, and specify a value for the method (use a comment or console.log() statement for the function body).
  4. BONUS: Rewrite your answers for 1-3 as a single JavaScript statement.

Objects & JSON

Real World Scenarios

Objects & JSON

Objects in the Real World

"A user, browsing on a shopping website, searches for size 10 running shoes, and examines several pairs before purchasing one."

Objects & JSON

Objects = Nouns

"A user, browsing on a shopping website, searches for size 10 running shoes, and examines several pairs before purchasing one."

implicit object:

shopping cart

Objects & JSON

Properties = Adjectives

"A user, browsing on a shopping website, searches for size 10 running shoes, and examines several pairs before purchasing one."

implicit properties:

for each pair of shoes:

price

colour

for the shopping cart:

contents

total

shipping

Objects & JSON

Properties = Adjectives

"A user, browsing on a shopping website, searches for size 10 running shoes, and examines several pairs before purchasing one."

implicit properties:

for each pair of shoes:

add to cart

for the shopping cart:

calculate shipping

calculate tax

complete purchase

remove item

Lab - Objects

Exercise

Key Objective

  • Create JavaScript objects using object literal notation

Type of Exercise

  • Individual

Location

  • starter-code > 3-object-exercise > monkey.js

Timing

15 mins

  1. Open monkey.js in your editor.
  2. Create objects for 3 different monkeys each with the properties and methods listed in the start file.
  3. Practice retrieving properties and using methods with both dot notation and bracket syntax.
  4. BONUS: Rewrite your code to use a constructor function.

Objects & JSON

JSON

Objects & JSON

Objects vs JSON

Object


const course = {
  name: 'JSD',
  weeks: 10,
  location: 'Remote',
  instructor; 'Wilson Espina',
  students: [
    'Mr Motivator',
    'Cathy Burke',
    'Carl Cox',
    'Steven King',
    'Susie Dent'
  ],
  dates: {
    start: '2020-05-11',
    end: '2020-07-20'
  }
}
								

JSON


const course = {
  "name": "JSD",
  "weeks": 10,
  "location": "Remote",
  "instructor": "Wilson Espina",
  "students": [
    "Mr Motivator",
    "Cathy Burke",
    "Carl Cox",
    "Steven King",
    "Susie Dent"
  ],
  "dates": {
    "start": "2020-05-11",
    "end": "2020-07-20"
  }
}
								

Objects & JSON

JSON

  • JavaScript Object Notation (JSON)
  • Lightweight text-based data format that's based on JS objects.
  • Easy for humans to read and write AND easy for programs to parse and generate.

const course = {
  "name": "JSD",
  "weeks": 10,
  "location": "Remote",
  "instructor": "Wilson Espina",
  "students": [
    "Mr Motivator",
    "Cathy Burke",
    "Carl Cox",
    "Steven King",
    "Susie Dent"
  ],
  "dates": {
    "start": "2020-05-11",
    "end": "2020-07-20"
  }
}
								

Objects & JSON

JSON is not JavaScript Specific

JSON Locations

Objects & JSON

JSON in action


"Programme": {
  "title": "Coronation Street",
  "synopsis":
  	"Geoff forces Yasmeen into an embarrassing situation in the Rovers.",
  "image":
  	"https://images-itv.com/episode/8290/1019",
  "description":
  	"Geoff forces Yasmeen into an embarrassing situation in the Rovers.",
  "dateTime": "2020-05-01T18:30:00.000Z",
  "channel": "itv",
  "production":
  	{ "productionId": "8290/1019/11",
	  "productionType": "PROGRAMME"
	}
}
							
Coronation street

Objects & JSON

JSON Rules

  • JSON object must be surrounded by curly braces {}
  • Name-value pairs are grouped by a : and separated by a comma,.
  • Each key must be unique and enclosed within double quotes ""
  • No trailing commas.
  • In numbers, a decimal point must be followed by at least one digit.
  • Boolean values can either be true or false and NULL values are represented with null (without quotes).
  • No comments.

Objects & JSON

To convert an object to JSON


JSON.stringify(object);
						

Objects & JSON

To convert an JSON to an Object


JSON.parse(json);
						

Code along

Code Along

Open up: 4-json-codealong

Code Along

Exercise - JSON

Exercise

Key Objective

  • Implement and work with JSON data

Type of Exercise

  • Individual or Pair

Location

  • starter-code > 5-json-exercise > app.js

Timing

10 mins

  1. Open the started code in your editor.
  2. Follow the instructions to write code that produces the stated output.

Objects & JSON

Working with nested Data Structures

Objects & JSON

Using JSON Data


const course = '{"name":"JSD","weeks":
10,"location":"Remote","instructor":
"Wilson Espina","students":["Mr 
Motivator","Cathy Burke","Carl Cox",
"Steven King","Susie Dent"],"dates":
{"start":"2020-05-11","end":"2020-07-
20"}}'
							
What gif

Objects & JSON

Working with nested data structure

Working with data structures

Objects & JSON

Working with nested data structure

Working with data structures step 1 Working with data structures step 1 image

Objects & JSON

Working with nested data structure

Working with data structures step 2 Working with data structures step 2 image

Objects & JSON

Working with nested data structure

Working with data structures step 3 Working with data structures step 3 image

Objects & JSON

Working with nested data structure

Working with data structures step 4 Working with data structures step 4 image

Objects & JSON

Working with nested data structure

Working with data structures step 4 Working with data structures step 5 Working with data structures step 5 image

Objects & JSON

Working with nested data structure

Working with data structures step 4 Working with data structures step 5 Working with data structures step 6 image

Code along

Code Along

Open up: 6-cat-facts-json

Code Along

Lab - JSON

Exercise

Key Objective

  • Implement and work with JSON data

Type of Exercise

  • Individual

Location

  • starter-code > 7-data-structure-exercise > app.js

Timing

8 mins

  1. Open app.js in your editor.
  2. Follow the instructions to write code that produces the stated output

Objects & JSON

Learning Objectives - Review

  • Know what objects and methods are
  • Real World Scenarios
  • Understand what is JSON
  • Work with JSON-formatted data

Objects & JSON

Lookahead to Next Lesson (03/06/20)

SlackBot Lab

  • Introduction to SlackBots.
  • Use API keys to interact with the Hubot Framework.
  • Write scripts that allow your bot to interact with users of the class Slack workspace.
Hubot

Objects & JSON

Q&A

Objects & JSON

Exit Ticket

(Lesson #06)