Skip to content

den-wdi-2/js-objects

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 

Repository files navigation

JavaScript Objects

Objectives

After this lesson, students will be able to:

  • Compare key-value stores and arrays as data structures
  • Create empty objects and objects with multiple properties using object literal syntax
  • Compare adding and retrieving properties to an existing object using the dot and bracket notations
  • Access the keys of a key-value store to return and manipulate values

Preparation

Before this lesson, students should already be able to:

  • Create and manipulate variables with JavaScript
  • Use the chrome dev tools console

Opening

What are objects and key-value stores

There are two main ways to group data in modern languages:

key value store array
Can store any data type, strings, numbers, arrays Can store any data type, strings, numbers, arrays
Access the values by key or name Access the values by index
Set a value after it has been created Set a value after it had been created
Dynamic can add a key at any time Add values to the end of array easily

Some unique JavaScript issues:

  • No separate key-value store, we use objects
  • The keys of JavaScript key-value stores are called properties

Creating Objects

There are 2 main ways to create an object in Javascript.

Object literal syntax

This is also called an object initializer.

This is equivalent to the syntax above, and is the one we use to create JSON objects.

var myObject = {};

Constructor function

It is also possible to use a function statement to create an object that serves as a "constructor function."

The first step is to write a function that will define the object. By convention, we start the name of a constructor function with a capital letter. Once the function is defined (in the current scope), you can create a new object by using the keyword new.

function Classroom(name, numberOfStudents) {
  this.name = name;
  this.numberOfStudents = numberOfStudents;
}

var wdi = new Classroom("WDI 2 Denver", 12);

Object Properties

Objects in JavaScript always have properties associated with them.

You can think of a property on a JavaScript object as a type of variable that contains a value. The properties of an object can be accessed using "dot notation":

var Person = {
  name: "Ben"
}

Person.name
=> "Ben"

You can define or re-assign a property by assigning it a value using = as you would a normal variable.

Person.name = "Alex"

Person.name
=> "Alex"

Excercise

Create an object called classroom with properties, name and campus. The name property should have value Code Walkers and the campus property should have value Denver

```javascript var classroom = { name: "Code Walkers" campus: "Denver" } ```

Bracket notation

There is another way to set properties on a JavaScript object.

classroom["name"]   = "Code Walkers";
classroom["campus"] = "Denver";

This syntax can also be used to read properties of an object:

console.log(classroom["name"]);
=> "Code Walkers";

var property = "campus";

console.log(classroom["property"]);
=> "Denver";

For more details see MDN's Documentation on Property Accessors.

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:

The following code shows how to remove a property:

var classroom = {"name": "Code Walkers", "campus": "Denver", "start": "10/31/2016"};
delete classroom.start;
classroom
=> {name: "Code Walkers", campus: "Denver"}

Object methods

As we've said before, the value of a property can be anything in JavaScript, which includes functions. When a function is attached to a property, this function becomes a method. Methods are defined the exact same way as a function, except that they have to be defined as the property of an object.

var classroom = {
  name: "WDI 2",
  campus: "Denver",
  start: "10/31/2016",
  sayHello: function() {
    console.log("Hello");
  }
};

To call the method, we add a pair of parentheses to execute it:

classroom.sayHello();
=> Hello

this for object references

In JavaScript, this is a keyword that refers to the current object.

var classroom = {
  name: "WDI 2",
  campus: "Denver",
  start: "10/31/2016",
  classInfo: function(){
    console.log("This is " + this.name + " and the class starts on " + this.start);
  }
};

classroom.classInfo()
=> This is WDI 2 and it starts on 10/31/2016

Assigning a previously-defined function

We can attach regular functions to objects as methods, even after they are created.

var sayHello = function() { console.log("Hello"); }

classroom.sayHello = sayHello;  

classroom.sayHello()
=> Hello

Enumerating properties of an object

We can use Object.keys() function to get all of the keys of an object.

Once we have an array of the keys we can loop over the keys to work with all of the properties of an object.

var myCar = {"make": "Ford", "model": "Mustang", "year": 1969};

var keys = Object.keys(myCar)

for(i=0; i < keys.length; i++){ 
  console.log("Key " + i + " " + keys[i]) 
}

This section from MDN has more details.

Comparing Objects

In JavaScript, if two objects are created separately, they are distinct, even if they are given the same properties.

var student = {name: "Chris"};
=> undefined

var student2 = {name: "Chris"};
=> undefined

student == student2
=> false

student === student
=> true

Moreover, objects are assigned by reference. Another way to say this is if we create a new variable and assign the object to the new variable we don't create a new object.

var student1 = {name: "Chris"};
=> undefined

var student2 = student1;
=> undefined

student2.name
=> "Chris"

student2.name = "Tom";
=> "Tom"

student1.name
=> "Tom"

student1 === student2
=> true

What? Why is that? Well, even though we had two names we only had a single object. Both of these variables are pointing to the same thing.

Monkey Exercise

  • Create a monkey object, which has the following properties:

    • name
    • species
    • favoriteFoods

    And the following methods:

    • eatSomething(thing): tells the user that name ate thing
    • introduce: produces a string introducing the current monkey, including its name, species, and its favorite foods
  • Create 3 monkeys total. Make sure all 3 monkeys have all properties set. All monkeys should eat multiple foods.

  • Exercise your monkeys by retrieving their properties and using their methods. Practice using both syntaxes for retrieving properties (dot notation and brackets).

Conclusion

We will use key-value stores in JavaScript every day, and you will have plenty of time to practice creating and using objects in Javascript. There are a lot of resources available on the web for you to dive deeper, but the most detailed and understandable one is probably MDN.

Licensing

All content is licensed under a CC­BY­NC­SA 4.0 license. All software code is licensed under GNU GPLv3. For commercial use or alternative licensing, please contact [email protected].

About

[javascript, js, objects, fundamentals]

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published