Complete Guide to JavaScript Objects

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, ac…


This content originally appeared on DEV Community and was authored by James Lee

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
};

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");

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;

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

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.

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']

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

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

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

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]]

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 }

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 }

Object.isFrozen()

Determines if an object is frozen.

console.log(Object.isFrozen(me)); // Output: true

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 }

Object.isSealed()

Determines if an object is sealed.

console.log(Object.isSealed(me)); // Output: true

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

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

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.

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

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! 🍕


This content originally appeared on DEV Community and was authored by James Lee


Print Share Comment Cite Upload Translate Updates
APA

James Lee | Sciencx (2024-06-25T20:45:54+00:00) Complete Guide to JavaScript Objects. Retrieved from https://www.scien.cx/2024/06/25/complete-guide-to-javascript-objects/

MLA
" » Complete Guide to JavaScript Objects." James Lee | Sciencx - Tuesday June 25, 2024, https://www.scien.cx/2024/06/25/complete-guide-to-javascript-objects/
HARVARD
James Lee | Sciencx Tuesday June 25, 2024 » Complete Guide to JavaScript Objects., viewed ,<https://www.scien.cx/2024/06/25/complete-guide-to-javascript-objects/>
VANCOUVER
James Lee | Sciencx - » Complete Guide to JavaScript Objects. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/06/25/complete-guide-to-javascript-objects/
CHICAGO
" » Complete Guide to JavaScript Objects." James Lee | Sciencx - Accessed . https://www.scien.cx/2024/06/25/complete-guide-to-javascript-objects/
IEEE
" » Complete Guide to JavaScript Objects." James Lee | Sciencx [Online]. Available: https://www.scien.cx/2024/06/25/complete-guide-to-javascript-objects/. [Accessed: ]
rf:citation
» Complete Guide to JavaScript Objects | James Lee | Sciencx | https://www.scien.cx/2024/06/25/complete-guide-to-javascript-objects/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.