Object Data Types in JavaScript

JavaScript2 min read
Object Data Types in JavaScript
javascriptobject data typedata types

The object data type in JavaScript allows us to create complex data structures by grouping key-value pairs. An object can store different types of data, including numbers, strings, arrays, and even functions.

Object Data Types in JavaScript

  • The object data type in JavaScript allows us to create complex data structures by grouping key-value pairs.
  • An object can store different types of data, including numbers, strings, arrays, and even functions.

Creating an Object

  • To create an object, we use object literals, which are enclosed in curly braces {}.
let person = { name: "Coders", age: 22 };

In this example:

  • name and age are keys (also known as properties).
  • "Coders" and 22 are the values associated with those keys.

Accessing Object Properties

  • We can access the values of an object's properties using the dot (.) notation.
document.write("Name = " + person.name); // Output: Name = Coders document.write("Age = " + person.age); // Output: Age = 22

Adding a New Property

  • You can add new properties to an object after it has been created:
person.salary = "Ten thousand"; document.write("Salary = " + person.salary); // Output: Salary = Ten thousand

Defining Functions as Object Properties

  • In JavaScript, you can define functions as properties of an object, making them methods of that object.
person.greet = function() { return "Welcome!"; }; document.write(person.greet()); // Output: Welcome!

Explanation:

  • The greet function is defined as a property of the person object and can be accessed using dot notation just like any other property.

Summary:

  • Objects in JavaScript are versatile data structures that allow you to store key-value pairs.
  • You can access, modify, and add properties to objects dynamically.
  • Functions can be stored as properties within objects, turning them into methods.