Mastering Objects in JavaScript: A Deep Dive into Object Creation, Manipulation, and Best Practices
Objects in JavaScript are a fascinating aspect of the language. They serve as a versatile datatype for storing key-value pairs and are essential for understanding the intricacies of JavaScript programming. First, let's know what an object looks like in javascript.
//example of a user object
const user={
"first name":"Alex",
"last name":"Henderson",
"username":"alex03",
"age":27,
"password":"alex@2001Nov22"
"isLoggedIn":true
}
As you can see in the code example, an object is a store of key-value pairs, each key can either be a string or a Symbol. Keys are always unique and values can be of any valid datatypes. you can even create an object using the the constructor(new Object()), but the difference is the object created through constructor will be a singleton object and the object created as literal will be a non-singleton object. The key-value pairs are also known as properties of an object. In Objects, the order of the properties or key-value pair doesn't matter like arrays. Objects can even be nested. like this.
const myobj={
"prop1":"val1"
"obj2":{
"prop2":"val2"
}
}
When you fetch data from an API endpoint in the future, you might come across something like this in JSON format (think of it as JavaScript objects for now). The data is retrieved from JSON, which is often in a nested format like this.
How to access object properties
There are two ways to access the properties of an object. First, you can use the dot notation.
const user={
"first name":"Alex",
"last name":"Henderson",
"username":"alex03",
"age":27,
"password":"alex@2001Nov22"
"isLoggedIn":true
}
console.log(user.age)// 27
But when you have a key with spaces in between("first name"), you cannot use dot notation, then you will have to use this syntax.
console.log(user["first name"]) // Alex
Now an object can also have a function as a property. So, if you want to call the function, it's straightforward. Just add opening and closing brackets (like you do for invoking a function) after accessing the object property.
// lets consider we have a function named greet
user.greet()
//or
user["greet"]()
Suppose you want to check whether an object has a particular property or not, then you can use the .hasOwnProperty(), this function takes in the target property as an argument and returns true or false. Here's a quick example of how it works.
const obj={
prop1:"val1",
prop2:"val2"
};
console.log(obj.hasOwnProperty('prop3'); // false
How to modify an object
Suppose you find out that your object is missing some properties, now let's see how you can add them. For that first, you write the new property name and use the =
operator to assign a value to the new property. Like this.
// the user object dont have a email so lets add it
user["email"]="alex22@google.com"
console.log(user.email) // alex22@google.com
Through this way also, you can change the value of any key, let's say I want to update the age to 28. So I can do it like this.
user.age=28
console.log(user.age) // 28
A lot of times you might want to make the object unmodifiable, so in that case if anyone tries to modify the object it will throw an error, To do that you can use this function and pass in the name of the object.
Object.freeze(user)
// after this any modifcation on the object will throw an error
If you want the key set in the object in the form of an array you can use this command.
Object.keys(user)
This command will return the key set in the form of an array and similar ways if you want to get the values as an array you can try this command.
Object.values(user)
If you want to check if an object has a property or not then you can use this command, it will return true or false depending on whether the property exists or not.
user.hasProperty("skills")// false
How to copy properties from other objects
In your code, you may have other objects wich you want to combine into one or you may want to copy the properties of another object to a new object, so how can you do that? For that you have two ways. You can use the Object.assign() method.
const user={
firstname:"Alex",
lastname:"bakerfiekd"
}
const details={
age:24,
gender:"male"
}
// the syntax is Object.assign(target,source)
const finalUser=Object.assign({},user,details);
This function returns a new object after combining the two objects into the new blank object that you have given. this is a little tricky at first but there is also a better and more modern way and that is through spread operator ...
. The Spread operator spreads the properties or key-value pairs of the objects into single units. Let me show it with an example.
const user={
firstname:"Alex",
lastname:"bakerfiekd"
}
const details={
age:24,
gender:"male"
}
const finaluser={...user,...details};
So, what happens here is that the key-value pairs of user
and details
are broken down into single units and then stored in the finaluser
object.
So those were some of the basics about Objects in JavaScript, sure there is more to and we'll surely look into them, I can't cover all the concepts in a single blog, after all, I am just making things simple for beginners ๐, not rewriting the JavaScript docs ๐ .
Mastering objects in JavaScript is essential for developers. Understanding object creation, manipulation, and best practices improves data handling in JavaScript projects. By grasping the concepts in this article, you can excel in using objects effectively in JavaScript programming.