Leran JavaScripts

Get started with JS Objects

JavaScript Object Definition

Methods for Defining JavaScript Objects
Using::
an Object Literal
the new Keyword
an Object Constructor
Object.assign()
Object.create()
Object.fromEntries()


JavaScript Object Literal

An object literal is a list of property names:values inside curly braces {}.


{firstName:"John", lastName:"Doe", age:28};
              
Creating a JavaScript Object
Examples:
Create an empty JavaScript object using {}, and add properties:

// Create an Object
const person = {};

// Add Properties
person.firstName = "John";
person.lastName = "Doe";
person.age = 28;
              
Create an empty JavaScript object using new Object(), and add properties:

// Create an Object
const person = new Object();

// Add Properties
person.firstName = "John";
person.lastName = "Doe";
person.age = 28;
              
Object Constructor Functions
To create an object type we use an object constructor function.
Object Type Person
       
function Person(first, last, age) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
}
              
JavaScript Object Prototypes
All JavaScript objects inherit properties and methods from a prototype.
Example:

function Person(first, last, age) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
}

const myFather = new Person("John", "Doe", 28);
const myMother = new Person("Sally", "Rally", 48);
              
To add a new property to a constructor, you must add it to the constructor function:

Person.nationality = "English";
              

function Person(first, last, age) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.nationality = "English";
}
              
The JavaScript prototype property also allows you to add new methods to objects constructors:
Example::

function Person(first, last, age) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
}

Person.prototype.name = function() {
  return this.firstName + " " + this.lastName;
};
JavaScript Object Methods
General Methods
JavaScript Object.assign()

The Object.assign() method copies properties from one or more source objects to a target object. Example::

// Create Target Object
const person1 = {
  firstName: "John",
  lastName: "Doe",
  age: 28
};

// Create Source Object
const person2 = {firstName: "Anne",lastName: "Smith"};

// Assign Source to Target
Object.assign(person1, person2)
              
JavaScript Object.entries()
Object.entries() returns an array of the key/value pairs in an object:
Example::

const person = {
  firstName : "John",
  lastName : "Doe",
  age : 28
};

let text = Object.entries(person);
              
use objects in loops and maps:

const fruits = {Bananas:300, Oranges:200, Apples:500};
let text = "";
for (let [fruit, value] of Object.entries(fruits)) {
  text += fruit + ": " + value + "
"; }
map:

const fruits = {Bananas:300, Oranges:200, Apples:500};

const myMap = new Map(Object.entries(fruits));
              
JavaScript Object.fromEntries()
This method creates an object from a list of key/value pairs::

const fruits = [
  ["apples", 300],
  ["pears", 900],
  ["bananas", 500]
];

const myObj = Object.fromEntries(fruits);
              
JavaScript Object.values()
Object.values() returns a single dimension array of the object values:

const person = {
  firstName : "John",
  lastName : "Doe",
  age : 28
};

let text = Object.values(person);
              
JavaScript Object.groupBy()
The Object.groupBy() method groups elements of an object according to string values returned from a callback function.
The Object.groupBy() method does not change the original object.

// Create an Array
const fruits = [
  {name:"apples", quantity:300},
  {name:"bananas", quantity:500},
  {name:"oranges", quantity:200},
  {name:"kiwi", quantity:150}
];
// Callback function to Group Elements
function myCallback({ quantity }) {
  return quantity > 200 ? "ok" : "low";
}
// Group by Quantity
const result = Object.groupBy(fruits, myCallback);
                
JavaScript Object.keys()
This method returns an array with the keys of an object.

// Create an Object
const person = {
  firstName: "John",
  lastName: "Doe",
  age: 28
};
// Get the Keys
const keys = Object.keys(person);
              
JavaScript for...in Loop
for...in statement loops through the properties of an object.
Syntax
Looping through the properties of an object:

const person = {
  fname:" John",
  lname:" Doe",
  age: 25
};

for (let x in person) {
  txt += person[x];
}
              
JavaScript Object Accessors
JavaScript Accessors (Getters and Setters) JavaScript Getter (The get Keyword)
This example uses a lang property to get the value of the language property.

// Create an object:
const person = {
  firstName: "John",
  lastName: "Doe",
  language: "en",
  get lang() {
    return this.language;
  }
};
// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.lang;
               
JavaScript Setter (The set Keyword)
This example uses a lang property to set the value of the language property.

const person = {
  firstName: "John",
  lastName: "Doe",
  language: "",
  set lang(lang) {
    this.language = lang;
  }
};
// Set an object property using a setter:
person.lang = "en";
// Display data from the object:
document.getElementById("demo").innerHTML = person.language;
              
JavaScript Function or Getter?
  
const person = {
  firstName: "John",
  lastName: "Doe",
  fullName: function() {
    return this.firstName + " " + this.lastName; 
  }
};
// Display data from the object using a method:
document.getElementById("demo").innerHTML = person.fullName();
              
JavaScript Object Protection

Using const
The most common way to protect an object from being changed is by using the const keyword.
With const you can not re-assign the object, but you can still change the value of a property, delete a property or create a new property.

JavaScript Object.preventExtensions()
The Object.preventExtensions() method prevents adding properties to an object.

// Create Object
const person = {firstName:"John", lastName:"Doe"};
// Prevent Extensions
Object.preventExtensions(person);
// This will throw an error
person.nationality = "English";
          
Arrays can be prevented from extensions too:

// Create Array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
Object.preventExtensions(fruits);
// This will throw an error:
fruits.push("Kiwi");
          
JavaScript Object.isExtensible()
You can use Object.isExtensible() to check if an object is extensible.
The Object.isExtensible() returns true if an object is extensible.

// Create Object
const person = {firstName:"John", lastName:"Doe"};
// Prevent Extensions
Object.preventExtensions(person);
// This will return false
let answer = Object.isExtensible(person);
// Create Array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
// Prevent Extensions
Object.preventExtensions(fruits);
// This will return false
let answer = Object.isExtensible(fruits);