0
0
Javascriptprogramming~5 mins

Object creation in Javascript

Choose your learning style9 modes available
Introduction

Objects help group related information together in one place. They let you store and organize data with names.

When you want to store details about a person, like name and age.
When you need to group settings or options for a program.
When you want to represent real-world things with properties, like a car with color and model.
When you want to pass multiple related values together in a function.
When you want to keep track of items with labels instead of just numbers.
Syntax
Javascript
const objectName = {
  key1: value1,
  key2: value2
  // more key-value pairs
};

Keys are names for the data and values can be any type like numbers, strings, or even other objects.

Use commas to separate each key-value pair inside the curly braces.

Examples
This creates an object named person with two properties: name and age.
Javascript
const person = {
  name: "Alice",
  age: 30
};
An object car with three properties: brand, year, and isElectric.
Javascript
const car = {
  brand: "Toyota",
  year: 2020,
  isElectric: false
};
This creates an empty object with no properties yet.
Javascript
const emptyObject = {};
Sample Program

This program creates a book object with three properties. Then it prints each property to the console.

Javascript
const book = {
  title: "JavaScript Basics",
  author: "Sam",
  pages: 150
};

console.log("Book title:", book.title);
console.log("Author:", book.author);
console.log("Pages:", book.pages);
OutputSuccess
Important Notes

You can access object properties using dot notation like objectName.key.

Objects can hold other objects or arrays as values for more complex data.

Summary

Objects group related data with named keys.

Create objects using curly braces and key-value pairs.

Access data inside objects with dot notation.