Complete Guide to JavaScript Objects
Tags: javascript, objects, webdev, beginners
Published: 2024-06-25 20:45:54

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.

```javascript
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.

```javascript
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.

```javascript
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.

```javascript
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.

```javascript
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.

```javascript
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.

```javacript
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.

```javascript
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.

```javacript
console.log(Object.entries(aboutMe));
// Output: [['name', 'TSolutionsX'], ['age', 23]]
```

`Object.fromEntries()`

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

```javascript
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.

```javascript
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.

```javascript
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.

```javascript
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.

```javascript
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.


```javascript
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.

```javascript
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.

```javascript
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.

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