JavaScript Objects
In JavaScript, objects are king. If you understand objects, you understand JavaScript.
In JavaScript, almost "everything" is an object.
Booleans can be objects (if defined with the new keyword)
Numbers can be objects (if defined with the new keyword)
Strings can be objects (if defined with the new keyword)
Dates are always objects
Maths are always objects
Regular expressions are always objects
Arrays are always objects
Functions are always objects
Objects are always objects
All JavaScript values, except primitives, are objects.
JavaScript Primitives
A primitive value is a value that has no properties or methods.
3.14 is a primitive value
A primitive data type is data that has a primitive value.
JavaScript defines 7 types of primitive data types:
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.
Objects are Variables
JavaScript variables can contain single values:
let person = "John Doe";
JavaScript variables can also contain many values.
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).
let person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
It is a common practice to declare objects with the const keyword.
Objects written as name value pairs are similar to:
Associative arrays in PHP
Dictionaries in Python
Hash tables in C
Hash maps in Java
Hashes in Ruby and Perl.
Object Methods
Methods are actions that can be performed on objects.
Object properties can be both primitive values, other objects, and functions.
An object method is an object property containing a function definition.
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.
Creating a JavaScript Object
With JavaScript, you can define and create your own objects.
There are different ways to create new objects:
Create a single object, using an object literal.
Create a single object, with the keyword new.
Define an object constructor, and then create objects of the constructed type.
Create an object using Object.create().
Using an Object Literal
const person = {
firstName:"John",
lastName:"Doe",
age:50, eyeColor:"blue"
};
This example creates an empty JavaScript object, and then adds 4 properties:
const person = {};
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
Using the JavaScript Keyword new
const person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
The examples above do exactly the same.
But there is no need to use new Object().
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:
const x = person; // 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.
const person = {
firstName:"John",
lastName:"Doe",
age:50, eyeColor:"blue"
}
const x = person;
x.age = 10; // Will change both x.age and person.age
JavaScript for...in Loop
The JavaScript for...in statement loops through the properties of an object.
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.
Looping through the properties of an object:
Example
<script>
const person = {
fname:"John",
lname:"Doe",
age:25
};
let txt = "";
for (let x in person) {
txt += person[x] + " ";
document.getElementById("demo").innerHTML = txt;
</script>
Adding New Properties
person.nationality = "English";
Deleting Properties
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
delete person.age;
Nested Objects
myObj = {
name:"John",
age:30,
cars: {
car1:"Ford",
car2:"BMW",
car3:"Fiat"
}
}
Example
<script>
const myObj = {
name: "John",
age: 30,
cars: {
car1: "Ford",
car2: "BMW",
car3: "Fiat"
}
}
document.getElementById("demo").innerHTML =
myObj.cars.car2;
</script>
Nested Arrays and Objects
const myObj = {
name: "John",
age: 30,
cars: [
{name:"Ford", models:["Fiesta", "Focus", "Mus
tang"]},
{name:"BMW", models:["320", "X3", "X5"]},
{name:"Fiat", models:["500", "Panda"]}
]
}
Example
<script>
let x = "";
const myObj = {
name: "John",
age: 30,
cars: [
{name:"Ford", models:["Fiesta", "Focus", "Mustang"]},
{name:"BMW", models:["320", "X3", "X5"]},
{name:"Fiat", models:["500", "Panda"]}
for (let i in myObj.cars) {
x += "<h2>" + myObj.cars[i].name + "</h2>";
for (let j in myObj.cars[i].models) {
x += myObj.cars[i].models[j] + "<br>";
document.getElementById("demo").innerHTML = x;
</script>
JavaScript Object Methods
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
Accessing Object Methods
You access an object method with the following syntax:
objectName.methodName()
Example
<script>
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
};
document.getElementById("demo").innerHTML = person.fullName();
</script>
Using Built-In Methods
let message = "Hello world!";
let x = message.toUpperCase();
Example
<script>
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
};
person.name = function() {
return (this.firstName + " " + this.lastName).toUpperCase();
};
document.getElementById("demo").innerHTML =
"My father is " + person.name();
</script>
<script>
How to Display JavaScript Objects?
Displaying a JavaScript object will output [object Object].
<script>
const person = {
name: "John",
age: 30,
city: "New York"
};
document.getElementById("demo").innerHTML = person;
</script>
It will print the Type of the variable which is object in this case.
Using Object.values()
const person = {
name: "John",
age: 30,
city: "New York"
};
const myArray = Object.values(person);
Using JSON.stringify()
const person = {
name: "John",
age: 30,
city: "New York"
};
let myString = JSON.stringify(person);
Output
{"name":"John","age":30,"city":"New York"}
Stringify Dates
JSON.stringify converts dates into strings:
const person = {
name: "John",
today: new Date()
};
let myString = JSON.stringify(person);
document.getElementById("demo").innerHTML = myString;
Output
{"name":"John","today":"2023-12-13T05:18:18.854Z"}
Stringify Functions
JSON.stringify will not stringify functions:
This can be "fixed" if you convert the functions into strings before stringifying.
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;
Output
["John","Peter","Sally","Jane"]
JavaScript Accessors (Getters and
Setters)
ECMAScript 5 (ES5 2009) introduced Getter and Setters.
Getters and setters allow you to define Object Accessors (Computed Properties).
JavaScript Getter (The get Keyword)
This example uses a lang property to get the value of the language property.
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
language: "en",
get lang() {
return this.language;
}
};
// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.lang;
JavaScript Setter (The set Keyword)
This example uses a lang property to set the value of the language property.
const person = {
firstName: "John",
lastName: "Doe",
language: "",
set lang(lang) {
this.language = lang;
}
};
// Set an object property using a setter:
person.lang = "en";
// Display data from the object:
document.getElementById("demo").innerHTML = person.language;
JavaScript Function or Getter?
What is the differences between these two examples?
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;
}
};
// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.fullName;
Example 1 access fullName as a function: person.fullName().
Example 2 access fullName as a property: person.fullName.
The second example provides a simpler syntax.
Why Using Getters and Setters?
It gives simpler syntax
It allows equal syntax for properties and methods
It can secure better data quality
It is useful for doing things behind-the-scenes
Object.defineProperty()
The Object.defineProperty() method can also be used to add Getters and Setters:
// Define object
const obj = {counter : 0};
// Define setters and getters
Object.defineProperty(obj, "reset", {
get : function () {this.counter = 0;}
});
Object.defineProperty(obj, "increment", {
get : function () {this.counter++;}
});
Object.defineProperty(obj, "decrement", {
get : function () {this.counter--;}
});
Object.defineProperty(obj, "add", {
set : function (value) {this.counter += value;}
});
Object.defineProperty(obj, "subtract", {
set : function (value) {this.counter -= value;}
});
// Play with the counter:
obj.reset;
obj.add = 5;
obj.subtract = 1;
obj.increment;
obj.decrement;
JavaScript Object
Constructors
<script>
// Constructor function for Person objects
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
// Create a Person object
const myFather = new Person("John", "Doe", 50, "blue");
// Display age
document.getElementById("demo").innerHTML =
"My father is " + myFather.age + ".";
</script>
Output ---- My father is 50.
The examples from the previous chapters are limited. They only create
single objects.
Sometimes we need a "blueprint" for creating many objects of the same
"type".
The way to create an "object type", is to use an object constructor
function.
In the example above, function Person() is an object constructor
function.
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");
Adding a Property to an Object
Adding a new property to an existing object is easy:
Example
myFather.nationality = "English";
The property will be added to myFather. Not to myMother. (Not to any
other person objects).
Adding a Method to an Object
Adding a new method to an existing object is easy:
Example
myFather.name = function () {
return this.firstName + " " + this.lastName;
};
Built-in JavaScript Constructors
JavaScript has built-in constructors for native objects:
new String() // A new String object
new Number() // A new Number object
new Boolean() // A new Boolean object
new Object() // A new Object object
new Array() // A new Array object
new RegExp() // A new RegExp object
new Function() // A new Function object
new Date() // A new Date object
Did You Know?
As you can see above, JavaScript has object versions of the primitive data
types String, Number, and Boolean. But there is no reason to create complex
objects. Primitive values are much faster:
Use string literals "" instead of new String().
Use number literals 50 instead of new Number().
Use boolean literals true / false instead of new Boolean().
Use object literals {} instead of new Object().
Use array literals [] instead of new Array().
Use pattern literals /()/ instead of new RegExp().
Use function expressions () {} instead of new Function().
Example
let x1 = ""; // new primitive string
let x2 = 0; // new primitive number
let x3 = false; // new primitive boolean
const x4 = {}; // new Object object
const x5 = []; // new Array object
const x6 = /()/ // new RegExp object
const x7 = function(){}; // new function
JavaScript Object Prototypes
All JavaScript objects inherit properties and methods from a prototype.
In the previous chapter we learned how to use an object constructor:
Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");
We also learned that you can not add a new property to an existing object
constructor:
Example
Person.nationality = "English";
To add a new property to a constructor, you must add it to the constructor
function:
Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English";
}
Prototype Inheritance
All JavaScript objects inherit properties and methods from a prototype:
Date objects inherit from Date.prototype
Array objects inherit from Array.prototype
Person objects inherit from Person.prototype
The Object.prototype is on the top of the prototype inheritance chain:
Date objects, Array objects, and Person objects inherit from Object.prototype.
Using the prototype Property
The JavaScript prototype property allows you to add new properties to object
constructors:
Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
JavaScript Sets
A JavaScript Set is a collection of unique values.
Each value can only occur once in a Set.
A Set can hold any value of any data type
Set Methods
Method Description
new Set() Creates a new Set
add() Adds a new element to the Set
delete() Removes an element from a Set
has() Returns true if a value exists
clear() Removes all elements from a Set
forEach() Invokes a callback for each element
values() Returns an Iterator with all the values in a Set
keys() Same as values()
entries() Returns an Iterator with the [value,value] pairs from a Set
Property Description
size Returns the number elements in a Set
How to Create a Set
You can create a JavaScript Set by:
Passing an Array to new Set()
Create a new Set and use add() to add values
Create a new Set and use add() to add variables
The new Set() Method
Pass an Array to the new Set() constructor:
Example
// Create a Set
const letters = new Set(["a","b","c"]);
Create a Set and add literal values:
Example
// Create a Set
const letters = new Set();
// Add Values to the Set
letters.add("a");
letters.add("b");
letters.add("c");
Create a Set and add variables:
Example
// Create Variables
const a = "a";
const b = "b";
const c = "c";
// Create a Set
const letters = new Set();
// Add Variables to the Set
letters.add(a);
letters.add(b);
letters.add(c);
The forEach() Method
The forEach() method invokes a function for each Set element:
Example
// Create a Set
const letters = new Set(["a","b","c"]);
// List all entries
let text = "";
letters.forEach (function(value) {
text += value;
})
The values() Method
The values() method returns an Iterator object containing all the values in a Set:
Example
letters.values() // Returns [object Set Iterator]
The keys() Method
A Set has no keys.
keys() returns the same as values().
This makes Sets compatible with Maps.
Example
letters.keys() // Returns [object Set Iterator]
The entries() Method
A Set has no keys.
entries() returns [value,value] pairs instead of [key,value] pairs.
This makes Sets compatible with Maps:
Example
// Create an Iterator
const myIterator = letters.entries();
// List all Entries
let text = "";
for (const entry of myIterator) {
text += entry;
}
JavaScript Maps
A Map holds key-value pairs where the keys can be any datatype.
A Map remembers the original insertion order of the keys.
A Map has a property that represents the size of the map.
Map Methods
Method Description
new Map() Creates a new Map object
set() Sets the value for a key in a Map
get() Gets the value for a key in a Map
clear() Removes all the elements from a Map
delete() Removes a Map element specified by a key
has() Returns true if a key exists in a Map
forEach() Invokes a callback for each key/value pair in a Map
entries() Returns an iterator object with the [key, value] pairs in a Map
keys() Returns an iterator object with the keys in a Map
values() Returns an iterator object of the values in a Map
How to Create a Map
You can create a JavaScript Map by:
Passing an Array to new Map()
Create a Map and use Map.set()
new Map()
You can create a Map by passing an Array to the new Map() constructor:
Example
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
Map.set()
You can add elements to a Map with the set() method:
Example
// Create a Map
const fruits = new Map();
// Set Map Values
fruits.set("apples", 500);
fruits.set("bananas", 300);
fruits.set("oranges", 200);
The set() method can also be used to change existing Map values:
Example
fruits.set("apples", 500);
Map.get()
The get() method gets the value of a key in a Map:
Example
fruits.get("apples"); // Returns 500
Map.size
The size property returns the number of elements in a Map:
Example
fruits.size;
Map.delete()
The delete() method removes a Map element:
Example
fruits.delete("apples");
Map.clear()
The clear() method removes all the elements from a Map:
Example
fruits.clear()
Map.has()
The has() method returns true if a key exists in a Map:
Example
fruits.has("apples");
Try This:
fruits.delete("apples");
fruits.has("apples");
Maps are Objects
typeof returns object:
Example
// Returns object:
typeof fruits;
instanceof Map returns true:
Example
// Returns true:
fruits instanceof Map;
JavaScript Objects vs Maps
Differences between JavaScript Objects and Maps:
Object Map
Not directly iterable Directly iterable
Do not have a size property Have a size property
Keys must be Strings (or Symbols) Keys can be any datatype
Keys are not well ordered Keys are ordered by insertion
Have default keys Do not have default keys
Map.forEach()
The forEach() method invokes a callback for each key/value pair in a Map:
Example
// List all entries
let text = "";
fruits.forEach (function(value, key) {
text += key + ' = ' + value;
})
Try it Yourself »
Map.entries()
The entries() method returns an iterator object with the [key,values] in a Map:
Example
// List all entries
let text = "";
for (const x of fruits.entries()) {
text += x;
}
Try it Yourself »
Map.keys()
The keys() method returns an iterator object with the keys in a Map:
Example
// List all keys
let text = "";
for (const x of fruits.keys()) {
text += x;
}
Try it Yourself »
Map.values()
The values() method returns an iterator object with the values in a Map:
Example
// List all values
let text = "";
for (const x of fruits.values()) {
text += x;
}
Try it Yourself »
You can use the values() method to sum the values in a Map:
Example
// Sum all values
let total = 0;
for (const x of fruits.values()) {
total += x;
}
Try it Yourself »
Objects as Keys
Being able to use objects as keys is an important Map feature.
Example
// Create Objects
const apples = {name: 'Apples'};
const bananas = {name: 'Bananas'};
const oranges = {name: 'Oranges'};
// Create a Map
const fruits = new Map();
// Add new Elements to the Map
fruits.set(apples, 500);
fruits.set(bananas, 300);
fruits.set(oranges, 200);
Try it Yourself »
Remember: The key is an object (apples), not a string ("apples"):
Example
fruits.get("apples"); // Returns undefined
Try it Yourself »