- JavaScript Introduction
- JavaScript Where To
- JavaScript Output
- JavaScript Statements
- JavaScript Syntax
- JavaScript Comments
- JavaScript Variables
- JavaScript Let
- JavaScript Const
- JavaScript Operators
- JavaScript Assignment
- JavaScript Data Types
- JavaScript Functions
- JavaScript Objects
- JavaScript Events
- JavaScript Strings
- JavaScript String Methods
- JavaScript Numbers
- JavaScript Number Methods
- JavaScript Arrays
- JavaScript Array Const
- JavaScript Array Methods
- JavaScript Sorting Arrays
- JavaScript Array Iteration
- JavaScript Date Objects
- JavaScript Date Formats
- JavaScript Get Date Methods
- JavaScript Set Date Methods
- JavaScript Math Object
- JavaScript Random
- JavaScript Booleans
- JavaScript Comparison And Logical Operators
- JavaScript If Else And Else If
- JavaScript Switch Statement
- JavaScript For Loop
- JavaScript Break And Continue
- JavaScript Type Conversion
- JavaScript Bitwise Operations
- JavaScript Regular Expressions
- JavaScript Errors
- JavaScript Scope
- JavaScript Hoisting
- JavaScript Use Strict
- The JavaScript This Keyword
- JavaScript Arrow Function
- JavaScript Classes
- JavaScript JSON
- JavaScript Debugging
- JavaScript Style Guide
- JavaScript Common Mistakes
- JavaScript Performance
- JavaScript Reserved Words
- JavaScript Versions
- JavaScript History
- JavaScript Forms
- JavaScript Validation API
- JavaScript Objects
- JavaScript Object Properties
- JavaScript Function Definitions
- JavaScript Function Parameters
- JavaScript Function Invocation
- JavaScript Closures
- JavaScript Classes
- Java Script Async
- JavaScript HTML DOM
- The Browser Object Model
- JS Ajax
- JavaScript JSON
- JavaScript Web APIs
- JS Vs JQuery
JavaScript 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:
or
or
The expression must evaluate to a property name.
Example 1
Example 2
JavaScript for...in Loop
The JavaScript for...in
statement loops through the properties of an object.
Syntax
// 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
fname:" John",
lname:" Doe",
age: 25
};
for (let x in person) {
txt += person[x];
}
Practice Excercise Practice now
Add Or Delete Properties
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
Deleting Properties
The delete
keyword deletes a property from an object:
Example
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
delete person.age;
or delete person["age"];
Example
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.
Practice Excercise Practice now
Nested Objects And Arrays
Values in an object can be another object:
Example
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
or:
Example
or:
Example
or:
Example
let p2 = "car2";
myObj[p1][p2];
Nested Arrays and Objects
Values in objects can be arrays, and values in arrays can be objects:
Example
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
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.
Practice Excercise Practice now
JavaScript Object Methods
Example
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
The this Keyword
In a function definition, this
refers to the "owner" of the function.
In the example above, this
is the person object that "owns" the fullName function.
In other words, this.firstName means the firstName property of this object.
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
If you access the fullName property, without (), it will return the function definition:
Example
Adding a Method to an Object
Adding a new method to an object is easy:
Example
return this.firstName + " " + this.lastName;
};
This example uses the toUpperCase()
method of the String object, to convert a text to uppercase:
let x = message.toUpperCase();
The value of x, after execution of the code above will be:
HELLO WORLD!
Example
return (this.firstName + " " + this.lastName).toUpperCase();
};
Practice Excercise Practice now
JavaScript Display Objects
How to Display JavaScript Objects?
Displaying a JavaScript object will output [object Object].
Example
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
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
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()
:
name: "John",
age: 30,
city: "New York"
};
var myArray = Object.values(person);
myArray
is now a JavaScript array, ready to be displayed:
Example
name: "John",
age: 30,
city: "New York"
};
var myArray = Object.values(person);
document.getElementById("demo").innerHTML = myArray;
Object.values()
is supported in all major browsers since 2016.
54 (2016) | 14 (2016) | 47 (2016) | 10 (2016) | 41 (2016) |
Using JSON.stringify()
JSON.stringify()
:name: "John",
age: 30,
city: "New York"
};
var myString = JSON.stringify(person);
myString
is now a JavaScript string, ready to be displayed:
Example
name: "John",
age: 30,
city: "New York"
};
var myString = JSON.stringify(person);
document.getElementById("demo").innerHTML = myString;
The result will be a string following the JSON notation:
JSON.stringify()
is included in JavaScript and supported in all major browsers.
Stringify Dates
JSON.stringify
converts dates into strings:
Example
name: "John",
today: new Date()
};
let myString = JSON.stringify(person);
document.getElementById("demo").innerHTML = myString;
Stringify Functions
JSON.stringify
will not stringify functions:
Example
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
name: "John",
age: function () {return 30;}
};
person.age = person.age.toString();
var myString = JSON.stringify(person);
document.getElementById("demo").innerHTML = myString;
Stringify Arrays
It is also possible to stringify JavaScript arrays:
Example
let myString = JSON.stringify(arr);
document.getElementById("demo").innerHTML = myString;
The result will be a string following the JSON notation:
Practice Excercise Practice now
JavaScript Object Accessors
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.
Example
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
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
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
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
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
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
const obj = {counter : 0};
// Define setters
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;
Practice Excercise Practice now
JavaScript Object Constructors
Example
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
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 myMother = new Person("Sally", "Rally", 48, "green");
The this Keyword
In JavaScript, the thing called this
is the object that "owns" the code.
The value of this
, when used in an object, is the object itself.
In a constructor function this
does not have a value. It is a substitute for the new object. The value of this
will become the new object when a new object is created.
Note that this
is not a variable. It is a keyword. You cannot change the value of this
.
Adding a Property to an Object
Adding a new property to an existing object is easy:
Example
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
return this.firstName + " " + this.lastName;
};
The method will be added to myFather. Not to myMother. (Not to any other person objects).
Adding a Property to a Constructor
You cannot add a new property to an object constructor the same way you add a new property to an existing object:
Example
To add a new property to a constructor, you must add it to the constructor function:
Example
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English";
}
This way object properties can have default values.
Adding a Method to a Constructor
Your constructor function can also define methods:
Example
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.name = function() {
return this.firstName + " " + this.lastName;
};
}
You cannot add a new method to an object constructor the same way you add a new method to an existing object.
Adding methods to an object constructor must be done inside the constructor function:
Example
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.eyeColor = eyeColor;
this.changeName = function (name) {
this.lastName = name;
};
}
The changeName() function assigns the value of name to the person's lastName property.
Now You Can Try:
JavaScript knows which person you are talking about by "substituting" this with myMother.
Built-in JavaScript Constructors
JavaScript has built-in constructors for native objects:
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
The Math()
object is not in the list. Math
is a global object. The new
keyword cannot be used on Math
.
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 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
String Objects
Normally, strings are created as primitives: firstName = "John"
But strings can also be created as objects using the new
keyword:
firstName = new String("John")
Number Objects
Normally, numbers are created as primitives: x = 30
But numbers can also be created as objects using the new
keyword:
x = new Number(30)
Boolean Objects
Normally, booleans are created as primitives: x = false
But booleans can also be created as objects using the new
keyword:
x = new Boolean(false)
Practice Excercise Practice now
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
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
To add a new property to a constructor, you must add it to the constructor function:
Example
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 fromDate.prototype
Array
objects inherit fromArray.prototype
Person
objects inherit fromPerson.prototype
The Object.prototype
is on the top of the prototype inheritance chain:
Date
objects, Array
objects, and Person
objects inherit from Object.prototype
.
Adding Properties and Methods to Objects
Sometimes you want to add new properties (or methods) to all existing objects of a given type.
Sometimes you want to add new properties (or methods) to an object constructor.
Using the prototype Property
The JavaScript prototype
property allows you to add new properties to object constructors:
Example
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
The JavaScript prototype
property also allows you to add new methods to objects constructors:
Example
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};
Practice Excercise Practice now
JavaScript ES5 Object Methods
ECMAScript 5 added a lot of new Object Methods to JavaScript.
ES5 New Object Methods
// Adding or changing an object propertyObject.defineProperty(object, property, descriptor)
// Adding or changing many object properties
Object.defineProperties(object, descriptors)
// Accessing Properties
Object.getOwnPropertyDescriptor(object, property)
// Returns all properties as an array
Object.getOwnPropertyNames(object)
// Returns enumerable properties as an array
Object.keys(object)
// Accessing the prototype
Object.getPrototypeOf(object)
// Prevents adding properties to an object
Object.preventExtensions(object)
// Returns true if properties can be added to an object
Object.isExtensible(object)
// Prevents changes of object properties (not values)
Object.seal(object)
// Returns true if object is sealed
Object.isSealed(object)
// Prevents any changes to an object
Object.freeze(object)
// Returns true if object is frozen
Object.isFrozen(object)
Changing a Property Value
Syntax
This example changes a property value:
Example
firstName: "John",
lastName : "Doe",
language : "EN"
};
// Change a property
Object.defineProperty(person, "language", {value : "NO"});
Changing Meta Data
ES5 allows the following property meta data to be changed:
writable : true // Property value can be changedenumerable : true // Property can be enumerated
configurable : true // Property can be reconfigured
writable : false // Property value can not be changed
enumerable : false // Property can be not enumerated
configurable : false // Property can be not reconfigured
ES5 allows getters and setters to be changed:
// Defining a getterget: function() { return language }
// Defining a setter
set: function(value) { language = value }
This example makes language read-only:
Object.defineProperty(person, "language", {writable:false});This example makes language not enumerable:
Object.defineProperty(person, "language", {enumerable:false});Listing All Properties
This example list all properties of an object:
Example
firstName: "John",
lastName : "Doe",
language : "EN"
};
Object.defineProperty(person, "language", {enumerable:false});
Object.getOwnPropertyNames(person); // Returns an array of properties
Listing Enumerable Properties
This example list only the enumerable properties of an object:
Example
firstName: "John",
lastName : "Doe",
language : "EN"
};
Object.defineProperty(person, "language", {enumerable:false});
Object.keys(person); // Returns an array of enumerable properties
Adding a Property
This example adds a new property to an object:
Example
const person = {
firstName: "John",
lastName : "Doe",
language : "EN"
};
// Add a property
Object.defineProperty(person, "year", {value:"2008"});
Adding Getters and Setters
The Object.defineProperty()
method can also be used to add Getters and Setters:
Example
const person = {firstName:"John", lastName:"Doe"};
// Define a getter
Object.defineProperty(person, "fullName", {
get: function () {return this.firstName + " " + this.lastName;}
});
A Counter Example
Example
const obj = {counter:0};
// Define setters
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 (i) {this.counter -= i;}
});
// Play with the counter:
obj.reset;
obj.add = 5;
obj.subtract = 1;
obj.increment;
obj.decrement;
Practice Excercise Practice now
Products
Partner
Copyright © RVR Innovations LLP 2024 | All rights reserved - Mytat.co is the venture of RVR Innovations LLP