Objects In Javascript - The Proper Guide
Tags: javascript, webdev, programming, oop
Published: 2020-05-14 06:14:28



| | | |
|-|-|-|
|  | _"Object are huge part of the Javascript language, and it at the core of many things we do. So learning how to use them is definitely essential. "_ | |
|

In JavaScript, almost <i>"everything"</i> is an object.
+ Booleans can be objects (if defined with the <i>new</i> keyword)
+ Numbers can be objects (if defined with the <i>new</i> keyword)
+ Strings can be objects (if defined with the <i>new</i> 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

Basically, all javaScript values, except primitives, are objects.

<hr/>
I think the best way to easily understand objects in javascript is to compare it with objects in real life objects.

Objects in real life have properties and also have things they can do, for an example <b>Car</b> object could have color, make and model year as its properties, but it also has things it can do, it could move and horn. Now an object in javascript is no different, it has properties and it can have things it can do.

So, for an instance we could have a User object in javascript and it properties would be an email, a username and a gender and it can also have things it can do in javascript these are called <b>methods</b> which are just functions, so a User object could have a Login method and a Logout Method. Another good example would be if we had a blog object which will represent a single blog on a website, now the properties of a blog object could be a title, the content and the author and the methods could be publish, unpublish or a method to delete the blog. So you can see how javascript objects and real life objects are quite similar, they both have properties and they both have things they can do but in javascript they are called methods which are simply functions. 

So, this idea of Objects is going to allow us to create this kind of data structures which represent certain things in our application code. 

# Creating Objects in Javascript
Even though javascript has some built in objects like the Date and Math object, it also allows us to create or define our own objects and we can do this in a variety of way.
+ Object Literal Notation
+ Object Constructor 
+ Constructor Function
+ Prototype Inheritance

# Using an Object Literal
The object literal notation allows us to create single objects.
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 gender:male) inside curly braces {}

The following example creates a new JavaScript object:
```javascript
let user = {
 name: "Jannet"
};
```
So, if you want to add more than one property you separate them with a comma, just remember not to add comma to the last one.
```javascript
let user = {
 name: "Jannet",
 age: 30,
 email: 'jannet@gmail.com',
 location: 'Nigeria',
 blogs: ["human resource management", "tech for the non-tech savvy"]
};
```
# Accessing The Object Properties
There are basically two ways of accessing an object properties.
+ Dot Notation 
+ Square Bracket Notation

<h3>Dot Notation </h3>
Let say we want to access the name property of our object.
```java
console.log(user.name);

// Output: Jannet
```
Perhaps later on in our code if you want to override or change the value of a property in our objects we could do this way:
```java
// we change the age property from 30 to 35
user.age = 35;
console.log(user.age)

// Output: 35
```
<h3> Square Bracket Notation </h3>
Let's say we want to access the name property of our user object, we use the a set of square brackets like so [].
```java
console.log(user['name'])
```
You can also update or change the name property like so:
```javascript
user["name"] = "Lanre"
console.log(user["name"]);
// Output: Lanre
```
You can also define object properties like so:
```javascript
let user = {
 "User Name": "Jannet"
};
```
But this types of properties are only accessed with the bracket notation like so:
```javascript
user["User Name"];
console.log(user["User Name"])
// Output: Jannet
```
They can also be used to pass variables, let say you want to access the location.
```javascript
const key = "location";
console.log(user[key]);
// Output: Nigeria
```
<h3>Adding Methods to Objects 👩</h3>
Methods are basically functions inside of an Object, which holds a piece of code. We can add a method called login to our user object like so:
```javascript
let user = {
 name: "Jannet",
 age: 30,
 email: 'jannet@gmail.com',
 location: 'Nigeria',
 blogs: ["human resource management", "tech for the non-tech savvy"],
 login: function() {
   console.log("the user is logged in");
  }
};
```
And we can call or invoke the method like so:
```javascript
user.login();

// Output: the user is logged in
```
<h3>Accessing object properties within the object methods</h3>
Let say we want to create a method in our object that prints out the text in the blog array of our object. first we'll need to access the the blog property, and we do so by using the <i>"this"</i> keyword in javascript. 

Now, the question is what is the <i>"this"</i> keyword ?

put simply the <i>this</i> keyword is a context object and it represents the context the current code is executing, so depending on where and how we use it value is going to be different. if you use <i>"this"</i> inside the root of the document, it value is going to refer to the global object which is the Window object. But if we use <i>"this"</i> inside of a method in our object the <i>"this"</i> keyword would refer to our user object.
```javascript
...
 printBlog: function() {
  console.log(this)
 }
...
// Output: the user object
```
So, we can use <i>"this"</i> keyword to access the blog property and print it values like so:
```javascript
...
 printBlog: function() {
  this.blog.forEach(blog => {
    console.log(blog)
  }) 
};
...
```
<h3>Deleting Properties</h3>
The <i>delete</i> keyword deletes a property from an object:
```javascript
let user = {
 name: "Jannet",
 age: 30,
 email: 'jannet@gmail.com',
 location: 'Nigeria',
 blogs: ["human resource management", "tech for the non-tech savvy"]
};

delete user.age 
```
<h3>Things To Note About The <i>delete</i> operator</h3>
+ The delete keyword deletes both the value of the property and the property itself.

+ After deletion, the property cannot be used before it is added back again.

+ The delete operator is designed to be used on object properties. It has no effect on variables or functions.

+ The delete operator should not be used on predefined JavaScript object properties. It can crash your application.
 
# Using an Object Constructor
Another way to create objects in JavaScript involves using the “Object” constructor. The Object constructor creates an object wrapper for the given value. This, used in conjunction with the “new” keyword allows us to initialize new objects like so:
```java
const user = new Object(); 
user.name = 'Jannet'; 
school.location = 'Nigeria'; 
school.age = 34; 
  
user.displayInfo = function(){ 
    console.log(`My ${user.name} i live in  
          in ${user.location} and am ${user.age} years old`); 
};
user.displayInfo();
//Output: 
```
Notice how i accessed the properties in the <i>displayInfo()</i> method, this approach is also accepted in Javascript if you dont want to use the <i>"this keyword"</i> you can directly access the properties.

NOTE: The two methods mentioned above are not well suited to programs that require the creation of multiple objects of the same kind, as it would involve repeatedly writing the above lines of code for each such object. To deal with this problem, we can make use of two other methods of object creation in JavaScript that reduces this burden significantly, as mentioned below:

# Using Constructor Function
Constructors in JavaScript, like in most other Object Oriented Programming  languages, provides a template sometimes called a blueprint for creation of objects. In other words, it defines a set of properties and methods that would be common to all objects initialized using the constructor.
Here is an example:
```java
function User(name,age, location) {
  this.name = name;
  this.age = age;
  this.language = language;
}

// creating new object
const object1 = new User("Bola", 20, "Nigeria");
const object2 = new User("Bola", 29, "New York");
```
<h3>The <i>this</i> keyword</h3>
Remember when i said the value of <i>this</i>, when used in an object, is the object itself.

However, in a constructor function <i>this</i> does not have a value. It is a substitute for the new object. The value of <i>this</i> will become the new object when a new object is created.

<h3>Adding a Property to a Constructor</h3>
You cannot add a new property to an object constructor the same way you add a new property to an existing object:
```javascript
  User.name = "Lanre";
```
To add a new property to a constructor, you must add it to the constructor function:
```javascript
  function User(name,age, location) {
   this.name = name;
   this.age = age;
   this.language = language;
   this.isArrogant = false;
}
```
<h3>Adding a Method to a Constructor</h3>
Adding methods to an constructor must be done inside the constructor function:
```javascript
  function User(name,age, location) {
   this.name = name;
   this.age = age;
   this.language = language;
   this.isArrogant = false;
   this.sayName = function() {
     console.log("My Name is "+ this.name)
 }
}
```
<h3>Built-in JavaScript Constructors</h3>
Here is the list of built in JavaScript constructors for native objects:
```java
 var object = new Object();      // A new Object object
 var string = new String();      // A new String object
 var number = new Number();      // A new Number object
 var boolean = new Boolean();    // A new Boolean object
 var array = new Array();        // A new Array object
 var regex = new RegExp();       // A new RegExp object
 var function = new Function();  // A new Function object
 var date = new Date();          // A new Date object
```
# JavaScript Object Prototypes
Another way to create objects involves using prototypes. All JavaScript objects inherit properties and methods from a prototype.
Browsers implement prototypes through the __proto__ property and this is how we’ll refer to it.
+ Date objects inherit from Date.prototype
+ Array objects inherit from Array.prototype
+ String object inherit from String.prototype
+ Number object inherit from Number.prototype
+ Boolean object inherit from Boolean.prototype
+ Person objects inherit from Person.prototype

NOTE: that the <i>Object.prototype</i> is on the top of the prototype inheritance chain.

<h3>Using the <i>prototype</i> Property</h3>
The JavaScript prototype property allows you to add new properties to object constructor function:
```javascript
  function User(name,age, location) {
   this.name = name;
   this.age = age;
}
 Person.prototype.isArrogant = "false";
```
And you can also add new methods to objects constructor function like so:
```javascript
  function User(name,age, location) {
   this.name = name;
   this.age = age;
}
User.prototype.sayName = function(){
  console.log("My name is " + this.name)
};
```
# ES5 New Object Methods
ECMAScript 5 added some new Object Methods to be aware of JavaScript.
We'll Look into some of them and their use case.

<h3>Object.defineProperty()</h3>
The static method <i>Object.defineProperty()</i> defines a new property directly on an object, or modifies an existing property on an object, and returns the object.
Here is an example:
```javascript
const object1 = {};

Object.defineProperty(object1, 'property1', {
  value: 42,
  writable: false
});

   object1.property1 = 77;
// throws an error in strict mode

   console.log(object1.property1);
// expected output: 42
```
<h3>Object.assign()</h3>
The <i>Object.assign()</i> method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.
It syntax Looks like this:
```javascript
  const targetObject = { a: 1, b: 2 };
  const sourceObject = { b: 4, c: 5 };

  const returnedTargetOject = Object.assign(target, source);

  console.log(targetObject);
  // expected output: Object { a: 1, b: 4, c: 5 }

  console.log(returnedTargetObject);
  // expected output: Object { a: 1, b: 4, c: 5 }
```
<h3>Object.create()</h3>
The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.
```java
  const User = {
  age: 0,
  printIntroduction: function() {
    console.log(`My name is ${this.name}. Am ${this.age} years old`);
  }
};

  const object1 = Object.create(person);

  object1.name = 'Steve';
  me.age = 34; // inherited properties can be overwritten

  object1.printIntroduction();
  // expected output: "My name is Steve. Am 34 years old"
```
<h3>Object.entries()</h3>
The <i>Object.entries()</i> method returns an array of a given object's own enumerable string-keyed property <i>[key, value]</i> pairs, in the same order as that provided by a for...in loop. (The only important difference is that a for...in loop enumerates properties in the prototype chain as well). 

The order of the array returned by Object.entries() does not depend on how an object is defined. If there is a need for certain ordering, then the array should be sorted first.
```javascript
  const obj = { foo: 'bar', baz: 42 };
  console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]

  // array like object
  const obj = { 0: 'a', 1: 'b', 2: 'c' };
  console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]
```
<h3>Object.freeze()</h3>
The <i>Object.freeze()</i> method freezes an object. A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed. In addition, freezing an object also prevents its prototype from being changed. freeze() returns the same object that was passed in.
```java
 const obj = {
  prop: 42
};

 Object.freeze(obj);

 obj.prop = 33;
 // Throws an error in strict mode

 console.log(obj.prop);
 // expected output: 42
```
<h3>Object.is()</h3>
The <i>Object.is()</i> method determines whether two values are the same value.
```javascript
const obj1 = {value: 20}
const obj2 = {value: 10}

Object.is(obj1, obj2);
// Output: false
```
<h3>Object.keys()</h3>
The <i>Object.keys()</i> method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.
```javascript
  const object1 = {
   a: 'somestring',
   b: 42,
   c: false
 };

  console.log(Object.keys(object1));
  // expected output: Array ["a", "b", "c"]
```
<h3>Object.hasOwnProperty()</i>
The <i>hasOwnProperty()</i> method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
```javascript
 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
```

<hr />

So, you can get a lot more stuff and play around each and every concept.

I had just gone through the Introduction in all concepts, so If you had any 
queries Just Ask in the response section.

Thanks for your time! ...


You can follow me on Instagram & Twitter @elechipro.

Reference From:
https://developer.mozilla.org/
https://www.w3schools.com/