Categories
javascript

JavaScript Fundamentals: Objects

JavaScript Fundamentals: Objects

Introduction to JavaScript Objects

Declaring an object:

const myObject ={
   // information about object
}

Objects can hold key-value expressions, arrays and even functions.

These will be separated in the object by commas, not semicolons.

Key-value expressions are written as key : value.

const myPerson ={
   firstName: john,
   lastName: hassel,
   age: 33,
   homestate: colorado,
   getFullName: function(){          // note formatting a function as a key:value
   return `${this.firstName} ${this.lastName}`   //note: template literals between backticks  `` 
   }
}

To access a key-value pair from an object, use dot notation, i.e. myPerson.firstName

Within any function within an object, refer to local variables using the this keyword, i.e. return this.firstName + this.lastName

console.log(myPerson.getFullName()); 
// this would return "john hassel"

To add new elements to an object, use dot notation to specify the new name of the key and assign it to a value.

myPerson.favoriteColor = "blue";
myPerson.favoriteFood = "peach";

Object Methods

To duplicate and object and not alter the original object, use the Object.assign() method.

const myDuplicatePerson = Object.assign({}, myPerson);

To get just the keys in an object without the values, use the Object.keys() method. Keys will be returned in an array.

let myPersonKeys = Object.keys(myPerson)
console.log(myPersonKeys);
   // returns: ["firstName", "lastName", "age", "homestate", "getFullName", "favoriteColor", "favoriteFood"]

To get just the values in an object without the keys, use the Object.values() method. Values will be returned in an array.

let myPersonValues = Object.values(myPerson);
console.log(myPersonValues);
   // returns: ["john", "hassel", 33, "colorado", ƒ, "blue", "peach"]

To check to see if an object has a certain property/key, use the hasOwnProperty method. This returns a boolean.

console.log(myPerson.hasOwnProperty('middleName'));
// returns false for our example.

LeaNakamura's avatar

By LeaNakamura

I'm a Brooklyn-based web development student, musician and textile artist originally from Maui, Hawaii.

Leave a comment

Design a site like this with WordPress.com
Get started