Getting Started with JavaScript Object

Originally published by Zell Liew at https://scotch.io

An object is a type of data in JavaScript. It's the only value you can pass around as variables besides primitives. For this reason, objects are really important in JavaScript.

In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight, a material it is made of, etc. The same way, JavaScript objects can have properties, which define their characteristics.

Table of Contents

  • What are objects
  • Object values
  • Getting the value of a property
  • Setting the value of a property
  • Deleting properties
  • Functions are Objects in JavaScript
  • Exercises to help you get better with objects 

What are objects

An object in JavaScript is a type of data that contains key-value pairs.

You can create objects by writing these key-value pairs within curly braces. If you intend to create multiple key-value pairs, you need to separate each pair with commas, like this:

const anObject = {
 key1: 'value1',
 key2: 'value2',
 key3: 'value3'
 // ...
}

Each key gives you a reference to a value. If you imagine an English dictionary, the keys are the words while the values are the definition of each word.

const dictionary = {
 dream: "a series of thoughts, images, and sensations occurring in a person's mind during sleep",
 happy: "feeling or showing pleasure or contentment",
 // ...
}

Since object stores key-value pairs, another analogy you can use is to compare objects in JavaScript with objects in real life.

For example, you can observe the device you're using to read this lesson. What device is this? What's its size? What's its operating system?

If you put these information together into a JavaScript object, it'd look like this:

const macbook = {
 operatingSystem: 'macOS Sierra',
 screenResolution: '2880x1800',
 screenSize: '15.4 inch',
 usbPorts: 2,
 hdmiPort: 1,
 storage: '512gb'
 // ... Other specs
}

Object values

Objects can contain any value that's valid in JavaScript. This means you can store primitives (like Strings and Numbers) and other objects.

const anObject = {
 string: 'Yay',
 number: 1,
 boolean: true,
 nullPrimitive: null,
 undefinedPrimitive: undefined,
 anotherObject: {},
 afunction: function () {} // more on functions later
 anArray: [] // more on array in the next lesson
}

Getting the value of a property

Keys are also called properties. You can use two methods to get the value of a property

The first method is through the dot notation, where you write the name of the object, followed by., followed by the property name:

const prop = object.property

So, if you'd like to get the storage of the macbook we declared above, you can write macbook.storage

const macbookStorage = macbook.storage
console.log(macbookStorage) // 512gb

The second method is through the bracket notation. Here, you write the name of the object, followed by a string of the property in square brackets ([]).

const macbookStorage = macbook['storage']
console.log(macbookStorage) // 512gb

Both methods work.

Normally, you'll use the dot notation. You'll only use the bracket notation in special occasions where the dot notation doesn't work. These special occasions include:

  1. When your property name is an invalid identifier
  2. When you need get the value of a property through a variable

Invalid identifiers

When you declare variables in JavaScript, you need to adhere to four rules:

  1. The variable must be written as a single word
  2. The variable must consist only of letters, numbers or underscores (0-9, a-z, A-Z, _).
  3. The variable cannot begin with a number.
  4. The variable cannot be any of these reserved keywords

If your variable follows these four rules, it's a valid identifier; if your variable doesn't follow any of these rules, it's an invalide identifier.

Objects can have invalid identifiers as properties. Here's one example:

const ObjWithInvalidIdentifer = {
 'First Name': 'Zell'
}

When you have an invalid identifier, you can't use the dot notation. You need to use the bracket notation:

const firstName = ObjWithInvalidIdentifer.First Name // Syntax Error: Unexpected identifier
const firstName2 = ObjWithInvalidIdentifer['First Name'] // Zell

Of course, when you create objects, try to make properties with valid identifiers so you can use the dot notation. Don't make life hard for yourself!

Getting the value of a property through a variable.

When you write more advanced code, you may need to get the value of a property through a variable. In this case, you can only use the bracket notation.

For example, let's say you store the property to search in a variable called propertyToGet.

const propertyToGet = 'storage'

There's no property called propertyToGet in the object, so you can't use the dot notation. If you try doing it, you'll get undefined.

const storageWithDotNotation = macbook.propertyToGet
console.log(storageWithDotNotation) // undefined

You can only use the bracket notation, like this:

const macbookStorage = macbook[propertyToGet]
console.log(macbookStorage) // 512gb

That's all you need to know about getting property values. Let's move on and learn to set property values.

Setting the value of a property

You can set the value of a property either with the dot notation or the bracket notation. Likewise, the dot notation is always preferred.

// Dot notation
macbook.storage = '256gb'

// Bracket notation
macbook[‘usbPorts’] = 2

console.log(macbook)
// {
//  storage: ‘256gb’,
//  usbPorts: 2
// }

Deleting properties

You can delete key-value pairs from objects with the delete keyword. To do so, you write delete, followed by the property either in dot or bracket notation.

delete object.property

Here’s an example where we delete the storage property from the macbook Object.

delete macbook.storage
console.log(macbook)
// The storage property is already deleted, hence you don’t see it anymore when you console.log it
// {
//  usbPorts: 2
// }

Functions are Objects in JavaScript

Functions are a special kind of Object in JavaScript. It can have properties too (even though you’d most likely won’t declare any).

// You can add properties to functions
function sayName () {}
sayName.property = ‘Hallelujah’

console.log(sayName.property)
// Hallelujah

Since functions are objects, you can write functions as values in objects. The properties that contain functions as their values are called methods.

const anObject = {
 aMethod: function() {
   // Do something in function
 }
}

In the following example, we say playMusic is a method of macbook.

const macbook = {
 playMusic: function () {
   /* some code to play music */
 }
}

Since methods are functions, they behave exactly like functions.

To call a method, you write parenthesis () after getting the method through the dot or bracket notation

// Calling a method with the dot notation
macbook.playMusic()

// Calling a method with the bracket notation
macbook’playMusic’

You can also add arguments to methods, just like normal functions:

const greeter = {
 sayHello: function (name) {
   console.log('Hello ’ + name + ‘!’)
 }
}

greeter.sayHello(‘Zell’)
// Hello Zell!

You may hear phrases like “higher order functions” and “functions are first class objects” when you browse outside tutorials. Ignore these phrases. They both mean functions are objects, which means you can pass functions around as a variable. People like to introduce important-sounding jargons to make functions sound more amazing (and confusing) than they really are.

Exercises to help you get better with objects

You’ll use a lot of objects in JavaScript. Make sure you know them inside-out. Here are some exercises to use can for practice:

  1. Make an empty object
  2. Make a property for your object with the dot notation. Give it a value
  3. Make a property for your object with the bracket notation. Give it a value
  4. Get the value of a property with the dot notation
  5. Get the value of a property with the square bracket notation
  6. Set the value of a property with the dot notation
  7. Set the value of a property with the square bracket notation
  8. Make a method. Call this method
  9. Make a method that takes in an argument. Call this method

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about JavaScript

The Complete JavaScript Course 2019: Build Real Projects!

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

JavaScript Bootcamp - Build Real World Applications

The Web Developer Bootcamp

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

New ES2019 Features Every JavaScript Developer Should Know

Best JavaScript Frameworks, Libraries and Tools to Use in 2019

JavaScript Basics Before You Learn React

Build a CMS with Laravel and Vue

Google’s Go Essentials For Node.js / JavaScript Developers

#javascript #objective-c #web-development

Getting Started with JavaScript Object
1 Likes9.95 GEEK