const obj = {
property1: value1, // property name may be an identifier
2: value2, // or a number
"property n": value3, // or a string
};Working with objects / notebook
Working with objects
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
let x;
if (cond) {
x = { greeting: "hi there" };
}const myHonda = {
color: "red",
wheels: 4,
engine: { cylinders: 4, size: 2.2 },
};function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}const myCar = new Car("Eagle", "Talon TSi", 1993);const randCar = new Car("Nissan", "300ZX", 1992);
const kenCar = new Car("Mazda", "Miata", 1990);function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}const rand = new Person("Rand McKinnon", 33, "M");
const ken = new Person("Ken Jones", 39, "M");function Car(make, model, year, owner) {
this.make = make;
this.model = model;
this.year = year;
this.owner = owner;
}const car1 = new Car("Eagle", "Talon TSi", 1993, rand);
const car2 = new Car("Nissan", "300ZX", 1992, ken);car2.owner.name;car1.color = "black";// Animal properties and method encapsulation
const animalProto = {
type: "Invertebrates", // Default value of properties
displayType() {
// Method which will display the type of animal
console.log(this.type);
},
};
// Create a new animal type called `animal`
const animal = Object.create(animalProto);
animal.displayType(); // Logs: Invertebrates
// Create a new animal type called fish
const fish = Object.create(animalProto);
fish.type = "Fishes";
fish.displayType(); // Logs: Fishesconst myCar = {
make: "Ford",
model: "Mustang",
year: 1969,
};// Dot notation
myCar.make = "Ford";
myCar.model = "Mustang";
myCar.year = 1969;
// Bracket notation
myCar["make"] = "Ford";
myCar["model"] = "Mustang";
myCar["year"] = 1969;const myObj = {};
const str = "myString";
const rand = Math.random();
const anotherObj = {};
// Create additional properties on myObj
myObj.type = "Dot syntax for a key named type";
myObj["date created"] = "This key has a space";
myObj[str] = "This key is in variable str";
myObj[rand] = "A random number is the key here";
myObj[anotherObj] = "This key is object anotherObj";
myObj[""] = "This key is an empty string";
console.log(myObj);
// {
// type: 'Dot syntax for a key named type',
// 'date created': 'This key has a space',
// myString: 'This key is in variable str',
// '0.6398914448618778': 'A random number is the key here',
// '[object Object]': 'This key is object anotherObj',
// '': 'This key is an empty string'
// }
console.log(myObj.myString); // 'This key is in variable str'str = "myString";
myObj[str] = "This key is in variable str";
console.log(myObj.str); // undefined
console.log(myObj[str]); // 'This key is in variable str'
console.log(myObj.myString); // 'This key is in variable str'let propertyName = "make";
myCar[propertyName] = "Ford";
// access different properties by changing the contents of the variable
propertyName = "model";
myCar[propertyName] = "Mustang";
console.log(myCar); // { make: 'Ford', model: 'Mustang' }myCar.nonexistentProperty; // undefinedfunction showProps(obj, objName) {
let result = "";
for (const i in obj) {
// Object.hasOwn() is used to exclude properties from the object's
// prototype chain and only show "own properties"
if (Object.hasOwn(obj, i)) {
result += `${objName}.${i} = ${obj[i]}\n`;
}
}
console.log(result);
}function showProps(obj, objName) {
let result = "";
Object.keys(obj).forEach((i) => {
result += `${objName}.${i} = ${obj[i]}\n`;
});
console.log(result);
}function listAllProperties(myObj) {
let objectToInspect = myObj;
let result = [];
while (objectToInspect !== null) {
result = result.concat(Object.getOwnPropertyNames(objectToInspect));
objectToInspect = Object.getPrototypeOf(objectToInspect);
}
return result;
}// Creates a new object, myObj, with two properties, a and b.
const myObj = { a: 5, b: 12 };
// Removes the a property, leaving myObj with only the b property.
delete myObj.a;
console.log("a" in myObj); // falseCar.prototype.color = "red";
console.log(car1.color); // "red"objectName.methodName = functionName;
const myObj = {
myMethod: function (params) {
// do something
},
// this works too!
myOtherMethod(params) {
// do something else
},
};objectName.methodName(params);Car.prototype.displayCar = function () {
const result = `A Beautiful ${this.year} ${this.make} ${this.model}`;
console.log(result);
};car1.displayCar();
car2.displayCar();const manager = {
name: "Karina",
age: 27,
job: "Software Engineer",
};
const intern = {
name: "Tyrone",
age: 21,
job: "Software Engineer Intern",
};
function sayHi() {
console.log(`Hello, my name is ${this.name}`);
}
// Add sayHi function to both objects
manager.sayHi = sayHi;
intern.sayHi = sayHi;
manager.sayHi(); // Hello, my name is Karina
intern.sayHi(); // Hello, my name is Tyroneconst myObj = {
a: 7,
get b() {
return this.a + 1;
},
set c(x) {
this.a = x / 2;
},
};
console.log(myObj.a); // 7
console.log(myObj.b); // 8, returned from the get b() method
myObj.c = 50; // Calls the set c(x) method
console.log(myObj.a); // 25const myObj = { a: 0 };
Object.defineProperties(myObj, {
b: {
get() {
return this.a + 1;
},
},
c: {
set(x) {
this.a = x / 2;
},
},
});
myObj.c = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
console.log(myObj.b); // Runs the getter, which yields a + 1 or 6// Two variables, two distinct objects with the same properties
const fruit = { name: "apple" };
const anotherFruit = { name: "apple" };
fruit == anotherFruit; // return false
fruit === anotherFruit; // return false// Two variables, a single object
const fruit = { name: "apple" };
const anotherFruit = fruit; // Assign fruit object reference to anotherFruit
// Here fruit and anotherFruit are pointing to same object
fruit == anotherFruit; // return true
fruit === anotherFruit; // return true
fruit.name = "grape";
console.log(anotherFruit); // { name: "grape" }; not { name: "apple" }