Object Basics in JavaScript
Learn JavaScript object basics: literals, dot and bracket access, methods, constructors, Object.keys, spread and JSON.stringify. Explanation and output.
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);
Sample Output
After adding properties: { ... }Node may print this object across several lines when it is long. The content is the same.
In this one
- How to create objects and read properties
- When to use dot or bracket access
- How methods use this
- How to list keys and values and copy objects
How it works
- 1
person is created and its name and age are printed.
- 2
email and phone are added.
- 3
calculator methods use this to add, subtract and multiply.
- 4
new Person makes Alice and Bob.
- 5
Object.keys, values and entries list the student data.
- 6
Destructuring and spread are used on person.
Edge cases
Missing property
person.salary is undefined, not an error.
Check with "salary" in person or use a default value.
Shallow copy
{ ...student }.subjects.push("Art") changes the original too.
Spread copies one level. Nested arrays and objects are shared.
Changing a const object
const p = {}; p.a = 1 works, but p = {} fails.
const blocks reassignment, not changes inside.
What's going on
An object groups related values under names. Each name is a key and each value is a property. A student record with name, age and city is a natural object.
Method 1 creates an object literal with curly braces: { name: "John", age: 30, city: "New York" }. You read values with dot notation, person.name.
Method 2 adds properties after creation. person.email uses a dot. person["phone"] uses brackets. Use brackets when the key is stored in a variable, like person[field], or when the key has a space or dash.
Method 3 puts functions inside an object. These are called methods. Inside a method, this refers to the object, so this.num1 reads the calculator's own value. multiply() shows the short ES6 method syntax.
Method 4 uses a constructor function with new. new creates an empty object, sets this to it, and returns it. Each Person gets its own name and greet.
Method 5 shows Object.keys, Object.values and Object.entries. They return arrays of keys, values, or [key, value] pairs, which are easy to loop over.
Method 6 uses destructuring to pull name and age out into variables. Method 7 copies with spread, { ...person }. Changing the copy does not change the original. The copy is shallow, so nested objects are still shared.
Two more tips. const person = {} stops you from assigning a new object to person, but you can still change its properties. const binds the name, not the insides. And if you need the object as text, to save or send it, use JSON.stringify(person).
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which reads a key stored in the variable k?
Pick an answer to check it.
Question 2
After let c = { ...p }; c.age = 31; what is p.age if it was 30?
Pick an answer to check it.
Questions people ask
How do I turn an object into a string?
JSON.stringify(obj). Use JSON.parse to turn it back.
Why does the browser show the object differently?
Node and browsers format console output differently. The data is the same.
When should I use a class instead?
When you create many objects with the same methods. See the Classes page.