Objects

What are Objects?

JavaScript objects are a fundamental data type in JavaScript. They are essentially dictionaries; an unordered collection of name/value pairs. To decide if you need to create an object, consider whether you can fit your details into the form of: *objectName* has a(n) *propertyName*. The name of objects take the data type of strings, whereas the values can be any type including a function; which will create an object method.

Creating an Object

You can create an object simply using object literal notation shown here. The general syntax is:

  • Define the object using let
  • Put the object name keeping to camel case notation
  • =
  • Opening curly bracket
  • New line per property, indented
  • The property name
  • A colon
  • The value e.g. a string or number
  • A comma at the end of the property
  • Continue for however many properties you have
  • The end curly bracket at the same indent level as the first
let myObject = {
    property1: 'value1',
	property2: 42,
}

Or use an object literal, which is a type of shorthand. This method is not recommended most of the time as it is less clear to someone reading the code.

let myObject = {property1: “String”, property2: 33, property3: “Another string”};

You may want to create an empty object to fill in later, these are some ways of doing that.

let obj1 = new Object();
let obj2 = {}; // Preferred
let obj3 = Object.create(Object.prototype);

When building an object, you should consider its privacy. Only certain properties should be able to change in value. To show that a property should not be altered, place an underscore (_) before the name of a property such as _name.

Constructor Functions

You can create constructor functions that create objects for you. It is key to make the arguments passed to your maker function be defined within your object.

function makerFunction(name, grade, letter){
    let madeObject = {}
    madeObject.name = name;
    madeObject.grade = grade;
    madeObject.letter = letter;
    return madeObject;
}
// Then call it with: 
myObject = makerFunction(“Adam”, 100, “A”);

Factory Functions

Factory functions are third way of defining objects.

function createPerson(name, age) {
    return {
        name,
        age
    };
}
let person2 = createPerson('Bob', 25);  

Comparing Objects

To compare objects, you can use ===. It checks that two things refer to the same object in the memory.

obj1 === obj2; // False unless they reference the same object

Accessing Object Properties

Use dot notation to find the associated value to an object property. There are two ways of doing the same thing, however if your name in the object also happens to be a reserved word, you need to use [].

myObject.property1;
myObject[property1];

You can assign a new key to your object using the following syntax.

myObject[newname] = value;

To assign a new value to an existing key.

objectName = {key:value};

You can also add a new property to an object.

myObject.newProperty = 'new';

To remove the value completely, leaving the key with an undefined value, just define it as null or undefined.

myObject.property1 = null;
myObject.property1 = undefined;

Or delete the property entirely with either of the following syntax.

delete myObject[name];
delete myObject.keyName;

Nested Objects and Arrays

As the value in the key: value pairs can be mostly anything, this can include another object or arrays. In the case of nested object, this would take the form of objectName : {object} in the parent object. To access the keys: values of the nested object, use dot notation.

object1.object2.key;

In the case of a nested array, this would take the form of arrayName : [array] in the parent object. To access this the indices of this use:

object1.array[i];

If an object is nested in an array, you can access the key: value pairs using:

array[i].key;

Object Methods

There are some useful built in methods when working with objects.

Object.keys(obj);: Returns and array of the object keys.

Object.entries(obj);: Returns and array of [key, value] pairs.

Object.assign(): Merges objects. Have the first parameter as the object you want to merge into and following parameters as objects to merge in.

obj.hasOwnProperty("property");: Returns true if the object has the property.

obj.valueOf();: Returns the primitive value of the object.

Looping

The general syntax for looping through the values of the keys in an object is:

for(let tempVar in object.key) {
}

Getters and Setters

Getters and setters are special methods that allow you to interact with an objects properties.

A getter is used to retrieve the value of a property, allowing you to define how the property should be returned. They can:

  • Perform an action on the data
  • Return different values using conditionals
  • Can use this.property instead of objectName.property
  • Makes functionality easier to understand
// Getter Syntax
get propertyName() {
    return this._propertyName; // _propertyName is the actual property name
}

// Getter Example
const person = {
    _name: 'Adam',
    get name() {
    return this._name; // Returns the value of the private _name property
    }
};

console.log(person.name); // Outputs: 'Adam'

A setter allows you to assign a value to a property. It defines how a property's value should be set.

// Setter Syntax
set propertyName(value) {
    this._propertyName = value; // Set the value of the internal property
}

// Setter Example
const person = {
    _name: 'Adam',
    set name(newName) {
    this._name = newName; // Sets the private _name property
    }
};

person.name = 'Bob'; // Uses the setter to assign a new value
console.log(person._name); // Outputs: 'Bob'

Setters and getters cannot share the same name as the property: You must distinguish the internal property (commonly prefixed with an underscore) from the getter/setter. For example, if the getter is name, the internal property is usually named _name.

Setters reassign values of existing properties within an object. When you assign a value using the setter, the value gets assigned to an internal property.

Best Practice

For best practice when creating an object remember:

  • Have properties set as _property
  • Use setters to set these
  • Use getters to return them nicely