In JavaScript, an object serves as a variable capable of storing numerous values. It acts as a repository for a set of values. Objects rank among the fundamental data types in JavaScript. Each object comprises properties and types, which function as a unified entity. Unlike primitive data types, objects are classified as non-primitive.
Consider a football as an example. A football possesses attributes such as weight, shape, color, and design. Here, the football serves as an object, while its weight and shape represent its attributes.
In a comparable manner, JavaScript utilizes objects that possess properties which characterize their attributes. An object is capable of storing multiple data types, such as Strings, Numbers, Booleans, Arrays, Functions, and more.
Syntax of Object in JavaScript
// Object literal syntax
const myObject = {
key1: value1,
key2: value2,
// more key-value pairs...
};
Explanation:
- Curly braces are used to demarcate the start and termination of an object literal.
- Inside these braces, you define key-value pairs separated by commas.
- Every key is a string (or symbol in ES6+).
- A colon comes after each key, followed by its value.
- They may be of any data type like strings, numbers, booleans, arrays, functions, or other objects.
Creating a JavaScript Object
JavaScript provides several means of object construction, and flexibility as well as versatility are both achievable. The different methods of object construction in JavaScript are:
- Using an Object Literal
- Employing the JavaScript Keyword new
- Constructing a constructor object
Using an Object Literal
In JavaScript, the most straightforward approach to define an object is through the use of an object literal. This method involves creating key-value pairs enclosed within curly braces {} to instantiate an object.
Example
let person = {
name: 'Harsh',
age: 30,
city: 'Ghaziabad'
};
In this illustration, an individual is depicted as an object that possesses three attributes: name, age, and city. Each attribute is assigned a corresponding value utilizing the colon (:) notation.
Using new keyword
Instances can also be generated utilizing constructor functions alongside the new keyword. Constructor functions provide the capability to instantiate numerous objects that share identical methods and properties.
Example
function Person(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
}
// Creating a new instance of Person
let person1 = new Person('Evan', 30, 'Paris');
let person2 = new Person('Anupam', 25, 'Delhi');
JavaScript Objects are Mutable
JavaScript objects possess mutability, meaning that you have the ability to modify their properties even after the object has been created. This allows you to add new properties, remove existing ones, and alter the values of current properties.
Example
let person = {
name: 'Aman',
age: 33,
city: 'Delhi'
};
// Modifying property value
person.age = 31;
// Adding a new property
person.email = 'aman@example.com';
// Removing a property
delete person.city;
Characteristics of Objects in JavaScript
- Objects are slightly tricky as they can contain any collection of reference data types and simple data types.
- A reference data type is used to label characters or numbers with a reference value, the reference character or number referencing its position.
- As an object is being passed from one function to another, this pointer points to where the object is.
- A class holds methods and attributes.
JavaScript Built-In Methods
Here are some commonly used JavaScript methods:
create: This function is employed to generate JavaScript objects that are derived from a specified prototype object, as previously discussed.
entries: This function takes a JavaScript object as its parameter and yields an array comprised of arrays that represent key-value pairs. For example, let’s take another look at our "student" object.
keys: The keys function accepts a JavaScript object as its argument and yields an array containing the names of its properties.
values: In a similar fashion, the values method accepts a JavaScript object as its argument and produces an array consisting of the object's values.
is: This function accepts another object as a parameter and evaluates whether the two objects are equivalent, yielding a Boolean result. If the objects match, it provides "true"; if they do not match, it delivers "false."
Object.create
The Object.create function generates a new object that is associated with a pre-existing object.
const people = {
printIntro: function () {
console.log(`My full name is ${this.Fname}. Am I Alive? ${this.isalive}`);
}
};
const name = Object.create(people);
name.Fname = "Robert"; // "Fname" is a property set on "name", but not on "people"
name.isalive = true;
name.printIntro();
Output:
Object.entries
The Object.entries method provides an array of a given object's enumerable properties in the form of [key, value] pairs.
Syntax:
Object.entries(obj)
const student = { 1: 'Steve', 100: 'Sanju', 45: 'Chris' };
console.log(Object.entries(student));
Output:
Object.keys
The Object.keys function returns an array containing the enumerable properties of a given array or an array-like object, regardless of whether the keys appear in a random sequence.
let employee_detail = {
employee_name: 'Smith',
employee_salary: 144,
employee_age : 23
} ;
console.log(Object.keys(employee_detail).length);
Output:
The code provided earlier will yield the size of the object by utilizing the object.keys method.
Object.values
The Object.values function provides an array containing the values of a specified property from an object. It extracts the values associated with the object and outputs them in the format of an array.
// Returning property values of an array
var check = ['x', 'y', 'z'];
console.log(Object.values(check));
Output:
Object.is
The JavaScript method Object.is serves as a helpful utility to determine if two values are precisely equal. This method performs its comparison without type coercion, meaning it evaluates the values in their original forms. Additionally, it addresses certain unique scenarios, such as distinguishing between positive and negative zero.
console.log(Object.is(5, 5)); // true
console.log(Object.is('Java', 'Java')); // true
console.log(Object.is(true, false)); // false
console.log(Object.is(0, -0)); // false
console.log(Object.is(NaN, NaN)); // true
Output:
Conclusion
In JavaScript, the concept of objects is essential for establishing data values and attributes, serving as a foundational component of programming. Within JScript, every element is treated as an object. Developers leverage objects, their properties, and methods to define and execute these objects across diverse programming concepts.
JavaScript Object Methods
| S.No | Methods | Description |
|---|---|---|
1 |
Object.assign() | This method is used to copy enumerable and own properties from a source object to a target object |
2 |
Object.create() | This method is used to create a new object with the specified prototype object and properties. |
3 |
Object.defineProperty() | This method is used to describe some behavioral attributes of the property. |
4 |
Object.defineProperties() | This method is used to create or configure multiple object properties. |
5 |
Object.entries() | This method returns an array with arrays of the key, value pairs. |
6 |
Object.freeze() | This method prevents existing properties from being removed. |
7 |
Object.getOwnPropertyDescriptor() | This method returns a property descriptor for the specified property of the specified object. |
8 |
Object.getOwnPropertyDescriptors() | This method returns all own property descriptors of a given object. |
9 |
Object.getOwnPropertyNames() | This method returns an array of all properties (enumerable or not) found. |
10 |
Object.getOwnPropertySymbols() | This method returns an array of all own symbol key properties. |
11 |
Object.getPrototypeOf() | This method returns the prototype of the specified object. |
12 |
Object.is() | This method determines whether two values are the same value. |
13 |
Object.isExtensible() | This method determines if an object is extensible |
14 |
Object.isFrozen() | This method determines if an object was frozen. |
15 |
Object.isSealed() | This method determines if an object is sealed. |
16 |
Object.keys() | This method returns an array of a given object's own property names. |
17 |
Object.preventExtensions() | This method is used to prevent any extensions of an object. |
18 |
Object.seal() | This method prevents new properties from being added and marks all existing properties as non-configurable. |
19 |
Object.setPrototypeOf() | This method sets the prototype of a specified object to another object. |
20 |
Object.values() | This method returns an array of values. |