Over the years, javascript has evolved and various features has been added to the language syntax. Some of the syntax seems strange and unknown, so here are some of the ones I have discovered in the few years i have been working with javascript.
Property Accessors
The regular way of accessing object properties in javascript is similar to other C like languages e.g getting the firstname property of a Person object is Person.firstname
.
Another way of accessing these properties is by treating the properties like keys of a map e.g Person['firstname']
. This way of accessing object properties is not limited to only fields/attributes but methods as well can be accessed this way. Below is an example using accessing methods like key of a map.
// create an array arr
var arr = ["hello"];
// access the push method of array prototype.
arr["push"]("Spankie");
console["log"](arr); // prints out: ["hello", "Spankie"]
Javascript object spreading
Concatenating objects properties in javascript has always been done with the Object
prototype method assign
, but there are other ways this can be achieved, which is done using the spread syntax ...
. here is an example;
let obj1 = { name: "Spankie" };
let obj2 = { greeting: "Hello", greet: () => console.log(this.greeting), sayhello: function() {
console.log(this.greeting);
}};
// concatenating obj2 properties into obj1...
let obj3 = {...obj1, ...obj2}
obj3.greet(); // prints out: undefined
obj3.sayhello(); // prints out: "Hello"
Javascript Object deconstructions
As mentioned earlier, getting object attributes can be done in several ways, and another way of doing that is by object deconstruction. This is a way fetching a particular attribute from an object and assigning it to a variable with the same name as the attribute. For example, retrieving a first_name
attribute from a person
object and assigning it to a variable name first_name
can be done easily like this;
const person = {first_name: "Spankie", last_name: "Dee"};
const { first_name } = person;
console.log(first_name); // prints out "Spankie";
Renaming deconstructed variables
const person = {first_name: "Spankie", last_name: "Dee", address: {
street: "1 Main st.",
city: "Lagos",
country: "Nigeria"
}};
const { address: myaddress } = person;
console.log(myaddress); // prints out "{street: "1 Main st.", city: "Lagos", country: "Nigeria"}"
Deconstructing nested object attributes
const person = {first_name: "Spankie", last_name: "Dee", address: {
street: "1 Main st.",
city: "Lagos",
country: "Nigeria"
}};
const { address: { city, country } } = person;
console.log(city, country); // prints out "Lagos Nigeria";
console.log(address); // Error: address is not defined.
Parsing Objects and string to json
Using json.parse()
with template literals can be quite tricky...
const a = "A girl has no face";
const b = {stark: "Winter is coming."};
console.log(JSON.parse(a)); // this would throw an unexpected token error
console.log(JSON.parse(b)); // this would throw an unexpected token error
console.log(JSON.parse(`${a}`)); // this would throw an unexpected token error
console.log(JSON.parse(`"${a}"`)); // this would log "A girl has no face"
console.log(JSON.parse(`"${b}"`)); // this would log "[object Object]"
console.log(JSON.parse(`${b}`)); // this would throw an unexpected token error
What will work in any of these cases is:
console.log(JSON.parse(JSON.stringify(a)));
// or
console.log(JSON.parse(JSON.stringify(b)));
Both will run fine.
Setters and getters object accessors in javascript.
accessing object OOP style using getters and setters method are quite popular, javascript is not exempted from this as well, in fact it is quite interesting how it is done in javascript.
Setters and getters can be defined for an attribute using the get
and set
keywords in an object. Here is an example showing how it is done;
const vehicle = {
name: "Volvo",
year: "1999",
// using getters and setter to set/get the year.
get description() {
return `This ${this.name} was made in ${this.year}`;
},
set description(desc) {
var descs = desc.toString().split(' ');
this.name = descs[0];
this.year = descs[1];
}
}
vehicle.description = "Mercedes 2018";
console.log(vehicle.description); // prints out "Mercedes was made in 2018"
Assigning variable object attributes
Sometimes you may want to assign a value to an object attribute without knowing exactly the name of the attribute, but the name is the value of another variable. Here is an example explaining this;
const carname = "volkswagen";
const caryear = 1937;
let CarsFounded = {
"bmw": 1916,
"mercedes benz": 1926,
[carname]: caryear,
}
console.log(CarsFounded); // prints out: { bmw: 1916, 'mercedes benz': 1926, volkswagen: 1937 }
console.log(CarsFounded[carname]); // prints out: 1937
Thanks for reading this to the end :). You can check out some of my articles here
Top comments (14)
Good article! The "Assigning variable object attributes" especially cool! Thanks very much indeed.
Thanks a lot bruce!
Nice article!!!
Thanks Princewill...
Awesome article!!!
Thanks boss! I appreciate...
Cool reading. In the end I've understood how works deconstruction. And found for me get/set keywords for first time (Shame on me)) ). Thanx)
Thanks for the feedback Joe, I am glad I could be of help.
Wow! Awesome article by a Grade A software engineer. Very interesting indeed 🎯🎯🎯
Thanks a lot... You make me feel special!
Great post!!!
Some things to look out for.
Thanks.
Awesome!
Thanks boss!