JS Objects
JS Objects
JS Objects
Object Definition
In JavaScript, almost "everything" is an object.
JavaScript Primitives
A primitive value is a value that has no properties or methods.
Examples
string
number
boolean
null
undefined
symbol
bigint
Immutable
Primitive values are immutable (they are hardcoded and cannot be changed).
if x = 3.14, you can change the value of x, but you cannot change the value of
3.14.
Example
let person = "John Doe";
Objects are variables too. But objects can contain many values.
Object values are written as name : value pairs (name and value separated by
a colon).
Example
let person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
A JavaScript object is a collection of named values
Example
const person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
Object Properties
The named values, in JavaScript objects, are called properties.
Property Value
firstName John
lastName Doe
age 50
eyeColor blue
Object Methods
Methods are actions that can be performed on objects.
Object properties can be both primitive values, other objects, and functions.
Property Value
firstName John
lastName Doe
age 50
eyeColor blue
fullName function() {return this.firstName + " " + this.lastName;}
JavaScript objects are containers for named values, called properties and
methods.
Using an object literal, you both define and create an object in one statement.
An object literal is a list of name:value pairs (like age:50) inside curly braces
{}.
The following example creates a new JavaScript object with four properties:
Example
const person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
Spaces and line breaks are not important. An object definition can span multiple
lines:
Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
This example creates an empty JavaScript object, and then adds 4 properties:
Example
const person = {};
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
Example
const person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
The examples above do exactly the same.
For readability, simplicity and execution speed, use the object literal method.
JavaScript Objects are Mutable
Objects are mutable: They are addressed by reference, not by value.
If person is an object, the following statement will not create a copy of person:
The object x is not a copy of person. It is person. Both x and person are the
same object.
Any changes to x will also change person, because x and person are the same
object.
Example
const person = {
firstName:"John",
lastName:"Doe",
age:50, eyeColor:"blue"
}
const x = person;
x.age = 10; // Will change both x.age and person.age
Object Properties
JavaScript Properties
Properties are the values associated with a JavaScript object.
Properties can usually be changed, added, and deleted, but some are read only.
Accessing JavaScript Properties
The syntax for accessing the property of an object is:
or
objectName["property"] // person["age"]
or
Example 1
person.firstname + " is " + person.age + " years old.";
Example 2
person["firstname"] + " is " + person["age"] + " years old.";
Syntax
for (let variable in object) {
// code to be executed
}
The block of code inside of the for...in loop will be executed once for each
property.
Example
const person = {
fname:" John",
lname:" Doe",
age: 25
};
for (let x in person) {
txt += person[x];
}
Assume that the person object already exists - you can then give it new
properties:
Example
person.nationality = "English";
Deleting Properties
The delete keyword deletes a property from an object:
Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
delete person.age;
or delete person["age"];
Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
delete person["age"];
The delete keyword deletes both the value of the property and the property
itself.
After deletion, the property cannot be used before it is added back again.
Nested Objects
Values in an object can be another object:
Example
myObj = {
name:"John",
age:30,
cars: {
car1:"Ford",
car2:"BMW",
car3:"Fiat"
}
}
You can access nested objects using the dot notation or the bracket notation:
Example
myObj.cars.car2;
or:
Example
myObj.cars["car2"];
or:
Example
myObj["cars"]["car2"];
or:
Example
let p1 = "cars";
let p2 = "car2";
myObj[p1][p2];
Example
const myObj = {
name: "John",
age: 30,
cars: [
{name:"Ford", models:["Fiesta", "Focus", "Mustang"]},
{name:"BMW", models:["320", "X3", "X5"]},
{name:"Fiat", models:["500", "Panda"]}
]
}
To access arrays inside arrays, use a for-in loop for each array:
Example
for (let i in myObj.cars) {
x += "<h1>" + myObj.cars[i].name + "</h1>";
for (let j in myObj.cars[i].models) {
x += myObj.cars[i].models[j];
}
}
Property Attributes
All properties have a name. In addition they also have a value.
These attributes define how the property can be accessed (is it readable?, is it
writable?)
In JavaScript, all attributes can be read, but only the value attribute can be
changed (and only if the property is writable).
( ECMAScript 5 has methods for both getting and setting all property attributes)
Prototype Properties
JavaScript objects inherit the properties of their prototype.
Object Methods
Example
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
Try it Yourself »
What is this?
In JavaScript, the this keyword refers to an object.
Note
this is not a variable. It is a keyword. You cannot change the value of this.
See Also:
The JavaScript this Tutorial
JavaScript Methods
JavaScript methods are actions that can be performed on objects.
Property Value
firstName John
lastName Doe
age 50
eyeColor blue
objectName.methodName()
You will typically describe fullName() as a method of the person object, and
fullName as a property.
The fullName property will execute (as a function) when it is invoked with ().
Example
name = person.fullName();
Example
name = person.fullName;
Example
person.name = function () {
return this.firstName + " " + this.lastName;
};
Example
person.name = function () {
return (this.firstName + " " + this.lastName).toUpperCase();
};
Object Display
Example
const person = {
name: "John",
age: 30,
city: "New York"
};
document.getElementById("demo").innerHTML = person;
Example
const person = {
name: "John",
age: 30,
city: "New York"
};
document.getElementById("demo").innerHTML =
person.name + "," + person.age + "," + person.city;
Example
const person = {
name: "John",
age: 30,
city: "New York"
};
let txt = "";
for (let x in person) {
txt += person[x] + " ";
};
document.getElementById("demo").innerHTML = txt;
You must use person[x] in the loop.
Using Object.values()
Any JavaScript object can be converted to an array using Object.values():
const person = {
name: "John",
age: 30,
city: "New York"
};
const myArray = Object.values(person);
Example
const person = {
name: "John",
age: 30,
city: "New York"
};
const myArray = Object.values(person);
document.getElementById("demo").innerHTML = myArray;
Using JSON.stringify()
Any JavaScript object can be stringified (converted to a string) with the
JavaScript function JSON.stringify():
const person = {
name: "John",
age: 30,
city: "New York"
};
let myString = JSON.stringify(person);
Example
const person = {
name: "John",
age: 30,
city: "New York"
};
let myString = JSON.stringify(person);
document.getElementById("demo").innerHTML = myString;
The result will be a string following the JSON notation:
{"name":"John","age":50,"city":"New York"}
Stringify Dates
JSON.stringify converts dates into strings:
Example
const person = {
name: "John",
today: new Date()
};
let myString = JSON.stringify(person);
document.getElementById("demo").innerHTML = myString;
Stringify Functions
JSON.stringify will not stringify functions:
Example
const person = {
name: "John",
age: function () {return 30;}
};
let myString = JSON.stringify(person);
document.getElementById("demo").innerHTML = myString;
This can be "fixed" if you convert the functions into strings before stringifying.
Example
const person = {
name: "John",
age: function () {return 30;}
};
person.age = person.age.toString();
let myString = JSON.stringify(person);
document.getElementById("demo").innerHTML = myString;
Stringify Arrays
It is also possible to stringify JavaScript arrays:
Example
const arr = ["John", "Peter", "Sally", "Jane"];
let myString = JSON.stringify(arr);
document.getElementById("demo").innerHTML = myString;
The result will be a string following the JSON notation:
["John","Peter","Sally","Jane"]
Object Accessors
Example
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
language: "en",
get lang() {
return this.language;
}
};
Example
const person = {
firstName: "John",
lastName: "Doe",
language: "",
set lang(lang) {
this.language = lang;
}
};
Example 1
const person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the object using a method:
document.getElementById("demo").innerHTML = person.fullName();
Example 2
const person = {
firstName: "John",
lastName: "Doe",
get fullName() {
return this.firstName + " " + this.lastName;
}
};
Data Quality
JavaScript can secure better data quality when using getters and setters.
Example
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
language: "en",
get lang() {
return this.language.toUpperCase();
}
};
Example
const person = {
firstName: "John",
lastName: "Doe",
language: "",
set lang(lang) {
this.language = lang.toUpperCase();
}
};
Object.defineProperty()
The Object.defineProperty() method can also be used to add Getters and Setters:
A Counter Example
// Define object
const obj = {counter : 0};
Object Constructors
Example
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Notes
It is considered good practice to name constructor functions with an upper-case
first letter.
Objects of the same type are created by calling the constructor function with
the new keyword:
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");