What is this "[]" here doing? - javascript

Below is an extract from my textbook.
I have a question about the use of [] here in window.history[type](). I can tell that it's separating the object name(window) and the variable(type) so that they can be recognized as separate things but is there a name for this use of []? I performed a google search but nothing came up.
$(function() {
//omitted
['back', 'forward'].forEach(function(type) {
$('.' + type).click(function() {
window.history[type]();
});
});
});

This is property/method access using bracket notation.
In Javascript, you can access the properties of an object using the dot notation:
myObj.prop
Or the bracket notation:
myObj['prop']
When you dynamically construct the properties, however, you have no choice but to use bracket notation:
window.history['forward']()
is the same as
window.history.forward()
Here you are iterating on the forward and back properties, and the bracket notation is used to call the functions from their string names on window.history.
Here is the doc linked by #Teemu

Related

How to call function using bracket notation in node js

I know we can access data using dot notation and bracket notation but here if I access faker data using bracket notation I can't access that data. Is there any way to access data using bracket notation?
var faker = require("faker");
console.log(faker.name.findName()); // Output: any name.
console.log(faker["name.findName"]()); // Output: TypeError: faker.name.findName is not a function
The problem is that
faker["name.findName"]
would try to access a property called "name.findName" on the faker-object.
In order to access findName using bracket-notation, you need to change it to:
console.log(faker["name"]["findName"]());
You shouldn't use bracket notation to return functions.
console.log(faker["name"].findName())
or if you really just want to use brackets, try
let _findName = faker["name"]["findName"];
console.log(_findName());

Mapping a dot notation key in an object?

I have an object like this:
let object = {
seniority: 'director_level',
'address.long_form': 'Phoenix, AZ, United States'
}
when I go to print address.long_form like this I get an error.
console.log(object.address.long_form)
How do get the value for 'address.long_form'?
Since address.long_form is in string, you cannot use dot notation instead use this
console.log(object['address.long_form'])
It will work like this: object["address.long_form"], but just don't use dots in object indexes.
You can still extract it but you can't use the literal notation, you need to use the [] notation in order to get past the ambiguity.
i.e.
console.log(object['address.long_form'])
Of course better would to just avoid keys in that form, but depends on your data.

Passing an Object as an Argument in Javascript - But not simply an Argument but an argument built from variables

I am passing an object to a function. Simplified example below:
countyInfo(sales.NY2008);
The object is:
{countyName:"Albany",percentage:0.864789889,percentageComparison:40.18903649,sales:1222},
{countyName:"Allegany",percentage:0.789529462,percentageComparison:27.98874729,sales:149},
{countyName:"Broome",percentage:1.009475302,percentageComparison:63.64364553,sales:880},
{countyName:"Cattaraugus",percentage:0.874885092,percentageComparison:41.82554597,sales:276},
{countyName:"Cayuga",percentage:0.801267677,percentageComparison:29.89160156,sales:268},
{countyName:"Chautauqua",percentage:0.830185925,percentageComparison:34.5794701,sales:455},
{countyName:"Chemung",percentage:0.744919757,percentageComparison:20.75717391,sales:272},
{countyName:"Chenango",percentage:1.191003494,percentageComparison:93.07074993,sales:242},
{countyName:"Clinton",percentage:0.767315265,percentageComparison:24.38765663,sales:265},
{countyName:"Columbia",percentage:0.83461736,percentageComparison:35.29783949,sales:260},
{countyName:"Cortland",percentage:1.144086442,percentageComparison:85.46513794,sales:234},
It works beautifully.
Now I would like to compose this parameter from variables.
var getLocation = "NY";
var getYear = "2008";
var getParameter= getLocation + getYear;
countyInfo(sales.getParameter)
It doesn't work as I'm passing a string. But how can this be done?
Just change your code to use bracket notation to access object property instead of dot notation
var getLocation = "NY";
var getYear = "2008";
var getParameter= getLocation + getYear;
countyInfo(sales[getParameter]);
Dot notation:
Property identifies can only be alphanumeric (and _ and $)
Propertyidentifiers cannot start with a number.
Property identifiers cannot contain variables.
OK — obj.prop_1, obj.prop$
Not OK — obj.1prop, obj.prop name
Bracket notation:
Property identifiers have to be a String or a variable that
references a String.
It is okay to use variables, spaces, and Strings
that start with numbers
OK — obj["1prop"], obj["prop name"]
For Detailed explanation refer this --
https://codeburst.io/javascript-quickie-dot-notation-vs-bracket-notation-333641c0f781
Since sales seems to be an object, you can use index notation to access a member.
That is, sales.NY2008 is equivalent to sales["NY2008"].
So, simply do
countyInfo(sales[getLocation + getYear]);

Bad character in json response angular 2

I've retrieved a JSON response from an external API and one of the variable names begins with a # character, so the JSON variable looks like this #text. Unfortunately angular doesn't know how to handle this variable, is there any way delete the # so that the data assigned to the identifier is usable.
In order to reference a property that does not follow the rules for a properly formatted identifier, you must use bracket notation instead of dot notation for the property accessor:
var object = JSON.parse('{"#text":"https://lastfm-im...png","size":"extralarge"}')
console.log(object['#text'])
you cam modifide the response - loop throw it wite map- and chenge the object key -see here:
JavaScript: Object Rename Key
You can use square bracket notation instead of dot notation. like (Object mutation is highly not recommended)
//to access it u can use square bracket notation like k["objectname"]
let k = {"#test":"some data"}
alert("data is "+k["#test"])

Point the right key with a variable of a json array

I get the following json array from an api:
response = {"base":"USD","date":"2015-11-05","rates":
{"AUD":1.3997,"BGN":1.7971,"BRL":3.8008}}
I get that from the following http query:
$http.get(url).success(function(response){
let assume that
quote = "AUD";
How can I point to the AUD value of rates in response (i.e. rate = 1.3997)?
$scope.rate = response.rates.quote;
does not work...
this is called accessing property value of an object this is how we do it
var quote = 'AUD'
var response = {"base":"USD","date":"2015-11-05","rates":
{"AUD":1.3997,"BGN":1.7971,"BRL":3.8008}}
object = JSON.parse(JSON.stringify(response))
document.write(object.rates[quote])
If you use
rates.quote
This means that quote is a property of rates object which is not;
The value of quote is the property of rates
Try like this
$scope.rate = response.rates[quote];
This is one of those times when you have to use the square bracket notation instead of dot notation even though they are usually interchangeable. You can only use dot notation when you know the real name of the property. When you are using a variable as a placeholder you have to use square brackets.
Dot notaion has its limit, use brackets as others already suggested.
The dot notation is:
An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

Categories