- JavaScript Objects: Create Objects, Access Properties & Methods
- Create Object using Object Literal Syntax
- Create Objects using Objects() Constructor
- Access JavaScript Object Properties & Methods
- Enumerate Object’s Properties
- Pass by Reference
- Nested Objects
- JavaScript Function Definitions
- Function Declarations
- Example
- Function Expressions
- Example
- Example
- The Function() Constructor
- Example
- Example
- Function Hoisting
- Self-Invoking Functions
- Example
- Functions Can Be Used as Values
- Example
- Example
- Functions are Objects
- Example
- Example
- Arrow Functions
- Example
- Example
JavaScript Objects: Create Objects, Access Properties & Methods
Here you will learn objects, object literals, Object() constructor function, and access object in JavaScript.
You learned about primitive and structured data types in JavaScript. An object is a non-primitive, structured data type in JavaScript. Objects are same as variables in JavaScript, the only difference is that an object holds multiple values in terms of properties and methods.
In JavaScript, an object can be created in two ways: 1) using Object Literal/Initializer Syntax 2) using the Object() Constructor function with the new keyword. Objects created using any of these methods are the same.
The following example demonstrates creating objects using both ways.
var p1 = < name:"Steve" >; // object literal syntax var p2 = new Object(); // Object() constructor function p2.name = "Steve"; // property
Above, p1 and p2 are the names of objects. Objects can be declared same as variables using var or let keywords. The p1 object is created using the object literal syntax (a short form of creating objects) with a property named name . The p2 object is created by calling the Object() constructor function with the new keyword. The p2.name = «Steve»; attach a property name to p2 object with a string value «Steve» .
Create Object using Object Literal Syntax
The object literal is a short form of creating an object. Define an object in the < >brackets with key:value pairs separated by a comma. The key would be the name of the property and the value will be a literal value or a function.
The following example demonstrates objects created using object literal syntax.
var emptyObject = <>; // object with no properties or methods var person = < firstName: "John" >; // object with single property // object with single method var message = < showMessage: function (val) < alert(val); >>; // object with properties & method var person = < firstName: "James", lastName: "Bond", age: 15, getFullName: function () < return this.firstName + ' ' + this.lastName > >;
Note that the whole key-value pair must be declared. Declaring only a key without a value is invalid, as shown below.
Create Objects using Objects() Constructor
Another way of creating objects is using the Object() constructor function using the new keyword. Properties and methods can be declared using the dot notation .property-name or using the square brackets [«property-name»] , as shown below.
var person = new Object(); // Attach properties and methods to person object person.firstName = "James"; person["lastName"] = "Bond"; person.age = 25; person.getFullName = function () < return this.firstName + ' ' + this.lastName; >;
An object can have variables as properties or can have computed properties, as shown below.
var firstName = "James"; var lastName = "Bond"; var person =
Access JavaScript Object Properties & Methods
An object’s properties can be accessed using the dot notation obj.property-name or the square brackets obj[«property-name»] . However, method can be invoked only using the dot notation with the parenthesis, obj.method-name() , as shown below.
var person = < firstName: "James", lastName: "Bond", age: 25, getFullName: function () < return this.firstName + ' ' + this.lastName > >; person.firstName; // returns James person.lastName; // returns Bond person["firstName"];// returns James person["lastName"];// returns Bond person.getFullName(); // calling getFullName function
In the above example, the person.firstName access the firstName property of a person object. The person[«firstName»] is another way of accessing a property. An object’s methods can be called using () operator e.g. person.getFullName() . JavaScript engine will return the function definition if accessed method without the parenthesis.
Accessing undeclared properties of an object will return undefined. If you are not sure whether an object has a particular property or not, then use the hasOwnProperty() method before accessing them, as shown below.
var person = new Object(); person.firstName; // returns undefined if(person.hasOwnProperty("firstName"))
The properties and methods will be available only to an object where they are declared.
var p1 = new Object(); p1.firstName = "James"; p1.lastName = "Bond"; var p2 = new Object(); p2.firstName; // undefined p2.lastName; // undefined p3 = p1; // assigns object p3.firstName; // James p3.lastName; // Bond p3.firstName = "Sachin"; // assigns new value p3.lastName = "Tendulkar"; // assigns new value
Enumerate Object’s Properties
Use the for in loop to enumerate an object, as shown below.
var person = new Object(); person.firstName = "James"; person.lastName = "Bond"; for(var prop in person)< alert(prop); // access property name alert(person[prop]); // access property value >;
Pass by Reference
Object in JavaScript passes by reference from one function to another.
function changeFirstName(per) < per.firstName = "Steve"; > var person = < firstName : "Bill" >; changeFirstName(person) person.firstName; // returns Steve
Nested Objects
An object can be a property of another object. It is called a nested object.
var person = < firstName: "James", lastName: "Bond", age: 25, address: < id: 1, country:"UK" > >; person.address.country; // returns "UK"
Points to Remember :
- JavaScript object is a standalone entity that holds multiple values in terms of properties and methods.
- Object property stores a literal value and method represents function.
- An object can be created using object literal or object constructor syntax.
- Object literal:
var person = new Object(); person.firstName = "James"; person["lastName"] = "Bond"; person.age = 25; person.getFullName = function () < return this.firstName + ' ' + this.lastName; >;
JavaScript Function Definitions
JavaScript functions are defined with the function keyword.
You can use a function declaration or a function expression.
Function Declarations
Earlier in this tutorial, you learned that functions are declared with the following syntax:
Declared functions are not executed immediately. They are «saved for later use», and will be executed later, when they are invoked (called upon).
Example
Semicolons are used to separate executable JavaScript statements.
Since a function declaration is not an executable statement, it is not common to end it with a semicolon.
Function Expressions
A JavaScript function can also be defined using an expression.
A function expression can be stored in a variable:
Example
After a function expression has been stored in a variable, the variable can be used as a function:
Example
The function above is actually an anonymous function (a function without a name).
Functions stored in variables do not need function names. They are always invoked (called) using the variable name.
The function above ends with a semicolon because it is a part of an executable statement.
The Function() Constructor
As you have seen in the previous examples, JavaScript functions are defined with the function keyword.
Functions can also be defined with a built-in JavaScript function constructor called Function() .
Example
const myFunction = new Function(«a», «b», «return a * b»);
You actually don’t have to use the function constructor. The example above is the same as writing:
Example
const myFunction = function (a, b)
Most of the time, you can avoid using the new keyword in JavaScript.
Function Hoisting
Earlier in this tutorial, you learned about «hoisting» (JavaScript Hoisting).
Hoisting is JavaScript’s default behavior of moving declarations to the top of the current scope.
Hoisting applies to variable declarations and to function declarations.
Because of this, JavaScript functions can be called before they are declared:
function myFunction(y) return y * y;
>
Functions defined using an expression are not hoisted.
Self-Invoking Functions
Function expressions can be made «self-invoking».
A self-invoking expression is invoked (started) automatically, without being called.
Function expressions will execute automatically if the expression is followed by ().
You cannot self-invoke a function declaration.
You have to add parentheses around the function to indicate that it is a function expression:
Example
The function above is actually an anonymous self-invoking function (function without name).
Functions Can Be Used as Values
JavaScript functions can be used as values:
Example
function myFunction(a, b) <
return a * b;
>
JavaScript functions can be used in expressions:
Example
function myFunction(a, b) <
return a * b;
>
Functions are Objects
The typeof operator in JavaScript returns «function» for functions.
But, JavaScript functions can best be described as objects.
JavaScript functions have both properties and methods.
The arguments.length property returns the number of arguments received when the function was invoked:
Example
The toString() method returns the function as a string:
Example
function myFunction(a, b) <
return a * b;
>
let text = myFunction.toString();
A function defined as the property of an object, is called a method to the object.
A function designed to create new objects, is called an object constructor.
Arrow Functions
Arrow functions allows a short syntax for writing function expressions.
You don’t need the function keyword, the return keyword, and the curly brackets.
Example
// ES5
var x = function(x, y) return x * y;
>
Arrow functions do not have their own this . They are not well suited for defining object methods.
Arrow functions are not hoisted. They must be defined before they are used.
Using const is safer than using var , because a function expression is always constant value.
You can only omit the return keyword and the curly brackets if the function is a single statement. Because of this, it might be a good habit to always keep them:
Example
Arrow functions are not supported in IE11 or earlier.