JS Object

In JavaScript, an object is a collection of key-value pairs. Objects allow you to store and manage data with properties and methods.


Creating an Object:

1.Object Literal Syntax:

Example
let person = {
name: "John",
age: 30,
isStudent: false,
};
console.log(person); // {name:"John",age:30,isStudent:false}

Try it yourself

Using the Object Constructor:

Example
const person = new Object();
person.name = "John";
person.age = 30;
console.log(person); // {name:"John",age:30}

Try it yourself


Accessing Object Properties

Example
let person = {
name: "John",
age: 30,
isStudent: false,
};

// Dot Notation:
console.log(person.name); // Output: "John"


// Bracket Notation:
console.log(person["age"]); // Output: 30


// Dynamic Property Access:
const property = "isStudent";
console.log(person[property]); // Output: false

Try it yourself


Using Methods in Objects:

Objects can also contain functions, which are called methods.

Example
const car = {
make: "Toyota",
model: "Corolla",
year: 2020,
start() {
console.log("The car is starting...");
},
};

console.log(car.make); // Output: "Toyota"
car.start(); // Output: "The car is starting..."

car.color = "Blue"; // Add a new property
console.log(car); // {make: "Toyota", model: "Corolla", year: 2020, start: ƒ, color: "Blue"}

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.