Wednesday, March 7, 2018

Objects with Square Brackets

Consider the below object,

let test = {
  name: "Raj",
  age: 19,
}

Here , you are going to add another one property like state and district property. If you try directly based on the last post, it will throw an error. So what the error, check below.

// syntax error will occur
test.state district = TamilNadu Chennai


To solve that, you should use square brackets.

// setting value
test["state District"] = "TamilNadu Chennai";

// getting value
console.log(test["state District"]); // 

// deleting value
delete test["state District"];

From the above, We have not used dot operator and used [] .


Another important, here you can use any reserved words like "for", "switch", "let" etc., See the below to confirm how its working.

let obj = {
  for: 3,
  switch: 2,
  return: 5
}

console.log(obj.for + obj.switch + obj.return );  // Output 10






No comments:

Post a Comment