Object Basics in JavaScript
{ key: value }. Dot or bracket. JSON.stringify if you need a string.
BeginnerObject ProgramsExample 1 of 2
object-basics.js
1// Method 1: Object literal2let person = {3 name: "John",4 age: 30,5 city: "New York"6};78console.log("Person:", person);9console.log("Name:", person.name);10console.log("Age:", person.age);1112// Method 2: Adding properties13person.email = "john@example.com";14person["phone"] = "123-456-7890";1516console.log("\nAfter adding properties:", person);1718// Method 3: Object with methods19let calculator = {20 num1: 10,21 num2: 5,22 add: function() {23 return this.num1 + this.num2;24 },25 subtract: function() {26 return this.num1 - this.num2;27 },28 multiply() { // ES6 shorthand29 return this.num1 * this.num2;30 }31};3233console.log("\nCalculator:");34console.log("Add:", calculator.add());35console.log("Subtract:", calculator.subtract());36console.log("Multiply:", calculator.multiply());3738// Method 4: Object constructor39function Person(name, age) {40 this.name = name;41 this.age = age;42 this.greet = function() {43 return "Hello, I'm " + this.name;44 };45}4647let person1 = new Person("Alice", 25);48let person2 = new Person("Bob", 30);4950console.log("\nPerson 1:", person1.greet());51console.log("Person 2:", person2.greet());5253// Method 5: Object.keys, Object.values, Object.entries54let student = {55 name: "Jane",56 grade: "A",57 subjects: ["Math", "Science"]58};5960console.log("\nObject methods:");61console.log("Keys:", Object.keys(student));62console.log("Values:", Object.values(student));63console.log("Entries:", Object.entries(student));6465// Method 6: Object destructuring66let { name, age } = person;67console.log("\nDestructured:", name, age);6869// Method 7: Spread operator70let personCopy = { ...person };71personCopy.age = 31;72console.log("\nOriginal:", person.age);73console.log("Copy:", personCopy.age);
Output
Person: { name: 'John', age: 30, city: 'New York' }
Name: John
Age: 30
After adding properties: { name: 'John', age: 30, city: 'New York', email: 'john@example.com', phone: '123-456-7890' }
Calculator:
Add: 15
Subtract: 5
Multiply: 50
Person 1: Hello, I'm Alice
Person 2: Hello, I'm Bob
Object methods:
Keys: [ 'name', 'grade', 'subjects' ]
Values: [ 'Jane', 'A', [ 'Math', 'Science' ] ]
Entries: [ [ 'name', 'Jane' ], [ 'grade', 'A' ], [ 'subjects', [ 'Math', 'Science' ] ] ]
Destructured: John 30
Original: 30
Copy: 31What's going on
obj.key and obj['key']. Bracket when the name is in a variable.
const obj = {}; obj = 1 fails. obj.a = 1 is fine. const binds the name, not the insides.