"Object are huge part of the Javascript language, and it at the core of many things we do. So learning how to use them is definitely essential. " | ||
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
Basically, all javaScript values, except primitives, are objects.
I think the best way to easily understand objects in javascript is to compare it with objects in real life objects.
Objects in real life have properties and also have things they can do, for an example Car object could have color, make and model year as its properties, but it also has things it can do, it could move and horn. Now an object in javascript is no different, it has properties and it can have things it can do.
So, for an instance we could have a User object in javascript and it properties would be an email, a username and a gender and it can also have things it can do in javascript these are called methods which are just functions, so a User object could have a Login method and a Logout Method. Another good example would be if we had a blog object which will represent a single blog on a website, now the properties of a blog object could be a title, the content and the author and the methods could be publish, unpublish or a method to delete the blog. So you can see how javascript objects and real life objects are quite similar, they both have properties and they both have things they can do but in javascript they are called methods which are simply functions.
So, this idea of Objects is going to allow us to create this kind of data structures which represent certain things in our application code.
Creating Objects in Javascript
Even though javascript has some built in objects like the Date and Math object, it also allows us to create or define our own objects and we can do this in a variety of way.
- Object Literal Notation
- Object Constructor
- Constructor Function
- Prototype Inheritance
Using an Object Literal
The object literal notation allows us to create single objects.
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 gender:male) inside curly braces {}
The following example creates a new JavaScript object:
let user = {
name: "Jannet"
};
So, if you want to add more than one property you separate them with a comma, just remember not to add comma to the last one.
let user = {
name: "Jannet",
age: 30,
email: 'jannet@gmail.com',
location: 'Nigeria',
blogs: ["human resource management", "tech for the non-tech savvy"]
};
Accessing The Object Properties
There are basically two ways of accessing an object properties.
- Dot Notation
- Square Bracket Notation
Dot Notation
Let say we want to access the name property of our object.
console.log(user.name);
// Output: Jannet
Perhaps later on in our code if you want to override or change the value of a property in our objects we could do this way:
// we change the age property from 30 to 35
user.age = 35;
console.log(user.age)
// Output: 35
Square Bracket Notation
Let's say we want to access the name property of our user object, we use the a set of square brackets like so [].
console.log(user['name'])
You can also update or change the name property like so:
user["name"] = "Lanre"
console.log(user["name"]);
// Output: Lanre
You can also define object properties like so:
let user = {
"User Name": "Jannet"
};
But this types of properties are only accessed with the bracket notation like so:
user["User Name"];
console.log(user["User Name"])
// Output: Jannet
They can also be used to pass variables, let say you want to access the location.
const key = "location";
console.log(user[key]);
// Output: Nigeria
Adding Methods to Objects đź‘©
Methods are basically functions inside of an Object, which holds a piece of code. We can add a method called login to our user object like so:
let user = {
name: "Jannet",
age: 30,
email: 'jannet@gmail.com',
location: 'Nigeria',
blogs: ["human resource management", "tech for the non-tech savvy"],
login: function() {
console.log("the user is logged in");
}
};
And we can call or invoke the method like so:
user.login();
// Output: the user is logged in
Accessing object properties within the object methods
Let say we want to create a method in our object that prints out the text in the blog array of our object. first we'll need to access the the blog property, and we do so by using the "this" keyword in javascript.
Now, the question is what is the "this" keyword ?
put simply the this keyword is a context object and it represents the context the current code is executing, so depending on where and how we use it value is going to be different. if you use "this" inside the root of the document, it value is going to refer to the global object which is the Window object. But if we use "this" inside of a method in our object the "this" keyword would refer to our user object.
...
printBlog: function() {
console.log(this)
}
...
// Output: the user object
So, we can use "this" keyword to access the blog property and print it values like so:
...
printBlog: function() {
this.blog.forEach(blog => {
console.log(blog)
})
};
...
Deleting Properties
The delete keyword deletes a property from an object:
let user = {
name: "Jannet",
age: 30,
email: 'jannet@gmail.com',
location: 'Nigeria',
blogs: ["human resource management", "tech for the non-tech savvy"]
};
delete user.age
Things To Note About The delete operator
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.
Using an Object Constructor
Another way to create objects in JavaScript involves using the “Object” constructor. The Object constructor creates an object wrapper for the given value. This, used in conjunction with the “new” keyword allows us to initialize new objects like so:
const user = new Object();
user.name = 'Jannet';
school.location = 'Nigeria';
school.age = 34;
user.displayInfo = function(){
console.log(`My ${user.name} i live in
in ${user.location} and am ${user.age} years old`);
};
user.displayInfo();
//Output:
Notice how i accessed the properties in the displayInfo() method, this approach is also accepted in Javascript if you dont want to use the "this keyword" you can directly access the properties.
NOTE: The two methods mentioned above are not well suited to programs that require the creation of multiple objects of the same kind, as it would involve repeatedly writing the above lines of code for each such object. To deal with this problem, we can make use of two other methods of object creation in JavaScript that reduces this burden significantly, as mentioned below:
Using Constructor Function
Constructors in JavaScript, like in most other Object Oriented Programming languages, provides a template sometimes called a blueprint for creation of objects. In other words, it defines a set of properties and methods that would be common to all objects initialized using the constructor.
Here is an example:
function User(name,age, location) {
this.name = name;
this.age = age;
this.language = language;
}
// creating new object
const object1 = new User("Bola", 20, "Nigeria");
const object2 = new User("Bola", 29, "New York");
The this keyword
Remember when i said the value of this, when used in an object, is the object itself.
However, 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.
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:
User.name = "Lanre";
To add a new property to a constructor, you must add it to the constructor function:
function User(name,age, location) {
this.name = name;
this.age = age;
this.language = language;
this.isArrogant = false;
}
Adding a Method to a Constructor
Adding methods to an constructor must be done inside the constructor function:
function User(name,age, location) {
this.name = name;
this.age = age;
this.language = language;
this.isArrogant = false;
this.sayName = function() {
console.log("My Name is "+ this.name)
}
}
Built-in JavaScript Constructors
Here is the list of built in JavaScript constructors for native objects:
var object = new Object(); // A new Object object
var string = new String(); // A new String object
var number = new Number(); // A new Number object
var boolean = new Boolean(); // A new Boolean object
var array = new Array(); // A new Array object
var regex = new RegExp(); // A new RegExp object
var function = new Function(); // A new Function object
var date = new Date(); // A new Date object
JavaScript Object Prototypes
Another way to create objects involves using prototypes. All JavaScript objects inherit properties and methods from a prototype.
Browsers implement prototypes through the proto property and this is how we’ll refer to it.
- Date objects inherit from Date.prototype
- Array objects inherit from Array.prototype
- String object inherit from String.prototype
- Number object inherit from Number.prototype
- Boolean object inherit from Boolean.prototype
- Person objects inherit from Person.prototype
NOTE: that the Object.prototype is on the top of the prototype inheritance chain.
Using the prototype Property
The JavaScript prototype property allows you to add new properties to object constructor function:
function User(name,age, location) {
this.name = name;
this.age = age;
}
Person.prototype.isArrogant = "false";
And you can also add new methods to objects constructor function like so:
function User(name,age, location) {
this.name = name;
this.age = age;
}
User.prototype.sayName = function(){
console.log("My name is " + this.name)
};
ES5 New Object Methods
ECMAScript 5 added some new Object Methods to be aware of JavaScript.
We'll Look into some of them and their use case.
Object.defineProperty()
The static method Object.defineProperty() defines a new property directly on an object, or modifies an existing property on an object, and returns the object.
Here is an example:
const object1 = {};
Object.defineProperty(object1, 'property1', {
value: 42,
writable: false
});
object1.property1 = 77;
// throws an error in strict mode
console.log(object1.property1);
// expected output: 42
Object.assign()
The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.
It syntax Looks like this:
const targetObject = { a: 1, b: 2 };
const sourceObject = { b: 4, c: 5 };
const returnedTargetOject = Object.assign(target, source);
console.log(targetObject);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTargetObject);
// expected output: Object { a: 1, b: 4, c: 5 }
Object.create()
The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.
const User = {
age: 0,
printIntroduction: function() {
console.log(`My name is ${this.name}. Am ${this.age} years old`);
}
};
const object1 = Object.create(person);
object1.name = 'Steve';
me.age = 34; // inherited properties can be overwritten
object1.printIntroduction();
// expected output: "My name is Steve. Am 34 years old"
Object.entries()
The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop. (The only important difference is that a for...in loop enumerates properties in the prototype chain as well).
The order of the array returned by Object.entries() does not depend on how an object is defined. If there is a need for certain ordering, then the array should be sorted first.
const obj = { foo: 'bar', baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]
// array like object
const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]
Object.freeze()
The Object.freeze() method freezes an object. A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed. In addition, freezing an object also prevents its prototype from being changed. freeze() returns the same object that was passed in.
const obj = {
prop: 42
};
Object.freeze(obj);
obj.prop = 33;
// Throws an error in strict mode
console.log(obj.prop);
// expected output: 42
Object.is()
The Object.is() method determines whether two values are the same value.
const obj1 = {value: 20}
const obj2 = {value: 10}
Object.is(obj1, obj2);
// Output: false
Object.keys()
The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.
const object1 = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]
Object.hasOwnProperty()
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
const object1 = {};
object1.property1 = 42;
console.log(object1.hasOwnProperty('property1'));
// expected output: true
console.log(object1.hasOwnProperty('toString'));
// expected output: false
console.log(object1.hasOwnProperty('hasOwnProperty'));
// expected output: false
const object1 = {};
object1.property1 = 42;
console.log(object1.hasOwnProperty('property1'));
// expected output: true
console.log(object1.hasOwnProperty('toString'));
// expected output: false
console.log(object1.hasOwnProperty('hasOwnProperty'));
// expected output: false
So, you can get a lot more stuff and play around each and every concept.
I had just gone through the Introduction in all concepts, so If you had any
queries Just Ask in the response section.
Thanks for your time! ...
You can follow me on Instagram & Twitter @elechipro.
Reference From:
https://developer.mozilla.org/
https://www.w3schools.com/
Top comments (2)
Excellentđź’Žđź’Ž
Thank you for this article!