Skip to main content

JavaScript Core II - 1

Contents​


Learning Objectives​

By the end of this lesson trainees should be able to:

  • Define what an object is in JavaScript
  • Be able to write code that can use an object to store data
  • Be able to write code that changes the properties of an object
  • Be able to write code that can retrieve data from an object
  • Write and call methods inside JavaScript objects

Objects​

Objects in the real world have properties that describe how they are unique. Your laptop, for example, has a brand (Lenovo/Apple etc.), a screen size (13/15 inch), RAM (8/16GB) etc.

How would we describe the above laptop as a JavaScript object?

let laptop = {
brand: "Lenovo",
screenSize: 13,
isTouchscreen: true,
};

Exercise (1)​

Exercise

Describe your own laptop as a JavaScript object. Try to think of as many properties as you can!

Example:

let laptop = {
brand: "Lenovo",
screenSize: 13,
isTouchscreen: true,
};

Exercise (2)​

Exercise

Think of 5 different real world "things" that you can describe with a JavaScript object Assign each of them to a separate variable

Example:

let jumper = {
color: "blue",
isCotton: true,
};

Exercise (3)​

Exercise

The objects below have some syntax issues - try and fix them all!



let kitten = {
fur colour: "orange",
age "23"
};

let laptop =
brand: "Lenovo"
ram "5GB"
}

let phone = {
operating system "iOS",
hasStylus: true,
megapixels 12
"batteryLife": "24 hours"

Useful words to remember when talking about objects:

  • object literal: anything that has a set of {...} around a set of properties is an object literal
  • property or key: brand, screenSize and isTouchScreen are properties/keys of the object
  • values: "Lenovo", 13 and true are values of the object's properties

Exercise (4)​

Exercise

Choose a few nearby colleagues and one mentor, and go through each variable you declared above in Part 1, 2 or 3, reading everything that happens out loud.

Make sure each member of your group has read at least one variable!

Make sure you use words like:

  • object literal
  • property / key
  • value
  • string / number / boolean
  • declaring a variable
  • etc.

Objects Get and Set​

Getting the value of an object's property​

Let's take one of the objects we looked at earlier..

let laptop = {
brand: "Lenovo",
screenSize: 13,
isTouchscreen: true,
};

Try to console.log(laptop). The output might depend on your environment!

To find out the value of an object's property, you can use the dot notation..

console.log(laptop.brand);

You can also use the bracket notation (although this is rarely used, it's good to know):

console.log(laptop["brand"]);

Exercise (1)​

Console.log the values of each property of "kitten"

Exercise
/*
Console.log the values of each property of "kitten"
*/

let kitten = {
ageMonths: 3,
isFemale: true,
furColour: "brown",
};

Exercise (2)​

Exercise

The following code contains syntax errors - try and fix them! Once you fix them, run the code, it should output the correct values!

It should output: iPhone 2017

let phone = {
brand:'iPhone,
model 'iPhone X'
launchYear: 2017,
is Unlocked: true
;

let phoneBrand = phone.brand;
let phoneLaunchYear = phone["launchYear"];

console.log(phoneBrand);
console.log(phoneLaunchYear);

Setting the value of a property​

Similar to reading, if we want to set a property:

laptop.brand = "Apple";

It's strongly recommended you always use the same type when re-assigning an object's property (if it was a string before, keep it a string - and so on).

let laptop = {
brand: "Lenovo",
screenSize: 13,
isTouchscreen: true,
};

// DON'T DO THIS
laptop.screenSize = "15 inch";

// OK TO DO
laptop.screenSize = 15;

Exercise (1)​

Exercise

Write code in the space provided so that it outputs "Gilbert"

It should output: "Gilbert"

// WRITE CODE BELOW THIS

// WRITE CODE ABOVE THIS

console.log(kitten.name);

Exercise (2)​

Exercise

Write code in the space provided so that the expected values output

It should output: Rex true

let dog = {
name: "Billy",
wantsToPlay: false,
};

// WRITE CODE BELOW THIS LINE

// WRITE CODE ABOVE THIS LINE

console.log(dog.name);
console.log(dog.wantsToPlay);

// -> it should output:
// Rex
// true

More Complex Objects​

Object properties can even be assigned other objects, arrays or variables too. The example below shows an object with keys that have been assigned a variable, an array, and an object.

let kittenName = "Feathers";

let kitten = {
name: kittenName,
toyCollection: ["blue ball", "green ball", "hoover box"],
favoriteLocation: {
roomName: "Living room",
napPlace: "window",
idealTemperatureCelsius: 24,
},
};

Exercise (1)​

Exercise

Given the following house - follow the instructions below.

Make sure you run the file after and it outputs the correct results.

let house = {
address: "1 Kinning Park",
previousOwners: ["Claire M.", "John A."],
currentOwner: {
firstName: "Margaret",
lastName: "Conway",
},
};

/*
DO NOT EDIT ANYTHING ABOVE THIS LINE

WRITE YOUR CODE BELOW
*/

// - change the address of "house" to '51 Berkley Road'
// - change the previous owners of "house" to ["Brian M.", "Fiona S."]
// - change the last name of the current owner of "house" to "Montgomery"

/*
DO NOT EDIT ANYTHING BELOW THIS LINE
*/

console.log(
`Expected result: 51 Berkley Road. Actual result: ${house.address}`
);
console.log(
`Expected result: Brian M., Fiona S. Actual result: ${house.previousOwners.toString()}`
);
console.log(
`Expected result: Montgomery. Actual result: ${house.currentOwner.lastName}`
);

Exercise (2)​

Exercise

Given the same "house" object again

Follow the instructions below and then run the file and make sure it outputs the correct results

let house = {
address: "1 Kinning Park",
previousOwners: ["Claire M.", "John A."],
currentOwner: {
firstName: "Margaret",
lastName: "Conway",
},
};

let newCurrentOwner = {
firstName: "Georgina",
lastName: "Hernandez",
};

/*
DO NOT EDIT ANYTHING ABOVE THIS LINE

WRITE YOUR CODE BELOW
*/

// - assign the value of the variable 'newCurrentOwner' as the value to the house's "currentOwner"
// - from the list of previous owners, replace only "John A." with "Stephen B."
// - give the house a new property called 'isForSale' with the value 'false'

/*
DO NOT EDIT ANYTHING BELOW THIS LINE
*/
console.log(
`Did you correctly assign the new owner using the given variable?","Expected result: true. Actual result: " ${
house.currentOwner === newCurrentOwner
}`
);
console.log(
`Expected result: Claire M., Stephen B. Actual result: ${house.previousOwners.toString()}`
);
console.log(`Expected result: false. Actual result: ${house.isForSale}`);

Exercise (3)​

Exercise

Given the same "house" object again

Write the code for the functions as per the description above them

let kinningParkHouse = {
address: "1 Kinning Park",
price: 180000,
currentOwner: {
firstName: "Margaret",
lastName: "Conway",
email: "margaret@fake-emails.com",
},
};

let parkAvenueHouse = {
address: "50 Park Avenue",
price: 195000,
currentOwner: {
firstName: "Marie",
lastName: "McDonald",
email: "marie.m@real-emails.com",
},
};

/*
DO NOT EDIT ANYTHING ABOVE THIS LINE

WRITE YOUR CODE BELOW
*/

// returns the full name (first name + last name) of the owner of the house
function getOwnerFullName(house) {}

// returns an array of the owners' email addresses of the two houses
function getEmailAddresses(house1, house2) {}

// returns the address for the cheapest house out of the two
function getCheapestAddress(house1, house2) {}

/*
DO NOT EDIT ANYTHING BELOW THIS LINE
*/
console.log(
`Expected result: Margaret Conway. Actual result: ${getOwnerFullName(
kinningParkHouse
)}`
);
console.log(
`Expected result: margaret@fake-emails.com, marie.m@real-emails.com. Actual result: ${getEmailAddresses(
kinningParkHouse,
parkAvenueHouse
)}`
);
console.log(
`Expected result: 1 Kinning Park. Actual result: ${getCheapestAddress(
parkAvenueHouse,
kinningParkHouse
)}`
);

Object Methods​

Besides having specific properties, objects in the real world can also do things. For example, a computer can display something on the screen, a person can say their names etc... In Javascript, we do this using 'methods'. A method is a function attached to a particular object. You have already used some predefined methods before, for example toUpperCase() on a string or filter() on an array.

let athlete = {
name: "Usain Bolt",
goldMedals: 25,
sayHi: function () {
return "Hi everybody!";
},
};

How do we call this method?

athlete.sayHi(); // returns "Hi everybody!"

An object method can also rely on the other properties of the object to do more complex calculation. To reference the current object in the body of the method, we will use the keyword this. Let's take an example.

let athlete = {
name: "Usain Bolt",
goldMedals: 25,
sayName: function () {
return "My name is " + this.name;
},
};

athlete.sayName(); // returns "My name is Usain Bolt"

Knowing this, you can have methods which modify existing properties of your object.

let athlete = {
name: "Usain Bolt",
goldMedals: 25,
winNewMedal: function () {
this.goldMedals = this.goldMedals + 1;
},
};

athlete.winNewMedal();
console.log(athelete.goldMedals); // prints "26"

As methods are just functions attached to objects, they can also take parameters.

let athlete = {
name: "Usain Bolt",
goldMedals: 25,
silverMedals: 7,
winNewMedal: function (medal) {
if (medal === "gold") {
this.goldMedals = this.goldMedals + 1;
} else {
this.silverMedals = this.silverMedals + 1;
}
},
};

athlete.winNewMedal("silver");
console.log(athlete.goldMedals); // prints "25"
console.log(athlete.silverMedals); // prints "8"

Exercise (1)​

Exercise

A person named Alice is defined below.

  1. Add a method "greet" so this person can say hello.
  2. Add a method "sayName" so this person can say their own name. Hint: use 'this' keyword to access the name property.
let person = {
name: "Alice",
age: 25,
};

/*
DO NOT EDIT ANYTHING BELOW THIS LINE
*/

console.log(
`Expected result: Hello everybody. Actual result: ${person.greet()}`
);
console.log(
`Expected result: 'My name is Alice'. Actual result: ${person.sayName()}`
);

Exercise (2)​

Exercise

The following code contains syntax errors - try and fix them! Once you fix them, run this file, it should output the correct values!


let person = {
name: "Alice",
age: 25,
currentAddress: "Glasgow",
changeAddress: (newAddress) {
currentAddress = newAddress;
},
celebrateBirthday: function {
that.age = that.age + 1;
}
};

Exercise (3)​

Exercise

The following code contains syntax errors - try and fix them!

Once you fix them, run this file, it should output the correct values!


let person = {
name: "Alice",
age: 25,
currentAddress: "Glasgow",
changeAddress: (newAddress) {
currentAddress = newAddress;
},
celebrateBirthday: function {
that.age = that.age + 1;
}
};


/*
DO NOT EDIT ANYTHING BELOW THIS LINE
*/

person.changeAddress("Edinburgh");
console.log(`Expected result: Edinburgh. Actual result: ${person.currentAddress}`);

person.celebrateBirthday();
console.log(`Expected result: 26. Actual result: ${person.age}`);

Exercise (4)​

Exercise

Alice has a list of good friends.

Define a method "makeFriend" to add a new friend to her list.

let person = {
name: "Alice",
friends: ["John", "Nina"],
};

/*
DO NOT EDIT ANYTHING BELOW THIS LINE
*/

person.makeFriend("Bob");

console.log(
`Expected result: 'John,Nina,Bob'. Actual result: ${person.friends}`
);

Exercise (5)​

Exercise

A coffee machine is defined below. One that can buy three different coffees. Complete the methods "insertMoney" and "getCoffee" to match the expected result.

insertMoney takes an amount in parameter to add money in the coffee machine. getCoffee takes a coffee type in parameter and dispends the selected coffee only if the inserted amount is greater or equal than the price of the coffee!

let coffeeMachine = {
brand: "Super Coffee",
prices: {
cappuccino: 2.4,
blackCoffee: 1.5,
flatWhite: 3.0,
},
insertedAmount: 0,
insertMoney: function (amount) {},
getCoffee: function (coffee) {},
};

/*
DO NOT EDIT ANYTHING BELOW THIS LINE
*/

coffeeMachine.insertMoney(2.4);
console.log(
`Expected result: 'Please take your cappuccino'. Actual result: ${coffeeMachine.getCoffee(
"cappuccino"
)}`
);

coffeeMachine.insertMoney(1.5);
console.log(
`Expected result: 'Please take your blackCoffee'. Actual result: ${coffeeMachine.getCoffee(
"blackCoffee"
)}`
);

coffeeMachine.insertMoney(4.0);
console.log(
`Expected result: 'Please take your flatWhite'. Actual result: ${coffeeMachine.getCoffee(
"flatWhite"
)}`
);

coffeeMachine.insertMoney(2.4);
console.log(
`Expected result: 'Sorry you don't have enough money for a flatWhite'. Actual result: ${coffeeMachine.getCoffee(
"flatWhite"
)}`
);

Coursework​

The coursework for this lesson.

Feedback​

Please spend two minutes reviewing this lesson to help us improve it for the future. This feedback will be shared with volunteers.