Dot Notaition in Javascript Object : We use dot notation in Javascript Object to access object properties
Bracket Notation in Javascript : We use Bracket Notation when we use expression to get value.
// Javascript Object...
const anilDetails = {
firstName: 'Anil',
lastName: 'Singh',
age: 31,
job: 'programmer',
friends: ['ram', 'shyam', 'mohan', 'sohan'],
}
// Accessing properties using Dot Notation..
console.log(anilDetails.firstName);
// Accessing Property using Bracket Notations..
console.log(anilDetails['firstName']);
// Adding Property to the object
anilDetails.location = 'India';
anilDetails['twitter'] = '@anil';
console.log(anilDetails);
In bracket notation we can also put expression.
// Using expression in bracket notation
const nameKey = 'Name';
console.log(anilDetails['first' + nameKey]);
console.log(anilDetails['last' + nameKey]);
const userInput = prompt(`Enter What You want to know....`);
// Using dot notation to display value but not work.
console.log(anilDetails.userInput);
// Using Bracket Notation to get value its works.
console.log(anilDetails[userInput]);
// Using logic for display....
const userInput = prompt(`Enter What You want to know....`);
if (anilDetails[userInput]); {
console.log(anilDetails[userInput]);
} else {
console.log(`Wrong Request`);
}
// Anil has three friends and his best friend called sohan
const demoLine = `${anilDetails.firstName} has ${anilDetails.friends.length} friends and his best friend called ${anilDetails.friends[3]}`;
console.log(demoLine);
0 comments
Post a Comment