Everything about JavaScript objects

Object-  In JavaScript, an object is a standalone entity, with properties and type. Compare it with a Car, for example. A car is an object, with properties. A car 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.  

In JavaScript, almost “everything” is an object. 

  • Booleans can be objects (if defined with the new keyword) 
  • Numbers can be objects (if defined with the new keyword) 
  • Strings can be objects (if defined with the new keyword) 
  • Dates are always objects 
  • Maths are always objects 
  • Regular expressions are always objects 
  • Arrays are always objects 
  • Functions are always objects 
  • Objects are always objects 

All JavaScript values, except primitives, are objects. 

Object values are written as name : value pairs (name and value separated by a colon). 

A JavaScript object is a collection of named values, the named values, in JavaScript objects, are called properties. 

*Object Methods 

Methods are actions that can be performed on objects. 

Object properties can be both primitive values, other objects, and functions. 

An object method is an object property containing a function definition. 

Property  Value 
fName  Riya 
lName  Sharma 
age  20 
eyeColor  blue 
fullName  function() {return this.firstName + ” ” + this.lastName;} 

*Creating a JavaScript Object 

With JavaScript, you can define and create your own objects. 

There are different ways to create new objects: 

  1. Create a single object, using an object initializer/literal. 
  2. Create a single object, with the keyword new. 
  3. Define an object constructor, and then create objects of the constructed type. 
  4. Create an object using Object.create(). 
  1. Using object initializers: 

Object initializers are also called object literals. “Object initializer” is consistent with the terminology used by C++。 This is the easiest way to create a JavaScript Object. Using an object literal, you both define and create an object in one statement. An object literal is a list of name:value pairs (like age:50) inside curly braces {}. 

The syntax for an object using an object initializer is: 

const obj = {
property1: value1, // property name may be an identifier
2: value2, // or a number
“property n”: value3, // or a string
}; 

2. Using the JavaScript Keyword new 

The following example create a new JavaScript object using new Object(), and then adds 4 properties: 

Example: 

const person = new Object();
person.firstName = “John”;
person.lastName = “Doe”;
person.age = 50;
person.eyeColor = “blue”; 

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

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. 

function Car(color, model, year) {
this.color = color;
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: 

const myCar = new Car(“Red”, “Talon TSi”, 1993); 

We can make many objects from single constructor with different properties 

4. Create an object using Object.create(). 

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. 

// Car properties and method encapsulation
const Car = {
type: “Alto”, // Default value of properties
displayType() {
// Method which will display type of Animal
console.log(this.type);
},
};// Create new animal type called animal1
const Car11 = Object.create(Car);
animal1.displayType(); // Logs: Alto 

*Objects and properties 

Properties are the values associated with a JavaScript object. Value may contain string, boolean, Array, function or object.  Like JavaScript variables, property names are case sensitive. Property names can only be strings or Symbols. A JavaScript object is a collection of unordered properties. Properties can usually be changed, added, and deleted, but some are read only.  

*Accessing properties 

You can access a property of an object by its property name. Property accessors come in two syntaxes: dot notation and bracket notation. For example, you could access the properties of the Car object as follows: 

// Dot notation
Car.color = “Red”;
Car.model = “Alto”;
Car.year = 1969;// Bracket notation
Car[“color”] = “Red”;
Car[“model”] = “Alto”;
Car[“year”] = 1969; 

*Enumerating Properties

There are three native ways to list/traverse object properties: 

1. for…in loops: This method traverses all of the enumerable string properties of an object as well as its prototype chain. 

2. Object.Keys(myobj): This method returns an array with only the enumerable own string property names (“keys”) in the object myObj, but not those in the prototype chain. 

3. Object.getOwnPropertyNames(myObj): This method returns an array containing all the own string property names in the object myObj, regardless of if they are enumerable or not. 

1. for…in loops: The block of code inside of the for…in loop will be executed once for each property. Looping through the properties of an object: 

Exa

const person = { 

  fname:"Kavita", 
  lname:"Korde", 
  age:25 
}let txt = ""; 
for (let x in person) { 
  txt += person[x] + " "; 
} 
document.getElementById("demo").innerHTML = txt; 
Output: 
Kavita Korde 25

 

 

2.  Object.keys(myObj): The Object.keys() static method returns an array of a given object’s own enumerable string-keyed property names. 

const object1 = { 

  a: ‘somestring’, 

  b: 42, 
  c: false 
console.log(Object.keys(object1)); 
Output: 
Array ["a", "b", "c"]

3. Object.getOwnPropertyNames(myObj):The Object.getOwnPropertyNames() static method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object. 

const object1 = { 

a: 1, 
c: 3 
Output:
Array ["a", "b", "c"]
b: 2,} 
console.log(Object1.getOwnPropertyNames())

*Deleting properties

You can remove a non-inherited property using the delete operator. The following code shows how to remove a property. 

const person = { 
  fname:"Kavita", 
  lname:"Korde", 
  age:25 
}; 
delete person.age; 
Console.log(person.age) 
Output: 
Undefined


*Adding New Properties: 
You can add new properties to an existing object by simply giving it a value. 
Assume that the person object already exists – you can then give it new properties: 

const person = { 
  fname:"Kavita", 
  lname:"Korde", 
  age:25 
}; 
person.hobby=’singing’ 
Console.log(person.fname + " likes " + person.hobby+ "."); 
Output: 
Kavita likes singing. 

*Inheritance 

All objects in JavaScript inherit from at least one other object. The object being inherited from is known as the prototype, and the inherited properties can be found in the prototype object of the constructor. 

*Defining methods 

method is a function associated with an object, or, put differently, a method is a property of an object that is a function. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object. 

const person = { 
  fname:"Kavita", 
  lname:"Korde", 
  age:25 
fullName : function() { 
    return this.fName + " " + this.lName; 
  } 
}; 
Console.log(person.fullName()); 
Output: 
Kavita Korde 

*What is this? 

In JavaScript, the this keyword refers to an object. 

Which object depends on how this is being invoked (used or called). 

The this keyword refers to different objects depending on how it is used: 

In an object method, this refers to the object. 
Alone, this refers to the global object. 
In a function, this refers to the global object. 
In a function, in strict mode, this is undefined. 
In an event, this refers to the element that received the event. 
Methods like call(), apply(), and bind() can refer this to any object. 

 *JavaScript Object Accessors 

JavaScript Accessors (Getters and Setters) 

ECMAScript 5 (ES5 2009) introduced Getter and Setters. 

Getters and setters allow you to define Object Accessors (Computed Properties). 

1.JavaScript Getter (The get Keyword) 

This example uses a fullName property to get the value of the fname and lname  property. 

const person = { 
  fname:"Kavita", 
  lname:"Korde", 
  age:25 
get fullName () { 
    return this.fName + " " + this.lName; 
  } 
}
Console.log(person.fullName);  
Output: 
Kavita Korde 
2.JavaScript Setter (The set Keyword) 

This example uses a fname and lname property to set the value of the fullName property. 

const person = { 
  fname:"", 
  lname:"", 
  age:”” 
get getage (value) { 
    this.age = value; 
  } 
} 
person.getage = "25"; 
Console.log(person.age); 
Output: 
25 
Why Using Getters and Setters? 
  • It gives simpler syntax 
  • It allows equal syntax for properties and methods 
  • It can secure better data quality 
  • It is useful for doing things behind-the-scenes 

Object.defineProperty() 

The Object.defineProperty() method can also be used to add Getters and Setters: 

// Define object
const obj = {counter : 0};
// Define setters and getters
Object.defineProperty(obj, "reset", {
  get : function () {this.counter = 0;}
});
Object.defineProperty(obj, "increment", {
  get : function () {this.counter++;}
});
Object.defineProperty(obj, "decrement", {
  get : function () {this.counter--;}
});
Object.defineProperty(obj, "add", {
  set : function (value) {this.counter += value;}
});
Object.defineProperty(obj, "subtract", {
  set : function (value) {this.counter -= value;}
});
// Play with the counter:
obj.reset;
obj.add = 5;
obj.subtract = 1;
obj.increment;
obj.decrement; 
Console.log(obj); 
Output: 
4 

*Comparing objects 

In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true. 

// Two variables, two distinct objects with the same properties
const fruit = { name: “apple” };
const fruitbear = { name: “apple” };

fruit == fruitbear; // return false
fruit === fruitbear; // return false
 // Two variables, a single object

const fruit1 = { name: “apple” };
const fruitbear1 = fruit; // Assign fruit object reference to fruitbear

// Here fruit and fruitbear are pointing to same object
fruit1 == fruitbear1; // return true
fruit1 === fruitbear1; // return true

fruit.name = “grape”;
console.log(fruitbear); // { name: “grape” }; not { name: “apple” } 

 

*Object methods: 

  1. Object.assign()

 The Object.assign() static method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object. Properties in the target object are overwritten by properties in the sources if they have the same key. Later sources’ properties overwrite earlier ones.It is used to clone and merge objects. 

const target = { a: 1, b: 2 }; 
const source = { b: 4, c: 5 }; 
 const returnedTarget = Object.assign(target, source); 
 console.log(target); 
// expected output: Object { a: 1, b: 4, c: 5 } 
 console.log(returnedTarget === target); 
// expected output: true 

    2.Object.create() 

The Object.create() static method creates a new object, using an existing object as the prototype of the newly created object. 

const person = { 
Name:John 
  isHuman: false, 
  printIntroduction: function() { 
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`); 
  } 
}; 
const me = Object.create(person); 
me.name = 'Matthew'; // "name" is a property set on "me", but not on "person" 
me.isHuman = true; // Inherited properties can be overwritten 
me.printIntroduction(); 
// expected output: "My name is Matthew. Am I human? true" 
  1. Object.defineProperties()

The Object.defineProperties() static method defines new or modifies existing properties directly on an object, returning the object. 

const object1 = {}; 
 Object.defineProperties(object1, { 
  property1: { 
    value: 42, 
    writable: true 
  }, 
property2: {} 
}); 
console.log(object1.property1); 
// expected output: 42 

    4. Object.entries() 

The Object.entries() static method returns an array of a given object’s own enumerable string-keyed property key-value pairs. 

const object1 = { 
  a: 'somestring', 
  b: 42 
}; 
for (const [key, value] of Object.entries(object1)) { 
  console.log(`${key}: ${value}`); 
} 
// expected output: 
// "a: somestring" 
// "b: 42" 
  1. freeze()

The Object.freeze() static method freezes an object. Freezing an object prevents extensions and makes existing properties non-writable and non-configurable. A frozen object can no longer be changed: new properties cannot be added, existing properties cannot be removed, their enumerability, configurability, writability, or value cannot be changed, and the object’s prototype cannot be re-assigned. freeze() returns the same object that was passed in. 

Freezing an object is the highest integrity level that JavaScript provides. 

const obj = { 
  prop: 42 
}; 
 Object.freeze(obj); 
 obj.prop = 33; 
// Throws an error in strict mode 
 console.log(obj.prop); 
// expected output: 42 
  1. Object.fromEntries()

The Object.fromEntries() static method transforms a list of key-value pairs into an object. 

const entries = new Map([ 

  ['foo', 'bar'], 
  ['baz', 42] 
]); 
 const obj = Object.fromEntries(entries); 
 console.log(obj); 
// expected output: Object { foo: "bar", baz: 42 } 
  1. Object.getOwnPropertyDescriptor()

The Object.getOwnPropertyDescriptor() static method returns an object describing the configuration of a specific property on a given object (that is, one directly present on an object and not in the object’s prototype chain). The object returned is mutable but mutating it has no effect on the original property’s configuration. 

const object1 = { 
  property1: 42 
}; 
 const descriptor1 = Object.getOwnPropertyDescriptor(object1, 'property1'); 
 console.log(descriptor1.configurable); 
// expected output: true 
 console.log(descriptor1.value); 
// expected output: 42 
  1. Object.getOwnPropertyDescriptors()

The Object.getOwnPropertyDescriptors() static method returns all own property descriptors of a given object. 

const object1 = { 
  property1: 42 
}; 
const descriptors1 = Object.getOwnPropertyDescriptors(object1); 
 console.log(descriptors1.property1.writable); 
// expected output: true 
 console.log(descriptors1.property1.value); 
// expected output: 42 
  1. Object.getOwnPropertyNames()

The Object.getOwnPropertyNames() static method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object. 

const object1 = { 
  a: 1, 
  b: 2, 
  c: 3 
}; 
console.log(Object.getOwnPropertyNames(object1)); 
// expected output: Array ["a", "b", "c"] 
  1. Object.getOwnPropertySymbols()

The Object.getOwnPropertySymbols() static method returns an array of all symbol properties found directly upon a given object. 

const object1 = {}; 
const a = Symbol('a'); 
const b = Symbol.for('b'); 
object1[a] = 'localSymbol'; 
object1[b] = 'globalSymbol'; 
const objectSymbols = Object.getOwnPropertySymbols(object1); 
console.log(objectSymbols.length); 
// expected output: 2 
  1.  Object.getPrototypeOf()

The Object.getPrototypeOf() static method returns the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object. 

const prototype1 = {}; 
const object1 = Object.create(prototype1); 
console.log(Object.getPrototypeOf(object1) === prototype1); 
// expected output: true 
  1. Object.hasOwn()

The Object.hasOwn() static method returns true if the specified object has the indicated property as its own property. If the property is inherited, or does not exist, the method returns false. 

const object1 = { 
  prop: 'exists' 
}; 
console.log(Object.hasOwn(object1, 'prop')); 
// expected output: true 
 console.log(Object.hasOwn(object1, 'toString')); 
// expected output: false 
 console.log(Object.hasOwn(object1, 'undeclaredPropertyValue')); 
// expected output: false 
  1. Object.prototype.hasOwnProperty()

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). 

const object1 = {}; 
object1.property1 = 42; 
 console.log(object1.hasOwnProperty('property1')); 
// expected output: true 
 console.log(object1.hasOwnProperty('toString')); 
// expected output: false 
 console.log(object1.hasOwnProperty('hasOwnProperty')); 
// expected output: false 
  1. Object.is()

The Object.is() static method determines whether two values are the same value. 

Syntax :
Object.is(value1, value2)
Parameters 
value1 
The first value to compare. 
value2 
The second value to compare. 
Return value 
A boolean indicating whether or not the two arguments are the same value. 
  1. Object.isExtensible()

The Object.isExtensible() static method determines if an object is extensible (whether it can have new properties added to it). 

console.log(Object.isExtensible(object1)); 
// expected output: true 
 Object.preventExtensions(object1); 
 console.log(Object.isExtensible(object1)); 
// expected output: false 
  1. Object.isFrozen()

The Object.isFrozen() static method determines if an object is frozen. 

const object1 = { 
  property1: 42 
}; 
console.log(Object.isFrozen(object1)); 
// expected output: false 
 Object.freeze(object1); 
 console.log(Object.isFrozen(object1)); 
// expected output: true 
  1. Object.prototype.isPrototypeOf()

The isPrototypeOf() method checks if an object exists in another object’s prototype chain. 

function Foo() {} 
function Bar() {} 
 Bar.prototype = Object.create(Foo.prototype); 
 const bar = new Bar(); 
 console.log(Foo.prototype.isPrototypeOf(bar)); 
// expected output: true 
console.log(Bar.prototype.isPrototypeOf(bar)); 
// expected output: true 
  1. Object.isSealed()

The Object.isSealed() static method determines if an object is sealed. 

const object1 = { 
  property1: 42 
}; 
console.log(Object.isSealed(object1)); 
// expected output: false 
Object.seal(object1); 
console.log(Object.isSealed(object1)); 
// expected output: true 
  1. Object.keys()

The Object.keys() static method returns an array of a given object’s own enumerable string-keyed property names. 

const object1 = { 
  a: 'somestring', 
  b: 42, 
  c: false 
}; 
console.log(Object.keys(object1)); 
// expected output: Array ["a", "b", "c"] 
  1. Object.preventExtensions()

The Object.preventExtensions() static method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). It also prevents the object’s prototype from being re-assigned. 

const object1 = {}; 
 Object.preventExtensions(object1); 
 try { 
  Object.defineProperty(object1, 'property1', { 
    value: 42 
  }); 
} catch (e) { 
  console.log(e); 
  // expected output: TypeError: Cannot define property property1, object is not extensible 
} 
  1. Object.prototype.propertyIsEnumerable()

The propertyIsEnumerable() method returns a boolean indicating whether the specified property is the object’s enumerable own property. 

const object1 = {}; 
const array1 = []; 
object1.property1 = 42; 
array1[0] = 42; 
console.log(object1.propertyIsEnumerable('property1')); 
// expected output: true 
console.log(array1.propertyIsEnumerable(0)); 
// expected output: true 
console.log(array1.propertyIsEnumerable('length')); 
// expected output: false 
  1. Object.seal()

The Object.seal() static method seals an object. Sealing an object prevents extensions and makes existing properties non-configurable. A sealed object has a fixed set of properties: new properties cannot be added, existing properties cannot be removed, their enumerability and configurability cannot be changed, and its prototype cannot be re-assigned. Values of existing properties can still be changed as long as they are writable. seal() returns the same object that was passed in. 

const object1 = { 
  property1: 42 
}; 
Object.seal(object1); 
object1.property1 = 33; 
console.log(object1.property1); 
// expected output: 33 
 delete object1.property1; // Cannot delete when sealed 
console.log(object1.property1); 
// expected output: 33 
  1. Object.setPrototypeOf()

The Object.setPrototypeOf() method sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null. 

Syntax 

Object.setPrototypeOf(obj, prototype)
Copy to Clipboard 

Parameters 

obj 

The object which is to have its prototype set. 

prototype 

The object’s new prototype (an object or null). 

Return value 

The specified object. 

  1. Object.prototype.toLocaleString()

The toLocaleString() method returns a string representing the object. This method is meant to be overridden by derived objects for locale-specific purposes. 

const date1 = new Date(Date.UTC(2012, 11, 20, 3, 0, 0)); console.log(date1.toLocaleString(‘ar-EG’)); 

// expected output: “٢٠‏/١٢‏/٢٠١٢ ٤:٠٠:٠٠ ص” 

const number1 = 123456.789; 

console.log(number1.toLocaleString(‘de-DE’)); 

// expected output: “123.456,789” 

  1. Object.prototype.toString()
The toString() method returns a string representing the object. This method is meant to be overridden by derived objects for custom type conversion logic. 
function Dog(name) { 
  this.name = name; 
} 
const dog1 = new Dog('Gabby'); 
Dog.prototype.toString = function dogToString() { 
  return `${this.name}`; 
}; 
console.log(dog1.toString()); 
// expected output: "Gabby" 
  1. Object.prototype.valueOf()

The valueOf() method of Object converts the this value to an object. This method is meant to be overridden by derived objects for custom type conversion logic. 

function MyNumberType(n) { 
  this.number = n; 
} 
MyNumberType.prototype.valueOf = function() { 
  return this.number; 
}; 
const object1 = new MyNumberType(4); 
console.log(object1 + 3); 
// expected output: 7 
  1. Object.values()

The Object.values() static method returns an array of a given object’s own enumerable string-keyed property values. 

const object1 = { 
  a: 'somestring', 
  b: 42, 
  c: false 
}; 
console.log(Object.values(object1)); 
// expected output: Array ["somestring", 42, false] 

Reference :

https://www.w3schools.com/js/js_objects.asp

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object