7/8/2017 - 2:19 PM

Unit 2-Lesson 6: Objects

Unit 2-Lesson 6: Objects

A javascript object has properties associated with it. A property of an object can be explainedd as a variable that is attached to the object. Object properties are basically the same as ordinary JS variables, except for the attachement to objects. The properties of an object define the characeteristics of the object. You access the properties of an object with a simple dot-notation.

objectname.propertyName You can define a property by assigning it a value.

var myCar = new Object();
myCar.make = 'Ford';
myCar.model = 'Mustang';
myCar.year = 1969;

Unassigned properties of an object are undefined and not null.

myCar.color;//undefined Accessing properties using a bracket notation

myCar['make'] = 'Ford';
myCar['model'] = 'Mustang';
myCar['year'] = 1969;

Object property names

//four variables are created and assigned in a single go, separated by commas
var myObj = new Object();
    str = 'myString',
    rand = math.random(),
    obj = new Object();
    myObj.type            = 'Dot syntax';
    myObj['date created'] = 'Strong with space';
    myObj[str]            = 'Strong value';
    myObj[rand]           = 'Random Number';
    myObj[obj]            = 'Object';
    myObj['']             = 'Even an empty string';

Object.keys() method allows you to use array iteration methods on JavaScript objects.

Take this object literal:

const users = {
  user1: {
    age: 44,
    name: 'picard',
  user2: {
    age: 12,
    name: 'sisko',
  user3: {
    age: 109,
    name: 'janeway',

if you want to filter for all users older than 30 and store their data in an array you can do this instead of using a for loop:

const userKeys = Object.keys(users);

const adults = userKeys
  .filter(key => users[key].age > 30)
  .map(id => ({id, ...users[key] }));

play with this code here

The Object.keys() is a javascript method that returns an array of keys in the same order as they appear in the object.

  • "Object" needs to be capitalized for the method to work.
  • Pass in the object you want the keys to like: Object.keys(yourObject);

Problem: figure out how to get the number keys in an object. To solve this prolbem and get the total number of keys or length, add .length after .keys() It will look like this: Object.keys(yourObject).length; Get the total amount of keys in this object:

myObject = {
  item1: 'This',
  item2: 'is a',
  item3: 'Test'
  console.log(Object.keys(myObject).length);// 3


var arr = [1, true, "gone"]


var obj = {
'name': 'briana',
'food': 'cheese',
'dog': 'maurice'

Array has square * brackets * and can hold anything, including another array or object. Objects start with curly brackets and * key value pairs *. This notation is known as * JSON *.

JavaScript is an object oriented language and this means that most things in Js are Objects. Functions are objects. The only elements that are not objects are the Primitive Data Types: * strings * numbers * null * boolean * undefined

These Primitive Data Types also are #immutable#, which means that once created they cannot be modified.

One of the differences between the two is that Primitive Data Types are passed By Value and *Objects* are passed By Reference. What does this mean?

By Value means creating a COPY of the original. Picture it like twins: they are born exactly the same, but the first twin doesn't lose a leg when the second twin loses a leg.

By Reference means creating an ALIAS to the original. When your Mom calls you 'pumpkin pie' even though your name is "John', this doesn't suddenly give birth to a clone of yourself: you are still one, but you can be called by these two very different names.

Examples of how Primitives and Objects behave, when assigned values and passed through a function as a parameter.

#1 Assigning a value with the =operator to Primitives as Objects.

var name = 'carlos';// a variable 'name' is created with a value of 'carlos' and memory is allocated for it

var firstName = name;//a variable 'firstName' is created and is given a copy of name value. firstName has its own memory spot and is indep. of name. At this moment in the code, firstName also has a value of carlos.

name = 'carla';//We then change the value of name to carla. But firstname still holds its original value, because it lives in a different memory spot.

console.log(firstName);// carlos

#2 With Objects, =operator works by Reference.

var myName = {
  firstName: 'carlos'
  var identity = myName;
  myName.firstName = 'carla';


Whats happening? A variable 'myName' is created and is given the value of an object which has a property called 'firstName'. 'firstName' has the value of 'carlos'. Javascript allocates a memory spot for 'myName and the object it contains.

A variable 'identity' is created and is pointed to 'myName. There is no dedicated memory space to 'identity' value. It only points to 'myName's value.

We change the value of 'myName' 'firstName' property to 'carla' instead of 'carlos'.

When we log "myName.firstName" it desplays the new value, which is pretty straightforward. But when we log "identity.firstName" it also displays "myName.firstName" new value "carla". This happens because "identity.firstName" only points to myName.firstName" place in the memory.

Unit 2-Lesson 6-Assignment 4: Deeper into Objects (object.keys)

Object.keys()returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually.

better example var arr = ['a', 'b', 'c']; console.log(Object.keys(arr));// ['0', '1', '2']

//array like object var obj = {0; 'a', 1: 'b', 2: 'c'}; console.log(Object.keys(obj));//['0', '1', '2']

//array like object with random key ordering var anObj = {100; 'a', 2: 'b', 7: 'c'}; console.log(Object.keys(anObj));//['2', '7', '100']

//getFoo is property which isn't enumerable

var myObj = Object.create({}, {
  getFoo: {
    value: function () {return;}
  }); = 1;
  console.log(Object.keys(myObj));//console: ['foo']

If you want all properties, even not enumerable, see Object.getOwnPropertyNames()

const pageViewCounts = {
homePage: 399,
aboutPage: 400,
termsOfService: 22
Object.keys(pageViewCounts).forEach(key =>
  `The ${key} page has ${pageViewCounts[key]} views.`)
);//["homePage", "aboutPage", "termsOfService"] "The homePage page has 399 views." "The aboutPage page has 400 views." "The termsOfService page has 22 views."/

Write Preview

Leave a comment Attach files by dragging & dropping, Choose Files selecting them, or pasting from the clipboard. Styling with Markdown is supported Comment Contact GitHub API Training Shop Blog About © 2017 GitHub, Inc. Terms Privacy Security Status Help

In javascript, objects are a data structure made up of key-value pairs.

A bluepring for an object can be made by using a function that acts as a constructor function for the objects. You can also create an object literal that will result in a single object that you can't duplicate.

Object Literals

To create a literal object you make a variable that holds a group of comma separated key-value pairs, also called a hash, in which the keys are the names that refer to the values. Each key-value pair is a property of the Object. Values can be data or functions. The example below is an object literal that has 4 properties: name, age, gender, and runner.

var person = {
  name: "todd",
  age: 31,
  gender: 'male',
  runner: 'true'

An * Object Literal * is a single object. You can't make more versions of this object like you can in other languages when you make a class and create object instances of that class. To do that in JavaScript you need to create a constructor function that acts as a blueprint to create one or more instancesof that object.

Constructor created Objects

Make assignments to the function using the 'this' keyword. Whereas above we created a literal object called Person that can't be duplicated to create multiple Person's, now we will create a constructor function that will allow us to create as many Person objects as we want.

function Person(name, age, gender, runner) { = name;
  this.age = age;
  this.gender = gender;
  this.runner = runner;
  Now we can create multiplle instances of Person
  var todd = new Person('todd', 31, 'male', true);
  var joe = new Person('joe', 21, 'male', fales);
  var julia = new Person('julia', 29, 'female', true);
  #### what happens when you don't give the correct number of arguments to the constructor function: ####
var malcolm = new Person('malcolm', 23);
var jay = new Person('jay', 55, 'male', false, 'extraArgument');

console.log(malcolm.gender);// undefined
console.log(jay.runner);// undefined
 Any arguements you don't include will be initialized as *undefined*. If you give the constructor function to many arguments the extra arguments just won't do anything. In the above example there is no way to access the 'extraArgument' string.
 You can also set default values on your object properties in the constructor function in case

The three common ways to create new objects in JavaScript are as follows:

The three common ways to create new objects in JavaScript are as follows:

var newObject = {};
 // or
var newObject = Object.create( Object.prototype );
 // or
var newObject = new Object();

There are then four ways in which keys and values can then be assigned to an object:

  1. Dot syntax // Set properties newObject.someKey = "Hello World"; // Get properties var value = newObject.someKey;

// 2. Square bracket syntax // Set properties newObject["someKey"] = "Hello World";

// Get properties var value = newObject["someKey"];

  1. Object.defineProperty

// Set properties

Object.defineProperty( newObject, "someKey", {
    value: "for more control of the property's behavior",
    writable: true,
    enumerable: true,
    configurable: true

If the above feels a little difficult to read, a short-hand could

be written as follows:

var defineProp = function ( obj, key, value ){
 var config = {
   value: value,
   writable: true,
   enumerable: true,
   configurable: true
 Object.defineProperty( obj, key, config );

To use, we then create a new empty "person" object

var person = Object.create( Object.prototype );

Populate the object with properties

defineProp( person, "car", "Delorean" );
defineProp( person, "dateOfBirth", "1981" );
defineProp( person, "hasBeard", false );
// Outputs: Object {car: "Delorean", dateOfBirth: "1981", hasBeard: false}
  1. Object.defineProperties

Set properties

Object.defineProperties( newObject, {
  "someKey": {
    value: "Hello World",
    writable: true
  "anotherKey": {
    value: "Foo bar",
    writable: false

Getting properties for 3. and 4. can be done using any of the

options in 1. and 2.

Like all JavaScript variables, both the object name (which could be a normal variable) and property name are case sensitive. You can define a property by assigning it a value. For example, let's create an object named myCar and give it properties named make, model, and year as follows:

var myCar = new Object();
myCar.make = 'Ford';
myCar.model = 'Mustang';
myCar.year = 1969;

Unassigned properties of an object are undefined (and not null).

myCar.color; // undefined

Properties of JavaScript objects can also be accessed or set using a bracket notation (for more details see property accessors). Objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it. So, for example, you could access the properties of the myCar object as follows:

myCar['make'] = 'Ford';
myCar['model'] = 'Mustang';
myCar['year'] = 1969;

Here are four variables are created and assigned in a single go, separated by commas

var myObj = new Object(),
    str = 'myString',
    rand = Math.random(),
    obj = new Object();

myObj.type              = 'Dot syntax';
myObj['date created']   = 'String with space';
myObj[str]              = 'String value';
myObj[rand]             = 'Random Number';
myObj[obj]              = 'Object';
myObj['']               = 'Even an empty string';


Please note that all keys in the square bracket notation are converted to String type, since objects in JavaScript can only have String type as key type. For example, in the above code, when the key obj is added to the myObj, JavaScript will call the obj.toString() method, and use this result string as the new key.

You can also access properties by using a string value that is stored in a variable:

var propertyName = 'make';
myCar[propertyName] = 'Ford';

propertyName = 'model';
myCar[propertyName] = 'Mustang';
function showProps(obj, objName) {
  var result = '';
  for (var i in obj) {
    // obj.hasOwnProperty() is used to filter out properties from the object's prototype chain
    if (obj.hasOwnProperty(i)) {
      result += objName + '.' + i + ' = ' + obj[i] + '\n';
  return result;

So, the function call showProps(myCar, "myCar") would return the following:

myCar.make = Ford
myCar.model = Mustang
myCar.year = 1969

Enumerate the properties of an object: three native ways to list/traverse object properties: loops This method traverses all enumerable properties of an object and its prototype chain

Object.keys(o) This method returns an array with all the own (not in the prototype chain) enumerable properties' names ("keys") of an object o.

Object.getOwnPropertyNames(o) This method returns an array containing all own properties' names (enumerable or not) of an object o.

When you create an object with curly brackets, it's called an object literal.

Defining and creating a single object, using an object literal:

var car = {
  wheels: 4,
  engine: 1,
  seats: 4

Each key is followed by a colon (:). Each key/value pair is separated by a comma (,).

Ways of Creating new objects

JavaScript has a number of predefined objects. In addition, you can create your own objects. You can create an object using an object initializer. Alternatively, you can first create a constructor function and then instantiate an object invoking that function in conjunction with the new operator.

The syntax for an object using an object initializer is:

var obj = { property_1:   value_1,   // property_# may be an identifier...
            2:            value_2,   // or a number...
            // ...,
            'property n': value_n }; // or a string

Object initializers are expressions, and each object initializer results in a new object being created whenever the statement in which it appears is executed. Identical object initializers create distinct objects that will not compare to each other as equal. Objects are created as if a call to new Object() were made; that is, objects made from object literal expressions are instances of Object.

The following statement creates an object and assigns it to the variable x if and only if the expression cond is true: if (cond) var x = {greeting: 'hi there'};

The following example creates myHonda with three properties. Note that the engine property is also an object with its own properties.

var myHonda = {color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}};

Using a constructor function

Alternatively, you can create an object with these two steps:

Define the object type by writing a constructor function. There is a strong convention, with good reason, to use a capital initial letter.

Create an instance of the object with new. To define an object type, create a function for the object type that specifies its name, properties, and methods. For example, suppose you want to create an object type for cars. You want this type of object to be called car, and you want it to have properties for make, model, and year. To do this, you would write the following function:

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;

Notice the use of this to assign values to the object's properties based on the values passed to the function.

Now you can create an object called mycar as follows:

var mycar = new Car('Eagle', 'Talon TSi', 1993); This statement creates mycar and assigns it the specified values for its properties. Then the value of mycar.make is the string "Eagle", mycar.year is the integer 1993, and so on.

You can create any number of car objects by calls to new. For example,

var kenscar = new Car('Nissan', '300ZX', 1992);
var vpgscar = new Car('Mazda', 'Miata', 1990);
An object can have a property that is itself another object. For example, suppose you define an object called person as follows:

function Person(name, age, sex) { = name;
  this.age = age; = sex;

and then instantiate two new person objects as follows:

var rand = new Person('Rand McKinnon', 33, 'M');
var ken = new Person('Ken Jones', 39, 'M');

Then, you can rewrite the definition of car to include an owner property that takes a person object, as follows:

function Car(make, model, year, owner) {
  this.make = make;
  this.model = model;
  this.year = year;
  this.owner = owner;

To instantiate the new objects, you then use the following:

var car1 = new Car('Eagle', 'Talon TSi', 1993, rand);
var car2 = new Car('Nissan', '300ZX', 1992, ken);

Notice that instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the arguments for the owners. Then if you want to find out the name of the owner of car2, you can access the following property: Note that you can always add a property to a previously defined object. For example, the statement

car1.color = 'black'; adds a property color to car1, and assigns it a value of "black." However, this does not affect any other objects. To add the new property to all objects of the same type, you have to add the property to the definition of the car object type.

Using the Object.create method

Objects can also be created using the Object.create() method. This method can be very useful, because it allows you to choose the prototype object for the object you want to create, without having to define a constructor function.

// Animal properties and method encapsulation
var Animal = {
  type: 'Invertebrates', // Default value of properties
  displayType: function() {  // Method which will display type of Animal

// Create new animal type called animal1 
var animal1 = Object.create(Animal);
animal1.displayType(); // Output:Invertebrates

// Create new animal type called Fishes
var fish = Object.create(Animal);
fish.type = 'Fishes';
fish.displayType(); // Output:Fishes

Access object values:

objectName[key] = value
  newObject[name]='Mark Brown'
objectName.key = value
  newObject.employer = ?

Notice that the keys in the example above are **not enclosed in quotation marks**. This is the default way of indicating keys in an object literal, but **there are times where you need to use quotation marks**. For instance if you need a *space* or *period* in a key, you'd need to use quotation marks around the key:

const ledZeppelin2 = {
  'lead singer': 'Robert Plant',
  'lead guitar': 'Jimmy Page',
When an object has a value that is a function, we refer to that key/value pair as a method. Here's an example of an object representing a mammal, that features an evolve method.

const mammal = {
  numEyes: 2,
  warmBlooded: true, 
  evolve: function() {
    console.log("I'm not mutating, I'm evolving.");
    mammal.numEyes ++;
console.log(`mammal has ${mammal.numEyes} eyes`);// mammal has 2 eyes
mammal.evolve();//I'm not mutating, i'm evolving.
console.log(`mammal has ${mammal.numEyes} eyes`);//mammal has 3 eyes

Getting values and running methods Once the object is created, you can get values and run object methods in one of two ways: dot notation ( ledZeppelin.singer) or with bracket notation (ledZeppelin2['lead singer']). Using the example objects from above, both ledZeppelin.singer and ledZeppelin2['lead singer'] would return the value 'Robert Plant'. Usually we ****use dot notation to get values from an object, but if you need to get a key with spaces or periods, you must use bracket notation.****

The same syntax is used to run methods on an object. In the mammal example above, we use dot notation to call the evolve method.

Note that just like functions outside of objects, an object method can take arguments.

const simpleCalculator = {
  add: function(a, b) {
    return a+b;

simpleCalculator.add(1, 1); // => 2

Define and create a single object, with the keyword new var car = new Object();

Define an object constructor, and then *create objects of the constructed type

  var car = function(wheels, seats, engine){
    this.wheels = wheels;
    this.seats = seats;
    this.engine = engine;

Choosing between an object and an array gets much easier when you can determine the purpose of each structure. Arrays closely fit the way that #books# store information. And objects fit the way that #newspapers# store information.

Arrays Order of Data is Most Important

var book = ['foreward', 'boyWhoLived', 'vanishingGlass', 'lettersFromNoOne', 'afterword'];

book[0] //'foreward'

Ojects: Data Label is Most Important

var newspaper = {
  sports: 'Arod Hits Home Run',
  business: 'GE stocks plunge',
  movies: 'Star Wars is a flog',

newspaper['business'] ||

Combining Objects and Arrays

  • Arrays within objects
  • Objects within arrays
  • Arrays within arrays
  • Objects within objects

What if you wanted to also store the number of pages in each chapter? it might be best to now fill your array with objects, like this:

var book = [
    {name:'foreward', pageCount: 14},
    {name:'boyWhoLived', pageCount: 18},
    {name:'vanishingGlass', pageCount: 13},
    {name:'lettersFromNoOne', pageCount: 17},
    {name:'afterword', pageCount: 19}

This maintains the order of our chapters and now we have the ability to name specific properties of each chapter. book[1]['pageCount']