Js Objects in JavaScript
? JavaScript Objects – A Complete Introduction
In JavaScript, objects are collections of key-value pairs, used to store structured data and functionality. They are the building blocks of almost everything in JS.
? Creating an Object
? Using Object Literal (most common)
let person = { name: "Alice", age: 25, isStudent: false};? Using new Object()
let person = new Object();person.name = "Alice";person.age = 25;? Object Syntax
let objectName = { key1: value1, key2: value2, ...};Keys are also called properties
Values can be strings, numbers, arrays, functions, or other objects
? Accessing Object Properties
Dot Notation:
console.log(person.name); // "Alice"Bracket Notation:
console.log(person["age"]); // 25?? Adding / Updating Properties
person.country = "USA"; // addperson.age = 26; // update? Deleting Properties
delete person.isStudent;? Methods in Objects
You can define functions inside objects — these are called methods:
let person = { name: "Alice", greet: function() { return "Hi, I'm " + this.name; }};console.log(person.greet()); // Hi, I'm Alice? Loop Through Object
for (let key in person) { console.log(key + ": " + person[key]);}?? Built-in Object Methods
Object.keys(obj)– array of property namesObject.values(obj)– array of property valuesObject.entries(obj)– array of [key, value] pairshasOwnProperty()– check if object has a specific property
? Example Summary
let car = { brand: "Toyota", model: "Corolla", year: 2020, fullDetails: function() { return `${this.brand} ${this.model} (${this.year})`; }};console.log(car.fullDetails()); // "Toyota Corolla (2020)"? Objects Are Everywhere
In JS:
Arrays are objects
Functions are objects
DOM elements are objects
JSON data is made of objects
Would you like to explore how objects are used in JSON or how they compare to classes?