Limpuls Limpuls - 1 year ago 60
Javascript Question

How does bracket notation works when returning object's value

I have an object:

var contacts = [
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["Javascript", "Gaming", "Foxes"]

Now I have for loop and after I'm returning property's value by writing:

function lookUpProfile(firstName, prop){

for (i = 0; i < contacts.length; i++) {

if (contacts[i].firstName === firstName) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];

contacts[i][prop] is returning given property value, like "number": "0487345643", but what I don't understand is, why it's returning value of property if we say return contacts[i][prop] when prop means property and not value. What should we say then to get a property and not its value? How this all bracket notation thing works? It was always confusing for me.

Answer Source

The bracket notation is useful when you need to access an object's value but you don't know exactly which property you're going to be using.

For example:

var obj = {
    a: 'test',
    b: 'home'
//bracket notation
//define a string prop
var prop = 'a';

//then later we can use prop to access a value
console.log(obj[prop]); //prints 'test'

//its exactly the same as doing this:
console.log(obj['a']); //prints 'test'

//dot notation works when you know the property name
console.log(obj.b); //prints 'home'

In your function, a user can specify a property name prop. Below I am passing 'number' and 'lastName' to the function.

console.log(lookUpProfile('Sherlock', 'number')); //prints '0487345643'
console.log(lookUpProfile('Akira', 'lastName')); //prints 'Laine'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download