Complete Guide to JavaScript Objects

James Lee - Jun 25 - - Dev Community

JavaScript objects are foundational elements in programming with JavaScript. They allow you to store and manipulate key-value pairs, where each key is a string, and each value can be any data type. This guide will explore the various ways to create, access, and manipulate JavaScript objects, along with some advanced concepts like inheritance and static methods.

Creating JavaScript Objects

Object Literal Notation
The simplest and most commonly used method to create objects is the object literal notation.

const scorcism = {
    name: "TSolutionsX",
    age: 23
};
Enter fullscreen mode Exit fullscreen mode

Curly Braces: Enclose key-value pairs within curly braces {}.

Using the new Keyword

Creating objects using constructor functions and the new keyword is less common but essential for certain use cases.

function About(name, age, city) {
    this.name = name;
    this.age = age;
    this.city = city;
}

const me = new About("TSolutionsX", 23, "Toronto");
Enter fullscreen mode Exit fullscreen mode

Constructor Functions: Define a function and use this to set properties.
new Keyword: Creates an object with an internal this.

Using Object.create()
This method allows you to create a new object with a specified prototype object.

const aboutData = {
    greet: function() {
        return `Hello, my name is ${this.name}`;
    }
};

const me = Object.create(aboutData);
me.name = 'TSolutionsX';
me.age = 23;
Enter fullscreen mode Exit fullscreen mode

Prototype Inheritance: The new object inherits properties and methods from the prototype object.

Accessing Object Properties
Dot Notation and Bracket Notation
Properties of a JavaScript object can be accessed using dot notation or bracket notation.

Properties of a JavaScript object can be accessed using dot notation or bracket notation.

const me = {
    name: "TSolutionsX",
    age: 23
};

console.log(me.name);   // Output: TSolutionsX
console.log(me["age"]); // Output: 23
Enter fullscreen mode Exit fullscreen mode

Dot Notation: object.property
Bracket Notation: object["property"]

Object Prototypes and Inheritance
At the core of JavaScript lies the concept of prototypes. Every object in JavaScript is associated with a prototype object, which acts as a blueprint.

Object Prototype
The prototype object contains properties and methods accessible to all instances created from it.

const me = {
    name: "TSolutionsX",
    eatsAppleDaily: false,
    printAbout: function() {
        console.log(`I am ${this.name}. I ${this.eatsAppleDaily ? "eat" : "don't eat"} apple daily.`);
    }
};

const myFriend = Object.create(me);
myFriend.name = "Ladoo";
myFriend.eatsAppleDaily = true;

me.printAbout();        // Output: I am TSolutionsX. I don't eat apple daily.
myFriend.printAbout();  // Output: I am Ladoo. I eat apple daily.
Enter fullscreen mode Exit fullscreen mode

Static Methods

Object.keys()
Returns an array of a given object’s own enumerable property names.

const aboutMe = {
    name: "TSolutionsX",
    age: 23
};

let aboutMeKeys = Object.keys(aboutMe);
// Output: ['name', 'age']
Enter fullscreen mode Exit fullscreen mode

Object.values()
Returns an array of a given object’s own enumerable property values.

let aboutMeValues = Object.values(aboutMe);
// Output: ['TSolutionsX', 23]
Enter fullscreen mode Exit fullscreen mode

Object.assign()
Copies the values of all enumerable own properties from one or more source objects to a target object.

const target = { age: 23 };
const source = { name: "TSolutionsX" };
const merged = Object.assign(target, source);

console.log(merged); // Output: { age: 23, name: 'TSolutionsX' }
console.log(merged === target); // Output: true
Enter fullscreen mode Exit fullscreen mode

Object.entries()

Returns an array of the given object’s own enumerable string-keyed property key-value pairs.

console.log(Object.entries(aboutMe));
// Output: [['name', 'TSolutionsX'], ['age', 23]]
Enter fullscreen mode Exit fullscreen mode

Object.fromEntries()

Transforms a list of key-value pairs into an object.

const entries = [['name', 'TSolutionsX'], ['age', 23]];
console.log(Object.fromEntries(entries));
// Output: { name: 'TSolutionsX', age: 23 }
Enter fullscreen mode Exit fullscreen mode

Object.freeze()

Freezes an object, preventing new properties from being added, existing properties from being removed or changed, and the prototype from being altered.

Object.freeze(me);
me.name = "TSolutionsX"; // This change will not take effect

console.log(me); // Output: { name: "TSolutionsX", age: 23 }
Enter fullscreen mode Exit fullscreen mode

Object.isFrozen()

Determines if an object is frozen.

console.log(Object.isFrozen(me)); // Output: true
Enter fullscreen mode Exit fullscreen mode

Object.seal()

Seals an object, preventing new properties from being added and marking all existing properties as non-configurable.

Object.seal(me);
me.name = "TSolutionsX"; // This change will take effect
delete me.age; // This deletion will not take effect

console.log(me); // Output: { name: 'TSolutionsX', age: 21 }
Enter fullscreen mode Exit fullscreen mode

Object.isSealed()

Determines if an object is sealed.

console.log(Object.isSealed(me)); // Output: true
Enter fullscreen mode Exit fullscreen mode

Inheritance Static Methods

this Keyword
The this keyword refers to the properties of the object it is within.

const person = {
    name: 'TSolutionsX',
    sayMyName: function() {
        return `My name is ${this.name}`;
    }
};

console.log(person.sayMyName()); // Output: My name is TSolutionsX
Enter fullscreen mode Exit fullscreen mode

bind(), call(), and apply()

bind()
Creates a new function that, when called, has its this keyword set to the provided value.

function sayMyName() {
    return `My name is ${this.name}`;
}

const person = { name: 'TSolutionsX' };
const boundSayMyName = sayMyName.bind(person);

console.log(boundSayMyName()); // Output: My name is TSolutionsX
Enter fullscreen mode Exit fullscreen mode

call()

Calls a function with a given this value and arguments provided individually.

function introduce(language) {
    console.log(`I code in ${language}. My name is ${this.name}.`);
}

const mySelf = { name: "TSolutionsX" };

introduce.call(mySelf, 'Java'); // Output: I code in Java. My name is TSolutionsX.
Enter fullscreen mode Exit fullscreen mode

apply()
Similar to call(), but accepts arguments as an array.

function add(...args) {
    let sum = args.reduce((acc, curr) => acc + curr, 0);
    console.log(sum);
}

const numbers = [1, 2, 3, 4, 5];
add.apply(null, numbers); // Output: 15
Enter fullscreen mode Exit fullscreen mode

When to Use call, bind, and apply
call: Execute a function immediately and specify what this should refer to.
bind: Create a new function that, when executed later, has a predetermined this value.
apply: Use when you have an array of arguments to pass to a function.

Conclusion

Understanding JavaScript objects and their associated methods is crucial for any JavaScript developer. These concepts provide a solid foundation for working with data structures, creating complex functionalities, and leveraging the full power of JavaScript.

If this guide was helpful, please leave a like, follow.

Happy coding! 🍕

. . .