You are currently viewing What Is Object In Javascript And How To Create It?
Photo by Mohammad Rahmani

What Is Object In Javascript And How To Create It?

This is one of the core concepts in javascript that needs to be mastered. 

What is Object in javascript?

An object in javascript is simply a map containing the key-value pairs. It is pretty much similar to  –

  • struct in C
  • HashMap in java
  • unordered_map in c++
  • dictionary in python

So, if you’re coming from the above programming language, understanding javascript objects and constructors will be a piece of cake for you.

Note:- Sometimes Object is also referred to as “associative arrays” in other programming languages.

The value of a key can be a function, array, object, or any other primitive.

If the value of a key is a primitive or any other object (PS: an array is also an object in javascript) then it’s called properties but if it’s a function then it’s called method.

e.g.

Object in JS

In the above code, a person is an object which has keys sayHello and friends with value as function and arrays respectively.

You probably have heard that — 

Almost everything is an object in javascript. So question would be arising — what are the remaining ones which aren’t an object. Ans — Primitive

Primitive

A primitive (primitive value, primitive data type) is data that is not an object and doesn’t have any methods. There are 7 primitive data types — string, number, big int, boolean, undefined, symbol, and null.

All primitives are immutable i.e they can be replaced but can’t be altered.

Let’s understand this with an example — 

Primitive in JS

How to create an object in javascript?

Creating an object at the beginning may seem odd but once you are used to it, you will love it.

The object syntax is wrapped by curly braces. And the key-value pair separated by a colon with a trailing comma is added inside the object.

				
					var obj = {
    name: 'xyz',
    age: 26
};
				
			

we can also create an empty object and add properties as we go.

				
					var obj = {}; // empty or blank object

obj.name = 'xyz';
obj.age = 26;
				
			

Both object declarations are the same.

In the next part, we will see the other ways to create an object in detail.

If you like my article, please follow me on medium.

Thanks for reading the article!

Please share the articles on –

Facebook
Twitter
LinkedIn
Subscribe

The latest tips and news from the industry straight to your inbox!

Join 30,000+ subscribers for exclusive access to our monthly news and tutorials!