Objects In JavaScript

Objects In JavaScript

Guide On Objects In JavaScript And Its Methods

What Are Objects

An object is a data type that can take in collections of key-value pairs.

A major difference between an object and other data types such as strings and numbers in JavaScript is that objects can store different types of data as its values. On the other hand, primitive data types such as numbers and strings can store only numbers and strings, respectively, as their values.

The key, also known as the property name, is usually a string. If any other data type is used as a property name other than strings, it would be converted into a string.

The most recognizable feature of an object is the brackets which contain the key-value pair.

const emptyObject = {};
console.log(typeof emptyObject); //'object'

Need Of Objects

If you declare multiple variables to hold different values, this can make your program messy and clunky.

For instance, if you need to store three characteristics each for 10 individuals, having 30 variables individually declared can make your program appear less organized.

So you need a way to group values with similar characteristics together to make your code more readable. And in JavaScript, objects work well for this purpose. Unlike other data types, objects are capable of storing complex values. Because of this, JavaScript relies heavily on them.

Creating a JavaScript Object

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

There are different ways to create new objects:

  • Create a single object, using an object literal.

  • Create a single object, with the keyword new.

  • Create an object using Object.create().

Using an object literal.

This is the easiest way to create a JavaScript Object.

Using an object literal, you both define and create an object in one statement.

Example:

const person = {firstName:"Pujari", lastName:"Raj", age:21, eyeColor:"blue"};

Using the JavaScript Keyword new

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

Example

const person = new person();
person.firstName = "Pujari";
person.lastName = "Raj";
person.age = 21;
person.eyeColor = "blue";

Object. create()

JavaScript object.create() method is used to create a new object with the specified prototype object and properties. Object.create() method returns a new object with the specified prototype object and properties.

Example:

// creating a function which will be the
// prototype for the object to be created later
    function fruits() {
        this.name = 'fruit 1';
        this.season = 'summer';
    }

    // creating a function to whose object
    // will inherit properties from the
    // prototype using object.create() method
    function apple() {
    fruits.call(this);
    }

    // creating an object of the apple function which
    // will have properties of the prototype
    // object i.e. fruits
    apple.prototype
    = Object.create(fruits.prototype);
    const app = new apple();

    // Displaying the created object
    console.log(app.name);
    console.log(app.season);

JavScript Object Methods

  • Shallow copy — Object.assign()

  • Deep copy — JSON.parse() & JSON.stringify()

  • Object.create()

  • Object.entries()

  • Object.keys()

  • Object.values()

  • Object.freeze()

Copying an Object

You can’t use the typical assignment operation to copy an object in JS as that will only lead to creating a reference to the same object.

Example:

let newObj = obj;
obj.year = 2023;
console.log(newObj.year) // 2023

Object.create()

You can also create an object with Object.create() function this has additional flexibility in that you can choose what will be the prototype of your new object.

Example:

let createObj = Object.create(obj);
console.log(createObj);  //{}
createObj.name = “Pujari Raj”;
console.log(createObj.speak());// My Name is Pujari Raj and this is year 2023

In this example, obj is the prototype from which createdObj is created. Which means it can use properties of prototypes due to inheritance. That’s why we can use speak() method without declaring that in createdObj.

Object.entries()

This is a simple function that converts JS objects to an array of arrays. With inner array are a pair of keys and the value of the object. Let’s check out a self-explanatory example

Example:

let person = {name:”Pujari”,age:21}
let entries = Object.entries(person);
console.log(entries);//[ [ 'name', 'Pujari' ], [ 'age', 21 ] ]

Object.keys()

This function picks only keys (or property labels) of objects and returns an array.

Example:

let keys = Object.keys(person);
console.log(keys);// [ 'name', 'age' ]

Object.values()

This function picks only the values of objects and returns an array.

let values = Object.values(person);
console.log(values);// [ 'Pujari', 21 ]

Object.freeze()

This function freezes the object for any further changes (key or values). It may not throw any error (unless you are in strict mode) but there will be no effect of value change on your object.

let frozenObject = Object.freeze(person);
frozenObject.name = “Virat”;
console.log(frozenObject); //{ name: 'Pujari', age: 21}

Takeaway

That’s it for this small article — these are quite simple but important parts of a beginner’s journey to Javascript. Properly using copying and creation methods can avoid many potential bugs in Javascript applications.

That's it for the day see you in the next blog until then...

Keep Writing Code ❤️