An object in JavaScript is a variable that holds a different value. It acts as a storage space for a set of values. Objects are one of the most vital data types in JavaScript. The object carries properties and types and it’s a different entity. It is a non-primitive datatype. E.g, let’s take a keyboard. The keyboard has weight, shape, color, design, etc. Here keyboard is an object and weight, shape is the properties of the object. Thus, JavaScript objects will have properties and those properties will specify the characteristics of an object. An object can be anything Strings, Arrays, Numbers, Boolean, Functions, and so on.
An Object in javascript:)
We can create objects in JavaScript in three ways,
- “new” keyword
- Object literals
- create()
“new” keyword🙂
User-Defined Objects with “new” keyword: The “new” keyword will produce an instance of an object. The object is produced using the “new” keyword followed by the constructor.
<h2>New keyword</h2> <script> function fun() { var newKeyword = 1; this.x = "This is a New Keyword"; } var obj = new fun(); alert(obj.x); </script>
Object literals🙂
It is the easiest option to create the object in JavaScript. We can instantiate objects just like variables in Javascript.
<h1>Object literals</h1> <script> var database = { FirstName : "Brad", LastName : "Pitt", DateOfBirth : 1975 }; document.write(database.FirstName); </script>
create()
Object.create() Method: Object.create is a pre-built Object type in JavaScript. When you create new object the object.create() method will use object literal as prototype.
<h2>create()</h2> <script> var Animal = { traits: {}, } var goat = Object.create(Animal); goat.traits.legs = 4; var bird = Object.create(Animal); bird.traits.legs = 2; alert(goat.traits.legs) // shows 2!!! </script>
Conclusion
In JavaScript, we use objects for representing the value, and property of the data which is a very significant feature of the programming. In Javascript, each and everything is an object.