DEV Community

Collins Etemesi
Collins Etemesi

Posted on

Javascript Objects

Javascript works on the basis of object oriented programming. This article describes how to use objects, properties and methods, and how to create your own objects.

What is an object?
In JavaScript, an object is a standalone entity, with properties and type. They include: string, number, boolean, null and undefined. For example a user object can have the following properties: username, email and gender.

Objects and properties
A JavaScript object has properties associated with it. A property of an object is a variable that is attached to the object. The properties of an object define the characteristics of the object. You access the properties of an object with a simple dot-notation:
objectName.propertyName
Like all JavaScript variables, both the object name and property name are case sensitive.
You can define a property by assigning it a value. To demonstrate this, here’s a sample object myDog

const myDog = {
“name”: “Joe”,
“legs”: 4,
“tails”: 1,
“friends”:[“everyone”]
};

Enter fullscreen mode Exit fullscreen mode

“Name”, “legs”, “tails” and “friends” are properties while “Joe” “4” “1” and “everyone” are values.

Object Methods
Methods are actions that can be performed on objects.

const person = {
  firstName: "John",
  lastName: "Doe",
  id: 5566,
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

Enter fullscreen mode Exit fullscreen mode

Creating a JavaScript Object Using an Object Literal
This is the easiest way to create a JavaScript Object.
Using an object literal, you both define and create an object in one statement.
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Conclusion
Objects in JavaScript can be compared to objects in real life. The concept of objects in JavaScript can be understood with real life, tangible objects. In JavaScript, an object is a standalone entity, with properties and type. Compare it with a chair, for example. A chair is an object, with properties. A chair has a color, a design, weight, a material it is made of. The same way, JavaScript objects can have properties, which define their characteristics.

Top comments (0)