We all know Javascript objects. An object is nothing more than a container holding key-value pairs.
However, there’s a lot more to Javascript objects. Let’s go over some key concepts.
1. Defining properties with expressions
JS objects can be defined with expressions as property values. These expressions are immediately computed and stored as values.
Example:
let obj = { num: (1 + 2) * 3 }
In this case, the value of num is stored as 9 after the expression is evaluated.
let obj = { num: 9 }
But what if you want to define a property with a lazily computed expression?
The only way to achieve that is by wrapping the expression in a function.
function calc() { return (1 + 2) * 3; } let obj = { num: calc }
Now, obj.num holds a reference to the function calc. The value will only be computed by calling obj.num() when necessary.
2. Types of property names
Property names can be of any type but automatically converted to strings.
let obj = { "12": "this is a string name", // string, both obj[12] and obj["12"] will work 14: "this is an integer name", // coerced to a string, both obj[14] and obj["14"] will work true: "this is a boolean prop name", // coerced to a string, both obj[true] and obj["true"] will work [newObj]: "this is an obj prop name" // coerced to a string, obj[newObj] will not work but obj["newObj"]
3. Concise object methods
Starting from ES6, Javascript allows concise object method definitions without needing the “function” keyword.
let obj = { hello(){ console.log("Hello"); } }
In this example, the object has a method called “hello” which can be called by obj.hello().
We will see more in the upcoming episodes.
12 Comments
I loved your blog.Thanks Again. Want more.
I have read so many posts about the blogger lovers except thispost is genuinely a nice post, keep it up.
Hello there, just became aware of your blog through Google, and found that it is truly informative. I am going to watch out for brussels. I’ll be grateful if you continue this in future. Many people will be benefited from your writing. Cheers!
I really liked your blog article.Really looking forward to read more. Keep writing.
I sing in a choir principio ativo capoten Mediator Staffan de Mistura had been working since October on a local truce in the northern city of Aleppo and announced on Feb
disulfiram purchase
Enjoyed every bit of your blog post.Much thanks again. Great.
I really enjoy the blog post.Much thanks again. Cool.
I truly appreciate this blog article.Really looking forward to read more.
Thank you ever so for you blog. Keep writing.
I am so grateful for your post.Really looking forward to read more. Will read on…
I really like and appreciate your article post.Really looking forward to read more. Will read on…