I'm reading the JSlint Options Documentation to understand each of the available options, and have come across one that I don't quite understand, and can't find any useful information regarding it elsewhere.
sub - Tolerate inefficient subscripting
true if subscript notation may be used for expressions better expressed
in dot notation.
Can anyone shed more light as to what this means?
Thanks
JavaScript object members can be accessed using dot or subscript (square bracket) notation:
o.foo
o['foo']
...are the same thing. Square bracket notation is necessary for accessing members whose names can't be used in dot notation:
o['hello!']
or for accessing members from a dynamic name:
var name= issomething? 'foo' : 'bar';
o[name]
But for simple o['foo'] you don't need it. Normally the o.foo form is easier to read so it's considered better practice to use that. Some programmers coming from other languages may prefer to use square brackets for objects being using ‘like a mapping’ rather than ‘like an object’, but it's all the same to JS.
(JSlint is claiming that square bracket form is also “less efficient”, but if so then the difference is minuscule and not really worth bothering about.)
See here. Looks like subscript notation is doing:
document.forms['myformname'];
instead of
document.forms.myformname;
Related
As far as I know you can get map's value by key in two ways:
var myMap = {a: 1, b: 2}
var firstWay = myMap.a
var secondWay = myMap['a']
Which way is preferable? Is there a convection for this? Should I avoid first way and could be there any problems I may find in the future (e.g IE may not support it)? I understand that if I had some keys which require text escaping I won't be able to use .value on the map object, but what about simple cases?
My subjective point of view is that first way looks better.
The difference is that the dot notation requires the property name to be an identifierName. For example:
obj["a-b"]; // ok
obj.a-b; // fail! Parsed as `(obj.a) - b`
Moreover, before ECMAScript 5, the dot notation only allowed identifiers. That is, it excluded reservedWords. Then,
obj.class; // ok in ES5+
obj.class; // fail on old browsers
So in those cases you might prefer the bracket notation.
Otherwise it doesn't matter.
Technically the only difference is that you can use the [property] syntax even if you don't know the property name. E.g.:
property = 'a'
myMap[property] // results in 1
Otherwise just use the dot notation.
Also some people use a convention that you use the dot notation for your own data, but use brackets to access data retrieved from some external source.
jshint gives the error:
Line 362: document.forms['upload_form'].submit();
['upload_form'] is better written in dot notation.
for this line
document.forms['upload_form'].submit();
What dot notation...are they talking about accessing the object memmber via the '.' operator?
Yes; what other dot notation is there?
As you continue to ask jshint-related questions, bear in mind that some of the checks it performs are preferential: it's more important to remain consistent, and you can configure it to better-conform to your own particular style.
Also, bear in mind that for forms with array-notation names (tag[] or whatever), you'd need to use array notation anyway--I'd rather see the use of a single means of accessing form properties.
This is an example of dot notation
document.upload_form.submit()
Here is some reference.
http://www.quirksmode.org/js/forms.html
In addition I guess its best explained that all everything in JavaScript is Object Based.
Consider the following
var myobject = {value1 : 1, value2: 2};
I can access value1 and value2 like this
myobject.value1;
myobject["value1"];
When you have a multi-tiered object like a json object that say has 3 tiers
i = {'id':1{'name':'austin', 'lives':'college'{'name':'eckerd', 'major':'compsci'}}}
To reference the object is it better to reference it like so
for (x in i)
i[x]['lives']['name']
//or
i[x].lives.name
I think that gets my idea across. Pretty much use Associative arrays or the 'dot' method and why?
i[x].lives.name is equivalent to i[x]["lives"]["name"].
i[x][lives][name] means that you have variables called lives and name that you want to reference:
There's no real benefit to using one form over the other; imho it's clearest to use the dot notation unless you need the variable property names.
"Values can be retrieved from an object by wrapping a string expression in a [ ] suffix. If the string expression is a string literal, and if it is a legal JavaScript name and not a reserved word, then the . notation can be used instead. The . notation is preferred because it is more compact and reads better."
Crockford, D. (2008), JavaScript: The Good Parts. (pp. 21). Sebastopol, CA, U.S.A.: O'Reilly.
Is there any difference between
obj = {'foo': 'bar'}
and
obj = {foo: 'bar'}
I have noticed that you can't use - in the key when I don't use the quotes. But does it actually make a difference? If yes, which?
No, the quotes do not make a difference (unless, as you noted, you want to use a key that’s not a valid JavaScript identifier).
As a side note, the JSON data exchange format does require double quotes around identifiers (and does not allow single quotes).
From Unquoted property names / object keys in JavaScript, my write-up on the subject:
Quotes can only be omitted if the property name is a numeric literal or a valid identifier name.
[…]
Bracket notation can safely be used for all property names.
[…]
Dot notation can only be used when the property name is a valid identifier name.
Note that reserved words are allowed to be used as unquoted property names in ES5. However, for backwards compatibility with ES3, I’d suggest quoting them anyway.
I also made a tool that will tell you if any given property name can be used without quotes and/or with dot notation. Try it at mothereff.in/js-properties.
There is no difference here. Just a matter of style. One of the reasons for doing this is being able to use 'super' or 'class' as a key since those are reserved keywords.
Some people might be tempted to pass in a string with whitespace then call o['I can have whitespace'] But I would call that bad practice.
No, not to javascript. However, some JSON parsers will fail when the quotes around the keys are not present.
There are some situations where they are different. For example, if you are using jQuery, and you are making a list of parameters to pass when calling the jQuery $() command to create an element, quoted words are turned into parameters, and non-quoted words are turned into functions. For example, "size" will set the size attribute of the object, and size (no quotes), will call the size() function on the object. See jQuery(), near the bottom:
While the second argument is convenient, its flexibility can lead to unintended consequences (e.g. $( "<input>", {size: "4"} ) calling the .size() method instead of setting the size attribute). The previous code block could thus be written instead as:
Is there some way I can define String[int] to avoid using String.CharAt(int)?
No, there isn't a way to do this.
This is a common question from developers who are coming to JavaScript from another language, where operators can be defined or overridden for a certain type.
In C++, it's not entirely out of the question to overload operator* on MyType, ending up with a unique asterisk operator for operations involving objects of type MyType. The readability of this practice might still be called into question, but the language affords for it, nevertheless.
In JavaScript, this is simply not possible. You will not be able to define a method which allows you to index chars from a String using brackets.
#Lee Kowalkowski brings up a good point, namely that it is, in a way, possible to access characters using the brackets, because the brackets can be used to access members of a JavaScript Array. This would involve creating a new Array, using each of the characters of the string as its members, and then accessing the Array.
This is probably a confusing approach. Some implementations of JavaScript will provide access to a string via the brackets and some will not, so it's not standard practice. The object may be confused for a string, and as JavaScript is a loosely typed language, there is already a risk of misrepresenting a type. Defining an array solely for the purposes of using a different syntax from what the language already affords is only gong to promote this type of confusion. This gives rise to #Andrew Hedges's question: "Why fight the language?"..
There are useful patterns in JavaScript for legitimate function overloading and polymorphic inheritance. This isn't an example of either.
All semantics aside, the operators still haven't been overridden.
Side note: Developers who are accustomed to the conventions of strong type checking and classical inheritance are sometimes confused by JavaScript's C-family syntax. Under the hood, it is working in an unfamiliar way. It's best to write JavaScript in clean and unambiguous ways, in order to prevent confusion.
Please note: Before anybody else would like to vote my answer down, the question I answered was:
IE javascript string indexers
is there some way I can define string[int] to avoid using string.CharAt(int)?"
Nothing about specifically overriding brackets, or syntax, or best-practice, the question just asked for "some way". (And the only other answer said "No, there isn't.")
Well, there is actually, kind of:
var newArray = oldString.split('');
...now you can access newArray using bracket notation, because you've just converted it to an array.
Use String.charAt()
It's standard and works in all browsers.
In non-IE browsers you can use bracket notation to access characters like this:
"TEST"[1]; // = E
You could convert a string into an array of characters doing this:
var myString = "TEST";
var charArray = myString.split(''); // charArray[1] == E
These would be discouraged. There isn't any reason not to use the charAt() method, and there is no benefit to doing anything else.
This is not an answer, just a trick (strongly deprecated!). It shows, in particular, that in Javascript you can do whatever you want. It's just a matter of your fantasy.
You can use a fact that you can set any additional properties to String Object like to all others, so you can create String.0, String.1, ... properties:
String.prototype.toChars = function() {
for (var i=0; i<this.length; i++) {
this[i+""] = this.charAt(i);
}
};
Now you can access single characters using:
var str = "Hello World";
str.toChars();
var i = 1+"";
var c = str[i]; // "e"
Note that it's useful only for access. It should be another method defined for assigning string chars in such manner.
Also note that you must call .toChars() method every time you modify the sting.