JavaScript: bracket notation to retrieve property values - javascript

I'm working on codecademy.com JavaScript tutorial. This lesson on objects. I have a feeling this problem is fairly simple, but I'm not getting the answer. If I understood the instructions better, the answer might be clearer to me.
I set the value to the variable aProperty, and now I'm supposed to follow the instructions in the final comment, i.e. print the value of the first property using the variable "aProperty". I've included the "intro to the lesson" below to help explain what the lesson is trying to teach.
The Question: Assuming I set the variable aProperty correctly, how would you retrieve the first value of the James object using the variable aProperty.
var james = {
job: "programmer",
married: false
};
// set to the first property name of "james"
var aProperty = james.job;
// print the value of the first property of "james"
// using the variable "aProperty"
Intro to lesson
And finally, let's go over retrieving property values. Throughout this section, we've been using dot notation to get the value of an object's property:
someObj.propName
However, remember that we can also use bracket notation:
someObj["propName"]
An advantage of bracket notation is that we are not restricted to just using strings in the brackets. We can also use variables whose values are property names:
var someObj = {propName: someValue}; var myProperty = "propName"; someObj[myProperty]
The last line is exactly the same as using someObj["propName"].
Take advantage of the ability to use variables with bracket notation.
In line 7, set aProperty to a string of the first property in james (ie. the job property).
Then print james's job using bracket notation and aProperty.

var aProperty = 'job';
console.log(james[aProperty]);

Try something like this:
var james = {
job: "programmer",
married: false
};
var aProperty = "job";
console.log( james[aProperty] );

Related

JavaScript Conceptual Issue with a code. Please give an explanation for the output i am getting

I am having difficulty in understanding the following code, i have put a comment where i do not understand the concept, what exactly is going on
var ob = {};
var ob2 = ['name'];
for(var op of ob2)
{
ob[op]='at'; // here i dont understand what is happening, why here is an array type brackets
}
console.log(ob);
OUTPUT IS
name:'at'
That is just the syntax for accessing or assigning properties of an object dynamically in javascript.
You can think of it as though you are doing: ob.name = 'at'.
There are two ways to access object properties in JavaScript
var person = {
name: 'Jane'
}
person.name
// or
person['name']
// both return jane
in your case, that iterates through members of the array called ob2
first and only element of that array is a string name and it's given to that object as a prop, which becomes like following
ob['name'] = 'at';
// or
ob.name = 'at';
When to use brackets([]) over dot(.)
If you don't know the prop name at runtime you need to go with brackets, if you do know it you can choose either dot notation or brackets
Basically, it's accessing a property of the object ob. In this case, is accessing and creating new properties.
The loop is getting each index value, and for each assign/create a new property using that index value.
That approach is a dynamically way of creating property-names in an object.
ob['name'] = 'at';
ob.name = 'at'; // Just to illustrate
Read a little the docs here -> JavaScript object basics - Learn web development | MDN

JS - Difference between period and [] while accessing a JSON object [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 4 years ago.
What is the difference between accessing a JSON object using period (.) and [] notation in Javascript. For instance,
var person = {
"firstName": "Foo",
"lastName":"Bar"
}
I'm sure accessing the "firstName" and the "lastName" variables give me the same output type (string),i.e.
console.log(typeof person.firstName); // returns string
console.log(typeof person.lastName); // returns string
Also, accessing it both the ways, using . or [] will give me the same result:
console.log(person.firstName); // returns Foo
console.log(person['firstName']); // returns Foo
I'm trying to understand when to use which notation and when not to and the actual difference between them. I read somewhere that we can't use the dot notation if the data is complicated, I'm not sure what it means, tested out a couple of sample input data:
"firstName": " Foo Bar "
"firstName": "####$% Foo Bar!!!"
Interestingly, both gives me the same result, can someone please explain me what's the actual difference between these two notations and when to access which?
They are both valid ways of accessing Object Values.
Welcome to Stackoverflow!
The main difference between the two is that using bracket notation allows you to define and access properties with spaces in them -- something one cannot do with dot notation.
var foo = {
"I AM BAR": 1
}
If you wanted to access the single property "I AM BAR" on foo, with bracket notation, it would look like: foo["I AM BAR"]. This is not possible with dot notation.
There are not difference.
The [] approach is useful when you need find a key with a variable.
Like:
const theKey = 'test';
theArray[theKey]; // this work
theArray.theKey; // this dont work
Using dot notation you must provide the exact propertyName but you are able to work with the name when using [].
var person = {
"firstName": "Foo",
"lastName":"Bar"
}
Using . you can only access by
console.log(person.firstName); // returns Foo
Using [] you could access value with variable
let couldChange = 'Name';
console.log(person['first'+couldChange]); // returns foo
console.log(person['last'+couldChange]); // returns bar
Most of the time you will use dot notation. Unless you need the property on the object you need to access to be dynamic. This is because the value you pass into the brackets could be a variable as long it resolves to a string. Check out this link for more info:
https://codeburst.io/javascript-quickie-dot-notation-vs-bracket-notation-333641c0f781
Most of the time, there's no difference, see Property accessors (MDN), but you cannot use dot notation when the property name is not a valid identifier name, e.g. when it's representation is not a string, or when you need to use a variable to name the property.
obj[1] // is valid
obj["1"] // is the same
obj.1 // is NOT valid
const propertyName = 1;
obj[propertyName] // the same as obj[1]
obj.propertyName // not same
Using brackets can allow you to use a variable value to access object properties whereas dot notation won't. For example:
var propName = 'age';
var o = {
name: 'Tom',
age: '29',
about: 'He\'s a cool guy!'
};
console.log(o.propName); // <-- Will be undefined
console.log(o[propName]); // <-- Bingo

How to add an empty array to object?

I'm having trouble adding my empty array into my object via the bracket notation method. I know how to get my empty array into the object via dot notation, but I just don't understand why the bracket notation isn't working for me.
Update: I understand my problem now; the context switch between dot notation & bracket notation blinded me & I completely failed to recall that in my 3rd block - animal[noises] (forgot the "") was trying to access the property value of the property noises, which I hadn't created yet in my object
Creating & adding properties to my object
var animal = {};
animal.username = "Peggy";
animal["tagline"] = "Hello";
Which will then create this:
animal {
tagline: "Hello",
username: "Peggy"
}
Why won't the following work when I'm trying to add it into my object?
var noises = [];
animal[noises];
I'm getting this in my console (same as above):
animal {
tagline: "Hello",
username: "Peggy"
}
I was able to get my result this way:
animal.noises = [];
Which outputs this into my console:
animal {
noises: [],
tagline: "Hello",
username: "Peggy"
}
But that still leaves me with the question: why doesn't this work via bracket notation?
Use
animal.noises = noises;
or
animal['noises'] = noises;
As when you are using animal[noises]; it means when you are trying to read data from the object.
For animal[noises],
animal is the object
and noises is the key/property of the object animal
And an array cannot be a key. If you want to put noises array in animal object you can do it as follows,
animal['noises'] = noises;
In your case you have to try
animal['noises']=noises
Array [] notation is used to get property of an object that requires a quote around it. Array notations are commonly used to get identifiers of objects having special characters included.say,
var animal={
"#tiger":'carnivore' // you can't have #tiger without quote as identifier
}
console.log(animal.#tiger) // it will give ERROR
console.log(animal['#tiger']) // it will print out 'carnivore'
this link has good explanation on array and dot notation .

Various problems in JSHint

In JSHint I get the follwing message about my array declaration:
jesuschrist["eng_male"] = [//tons of arrays here];
['baby_jesus'] is better written in dot notation.
Does it mean I should write it as baby.jesus?
Also, I gives me a problem when declaring the object:
jesuschrist = new Object();
JSHint says this:
Use the object literal notation {}.
It's suggesting that your code change to:
jesuschrist = {};
jesuschrist.eng_male = [//tons of arrays here];
jShint tell you to use do notation because you are trying to get property with a string literal(which is static). Because property identifier wont change.
jesuschrist.eng_male //this wont change
You can access property of an object using [] but then pass property name as variable(which can be dynamic)
var prop = "eng_male";
jesuschrist[prop]; //this might be changed, depends on the prop value.
Both given examples are ok with JsHint.

The preferred way to access and create an object's properties?

In Javascript, you can create an object with a property name this way:
var person = { name: "Tucker" };
But also that way:
var person = { "name": "Tucker" };
Are these two equivalent? Which one is preferred?
Same goes with accessing a property:
person["name"] = "Dale";
vs.
person[name] = "Dale";
In Eloquent JavaScript, the author says that The part between the brackets can be any expression. It is converted to a string to determine the property name it refers to..
So, I guess directly putting a string between the brackets would be considered best practice.
Last but not least, properties can be accesses by using the dot notation:
person.name = "Dale";
if the property is a valid variable name. Does it actually makes sense to use this notation over the seemingly more flexible bracket notation?
These are the same, the only difference is that if your key is reserved keyword, you need the quotes:
var person = { name: "Tucker" };
var person = { "name": "Tucker" };
var person = { "for": "Tucker" }; //Need quotes here
When accessing, the same rules apply
person["name"] = "Dale"; //Sets the person object's name attribute to "Dale", the brackets are needed for variables or expressions.
person.name = "Dale"; //Same operation, different syntax
person[name] = "Dale"; //Sets the attribute equivalent to the value of the variable name, not necessarily "name"
Does it actually makes sense to use this notation over the seemingly more flexible bracket notation?
It is entirely up to you, or whoever decides your project's coding standards. The dot notation is simpler and reminiscent of Java/C/C++ (if you're into that sort of thing) and brackets, as you noted, are more flexible.
There's no 'best way', and it really depends on what you're doing.
var person = { name: "Tucker" };
Is fine, but if 'name' is actually 'name with a space' then you need:
var person = { "name with a space": "Tucker" };
For accessing properties, unless you're in a for ... in loop I would recommend dot notation:
person.name
Of course you can't do:
person."name with a space"
So do:
person["name with a space"]

Categories

Resources