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 literal
2let person = {
3 name: "John",
4 age: 30,
5 city: "New York"
6};
7
8console.log("Person:", person);
9console.log("Name:", person.name);
10console.log("Age:", person.age);
11
12// Method 2: Adding properties
13person.email = "john@example.com";
14person["phone"] = "123-456-7890";
15
16console.log("\nAfter adding properties:", person);
17
18// Method 3: Object with methods
19let 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 shorthand
29 return this.num1 * this.num2;
30 }
31};
32
33console.log("\nCalculator:");
34console.log("Add:", calculator.add());
35console.log("Subtract:", calculator.subtract());
36console.log("Multiply:", calculator.multiply());
37
38// Method 4: Object constructor
39function Person(name, age) {
40 this.name = name;
41 this.age = age;
42 this.greet = function() {
43 return "Hello, I'm " + this.name;
44 };
45}
46
47let person1 = new Person("Alice", 25);
48let person2 = new Person("Bob", 30);
49
50console.log("\nPerson 1:", person1.greet());
51console.log("Person 2:", person2.greet());
52
53// Method 5: Object.keys, Object.values, Object.entries
54let student = {
55 name: "Jane",
56 grade: "A",
57 subjects: ["Math", "Science"]
58};
59
60console.log("\nObject methods:");
61console.log("Keys:", Object.keys(student));
62console.log("Values:", Object.values(student));
63console.log("Entries:", Object.entries(student));
64
65// Method 6: Object destructuring
66let { name, age } = person;
67console.log("\nDestructured:", name, age);
68
69// Method 7: Spread operator
70let 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: 31

What'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.