Hidden power of javascript object

Object is awesome data structure in JavaScript. Why it’s awesome? Just because of it’s store data as key and value pair and every key is unique so we can store unique information inside objects. So one question arises in our mind how to use this, so the syntax for object is –

var variabl_name = {
    'key_1': value

var obj = {
    'name': 'xyz',
    'age': 23

How to access property
Here we have to way to access property of object

obj.propertyname // using dot
obj[propertyname] // using bracket 

Like -

obj.name // "xyz"
obj["name"] //name

How to delete property

To delete a property we can use delete keyword

delete obj.name;

Object tricks –

Lot of time we want to access or set dynamic key and we don’t know about that key so how we can access that property?

let key = prompt("what information you want to know about user?", "name");
console.log(obj[key]); // xyz

Instead of name:name we can just write name, like this:

function dummyObj(name, age) {
  return {
    name: name,
    age: age
    // ...other properties

var obj = makeUser("xyz", 30);
console.log(obj.name); // xyz

Power of in keyword

Supposed that you have a condition and you want to check key is the part of object like this example –

var obj = {
val: undefined

console.log(obj.test); // undefined
console.log("val" in obj); // true

Access all key with for in loop

We have for keyword to access to all key but with the help of in it become more easy to use –

for (var o in obj) {
     console.log(key, o[key]); 
     //name xyz
     // age 23

You May Also Like

About the Author: admin