Js Objects
* * *
In JavaScript, everything is an object: strings, numbers, arrays, functions...
Moreover, JavaScript allows you to define custom objects.
* * *
## Everything Is an Object
JavaScript provides several built-in objects, such as String, Date, Array, and more. An object is simply a special data type that has properties and methods.
* A Boolean can be an object.
* A Number can be an object.
* A string can also be an object.
* A Date is an object.
* Math and regular expressions are also objects.
* An array is an object.
* Even functions can be objects.
* * *
## JavaScript Objects
An object is just a special kind of data. An object has **properties** and **methods**.
* * *
## Accessing Object Properties
A property is a value associated with an object.
The syntax for accessing an object's property is:
objectName.propertyName
This example uses the length property of the String object to get the length of a string:
var message="Hello World!";var x=message.length;
After the above code executes, the value of x will be:
12
* * *
## Accessing Object Methods
A method is an action that can be performed on an object.
You can call a method using the following syntax:
objectName.methodName()
This example uses the toUpperCase() method of the String object to convert text to uppercase:
var message="Hello world!";var x=message.toUpperCase();
After the above code executes, the value of x will be:
HELLO WORLD!
* * *
## Creating JavaScript Objects
With JavaScript, you can define and create your own objects.
There are two different ways to create new objects:
* Use Object to define and create instances of objects.
* Use a function to define an object and then create new instances of that object.
### Using Object
In JavaScript, almost all objects are instances of the Object type, and they inherit properties and methods from Object.prototype.
The Object constructor creates an object wrapper.
The Object constructor creates an object based on the given argument, with the following cases:
* If the given value is null or undefined, it will create and return an empty object.
* If a primitive value is passed in, it will construct an object of its wrapper type.
* If a reference type value is passed in, it will still return that value; variables copied from them hold the same reference address as the source object.
* When called without being a constructor, Object behaves the same as new Object().
Syntax format:
// Called as a constructor: new Object()
value can be any value.
The following example uses Object to create a Boolean object:
// Equivalent to o = new Boolean(true);var o = new Object(true);
This example creates a new instance of an object and adds four properties to it:
## Example
person=new Object(); person.firstname="John"; person.lastname="Doe"; person.age=50; person.eyecolor="blue";
[Try it Β»](
You can also use object literals to create objects, with the following syntax:
var myObject = { key1: value1, key2: value2, // More key-value pairs...};
* **myObject:** The variable name used to reference the entire object.
* **key1, key2:** Property names, which can be strings or identifiers.
* **value1, value2:** The values of the properties, which can be any JavaScript data type, including numbers, strings, booleans, functions, arrays, or even other objects.
## Example
var person ={
firstName:'John',
lastName:'Doe',
age:30,
isStudent:false,
greet:function(){
console.log('Hello, I am '+this.firstName+' '+this.lastName);
}
};
console.log(person.firstName);// Output: John
person.greet();// Output: Hello, I am John Doe
## Example
person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
[Try it Β»](
A JavaScript object is essentially a collection of **name:value** pairs.
* * *
## Using Object Constructors
This example uses a function to construct objects:
## Example
function person(firstname,lastname,age,eyecolor){this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; }
[Try it Β»](
In JavaScript, `this` usually refers to the function itself that we're executing, or to the object that the function belongs to (at runtime).
* * *
## Creating JavaScript Object Instances
Once you have an object constructor, you can create new object instances like this:
var myFather=new person("John","Doe",50,"blue");var myMother=new person("Sally","Rally",48,"green");
* * *
## Adding Properties to JavaScript Objects
You can add new properties to existing objects by assigning values to them:
Assume the person object already existsβyou can add these new properties to it: firstname, lastname, age, and eyecolor:
person.firstname="John"; person.lastname="Doe"; person.age=30; person.eyecolor="blue"; x=person.firstname;
After the above code executes, the value of x will be:
John
* * *
## Adding Methods to JavaScript Objects
Methods are simply functions attached to objects.
Define methods of an object inside the constructor function:
function person(firstname,lastname,age,eyecolor){this.firstname=firstname;this.lastname=lastname;this.age=age;this.eyecolor=eyecolor;this.changeName=changeName;function changeName(name){this.lastname=name;}}
The changeName() function assigns the value of name to the person's lastname property.
## Now you can try it out:
myMother.changeName("Doe");
[Try it Β»](
* * *
## JavaScript Classes
JavaScript is an object-oriented language, but JavaScript doesn't use classes.
In JavaScript, you don't create classes, nor do you create objects through classes (as you would in other object-oriented languages).
JavaScript is prototype-based, rather than class-based.
* * *
## JavaScript for...in Loop
The JavaScript for...in statement loops through the properties of an object.
### Syntax
for (variable in object){Code to executeβ¦β¦}
**Note:** The block of code in the for...in loop will execute once for each property.
### Example
Loop through the properties of an object:
## Example
var person={fname:"John",lname:"Doe",age:25}; for(x in person){txt=txt + person; }
[Try it Β»](
* * *
## JavaScript Objects Are Mutable
Objects are mutableβthey're passed by reference.
The following example shows that the person object won't create a copy:
var x = person; // No copy of person is created; it's a reference
If you modify x, the person's properties will also change:
## Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}var x = person; x.age = 10;
[Try it Β»](
YouTip