JS OBJECTS
Object Definition
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.
Value Type Comment
"Hello" string "Hello" is always "Hello"
3.14 number 3.14 is always 3.14
true boolean true is always true
false boolean false is always false
null null (object) null is always null
undefined undefined undefined is always undefin
Objects are Variables
JavaScript variables can contain single values:
Example
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).
Example
let person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
A JavaScript object is a collection of named values
It is a common practice to declare objects with the const keyword.
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
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.
You will learn more about methods in the next chapters.
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
This is the easiest way to create a JavaScript Object.
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";
Using the JavaScript Keyword new
The following example create a new JavaScript object using new Object(), and
then adds 4 properties:
Example
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.
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.
A JavaScript object is a collection of unordered properties.
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:
objectName.property // person.age
or
objectName["property"] // person["age"]
or
objectName[expression] // x = "age"; person[x]
The expression must evaluate to a property name.
Example 1
person.firstname + " is " + person.age + " years old.";
Example 2
person["firstname"] + " is " + person["age"] + " years old.";
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
const person = {
fname:" John",
lname:" Doe",
age: 25
};
for (let x in person) {
txt += person[x];
}
Adding New Properties
You can add new properties to an existing object by simply giving it a value.
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.
The delete operator is designed to be used on object properties. It has no effect
on variables or functions.
The delete operator should not be used on predefined JavaScript object
properties. It can crash your application.
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];
Nested Arrays and Objects
Values in objects can be arrays, and values in arrays can be objects:
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.
The value is one of the property's attributes.
Other attributes are: enumerable, configurable, and writable.
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.
The delete keyword does not delete inherited properties, but if you delete a
prototype property, it will affect all objects inherited from the 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.
Which object depends on how this is being invoked (used or called).
The this keyword refers to different objects depending on how it is used:
In an object method, this refers to the object.
Alone, this refers to the global object.
In a function, this refers to the global object.
In a function, in strict mode, this is undefined.
In an event, this refers to the element that received the event.
Methods like call(), apply(), and bind() can refer this to any 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.
A JavaScript method is a property containing a function definition.
Property Value
firstName John
lastName Doe
age 50
eyeColor blue
fullName function() {return this.firstName + " " + this.lastName;}
Methods are functions stored as object properties.
Accessing Object Methods
You access an object method with the following syntax:
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 ().
This example accesses the fullName() method of a person object:
Example
name = person.fullName();
If you access the fullName property, without (), it will return the function
definition:
Example
name = person.fullName;
Adding a Method to an Object
Adding a new method to an object is easy:
Example
person.name = function () {
return this.firstName + " " + this.lastName;
};
Using Built-In Methods
This example uses the toUpperCase() method of the String object, to convert a
text to uppercase:
let message = "Hello world!";
let x = message.toUpperCase();
The value of x, after execution of the code above will be:
HELLO WORLD!
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;
Some common solutions to display JavaScript objects are:
Displaying the Object Properties by name
Displaying the Object Properties in a Loop
Displaying the Object using Object.values()
Displaying the Object using JSON.stringify()
Displaying Object Properties
The properties of an object can be displayed as a string:
Example
const person = {
name: "John",
age: 30,
city: "New York"
};
document.getElementById("demo").innerHTML =
person.name + "," + person.age + "," + person.city;
Displaying the Object in a Loop
The properties of an object can be collected in a loop:
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.
person.x will not work (Because x is a variable).
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);
myArray is now a JavaScript array, ready to be displayed:
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);
myString is now a JavaScript string, ready to be displayed:
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"}
JSON.stringify() is included in JavaScript and supported in all major browsers.
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;
}
};
// 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.
Example
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.
Data Quality
JavaScript can secure better data quality when using getters and setters.
Using the lang property, in this example, returns the value of
the language property in upper case:
Example
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
language: "en",
get lang() {
return this.language.toUpperCase();
}
};
// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.lang;
Using the lang property, in this example, stores an upper case value in
the language property:
Example
const person = {
firstName: "John",
lastName: "Doe",
language: "",
set lang(lang) {
this.language = lang.toUpperCase();
}
};
// Set an object property using a setter:
person.lang = "en";
// Display data from the object:
document.getElementById("demo").innerHTML = person.language;
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:
A Counter Example
// 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;
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.
Object Types (Blueprints) (Classes)
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");