In JavaScript, almost everything is an object. If you understand objects, you understand JavaScript.
What is an Object?
You can think of an object as a variable, where this variable contains different kinds of values. An object is basically a collection of properties, these properties are associated with a key: value pair. Each key is basically a string that points to a value. This value can either be a primitive value, such as a string, integer, boolean, etc or it can be a non-primitive value such as a function, array, or object.
var User={ name:"Aaron", age:24, displayInfo : function() { return User.name + "is" + User.age + " y/o" ; } }
Objects and properties
As I've mentioned before, objects have properties, there are 2 ways you can access or assign these properties, i.e
- Using dot. notation
- Using bracket[] notation
Using dot notation you can access and modify any property by just typing the "key" name.
let user={};
user.name="Aaron";
user.age=24;
console.log(user);
..............................output........................
{
name:Aaron,
age:24
}
as you can see in the example above using the dot notation we can create a property even if it does not exist.
if the name property is stored in a new variable say,
let xyz="name";
we cannot use xyz with a dot property, i.e user.xyz is not allowed. In this case, we use the Bracket Notation. The reason the bracket notation works are that it executes what's in the bracket and uses that solution to find the property name.
User[xyz]="Gavin";
Summary on Objects and properties
"." to access key values directly. "[variable_name]" when you access variables holding key names.
Copy by reference
An object by default follows copy by reference. let's keep the following code for reference.
let user={
name:"Aaron",
age:24
}
let user2=user
In the above code, we notice user is assigned to user2. Here user2 will be the same as user, and changes done in user2 will reflect in user i.e if user2.name="Charlene"; the value of user.name will also be updated automatically. This occurs as user2 holds the address of user and not any values of the object.
what if you don't want the updated values of user2 to rewrite the values of user? In that case, you clone the object of user to user2. Since cloning results in a different address, changes done to an object are restricted to its own address space.
user2=[...user] // syntax to clone.
If you enjoyed this article follow me on Twitter @RebeloAaron