I'm going through a javascript file having some functions like this:
'form_validation': function(form,error_bin){
for(var field in form){
if(field.substr(0,1) != "$"){
this.validation_messages(field,form,error_bin);
}
}
}
I want to understand what is the difference between defining a function with quotes (like mentioned above) and without quotes
EDIT: I've also observed that the functions having name in quotes are being called from a different file (like: ServiceName.functionName()), while without quotes are being called from the same file.
This is an Angularjs code
The two are equivalent syntax for object literals. The quotes allow you to use keys that aren't legal variable names, like so:
var foo ={ 'variable name':2}
There's nothing significant about the fact that the value assigned to the object key is a function. In JavaScript objects are (almost) just key value pairs of strings and arbitrary objects.
JavaScript has something called Objects these are link associative array's in other languages. Object have item. Each item has a key(name) and a value. Key's follow regular JavaScript variable names. You can check valid variable names here. Valid variable names do not need to be in quotes. Sometimes, to include special characters, the name is a string.
my_value <- Valid
my-value <- Invalid (needs to be in string)
my value <- Invalid (needs to be in string)
both are same for javascript objects. but you should avoid using quotes as a coding standard.
Related
Example code: https://playcode.io/757707/
Take a look at what it is logging to the console.
I am not sure if there is a way to compute property values, that have dots in the names, as valid JSON.
that third field in the objects that are printed is always:
{
dot.notation: "value"
}
In order for it to be valid JSON you need quotes around the property name if you would like to have a dot "." in the property name.
e.g. Valid JSON would look like this:
{
"dot.notation": "value"
}
It seems it's bad practice to use a dot in a property name... but there should be a way to set that property as a string explicitly so the JSON isn't invalid if I compute the property name. Because of this parsing the JSON string of that JSON Object just doesn't work.
Does anyone know of a workaround to explicitly set the property name in quotes?
I would love to just follow best practices and not use a dot in the property name but this is required for some requests in Looker. I was working for a client in Looker so I needed a workaround.
Strictly speaking of JSON format, ALL field names must be in quotes. This is required for interoperability, like sending data to a REST API, etc. Within these quotes, virtually any string is allowed per the JSON spec.
In JavaScript, this is looser, JavaScript objects don't need quotes around property names when these names are simple (a-z, A-Z, 0-9, _, $), otherwise, quotes are needed to disambiguate for language parsing reasons.
IF you want a property to be set from a string value, just do this:
{
[myStringVariable] : true
}
Without the need to fumble with quotes, this allows you to set a property with virtually any string. So you can set some constants in your code defining these field names, and then just do this in a consistent manner:
const FIELD1 = "my& crazy**field-name"; // Or from some schema definition.
// etc. other field consts.
let myObject = {
[FIELD1] : true
// .. etc.
}
Note also, that within this [ ] notation, you can put any valid JavaScript expression that can evaluate to a string, such as [myFields.field1Name] and even things like [(someCondition ? "unknown" : "myField")]
Finally, none of this is any kind of "standard", just mechanisms you may want to consider for cases where your field names are not controlled by you -- because when they are controlled by you, you should keep them simple for clarity.
I am using this script to make a style object of all the inherited, etc. styles.
var style = css($(this));
alert (style.width);
alert (style.text-align);
With the following, the first alert will work fine, but the second one doesn't... it's interpreting the - as a minus I assume. The debugger says 'uncaught reference error'. I can't put quotes around it, though, because it isn't a string. So how do I use this object property?
Look at the comments. You will see that for CSS properties, the key notation is not compatible with a number of properties. Using the camel case key notation therefore is the current way:
obj.style-attr // would become
obj["styleAttr"]
Use key notation rather than dot
style["text-align"]
All arrays in JavaScript are objects and all objects are just associative arrays. This means you can refer to a place in an object just as you would refer to a key in an array.
arr[0]
or the object
obj["method"] == obj.method
A couple things to remember when accessing properties this way:
they are evaluated so use strings unless you are doing something with a counter or using dynamic method names.
This means obj[method] would give you an undefined error while obj["method"] would not
You must use this notation if you are using characters that are not allowed in JavaScript variables.
This regex pretty much sums it up:
[a-zA-Z_$][0-9a-zA-Z_$]*
The answer to the original question is: place the property name in quotes and use array style indexing:
obj['property-with-hyphens'];
Several have pointed out that the property you are interested in is a CSS property. CSS properties that have hyphens are automatically converted to camel casing. In that case you must use the camel cased name like:
style.textAlign;
However this solution only works for CSS properties. For example,
obj['a-b'] = 2;
alert(obj.aB); // undefined
alert(obj['a-b']); // 2
CSS properties with a - are represented in camelCase in JavaScript objects. That would be:
alert( style.textAlign );
You could also use a bracket notation to use the string:
alert( style['text-align'] );
Property names may only contain characters, numbers, the well known $ sign and the _ (thanks to pimvdb).
Use brackets:
var notTheFlippingStyleObject = {
'a-b': 1
};
console.log(notTheFlippingStyleObject["a-b"] === 1); // true
More information on objects: MDN
NOTE: If you are accessing the style object, CSSStyleDeclaration, you must use camelCase to access it from JavaScript. More information is here.
alert(style.textAlign)
or
alert(style["textAlign"]);
To directly answer the question: style['text-align'] is how you would reference a property with a hyphen in it. But style.textAlign (or style['textAlign']) is what should be used in this case.
Hyphenated style properties are referenced via camelCase in JavaScript, so use style.textAlign.
To solve your problem: The CSS properties with hyphens in them are represented by JavaScript properties in camelCase to avoid this problem. You want: style.textAlign.
To answer the question: Use square bracket notation: obj.prop is the same as obj["prop"] so you can access property names using strings and use characters that are forbidden in identifiers.
I think in the case of CSS styles they get changed to camelCase in JavaScript, so test-align becomes textAlign.
In the general case, where you want to access a property that contains non-standard characters, you use array-style: ['text-align']
The object property names are not one-to-one matches for the CSS names.
At first, I wondered why the solution didn't work on my end:
api['data-sitekey'] // Returns undefined
...later on I figured out that accessing data attributes was different:
It should be like this:
var api = document.getElementById("some-api");
api.dataset.sitekey
Either if you saying '-' takes as a subtract expression.
eg. Json = {'Me-m':123}
But have you idea why we need to use [] for access this hyphen variable.
Such like that Json['Me-m'].
Writting
Json.Me-m
will evaluate to
Json.Me - m
It will try to access Me property from Json object and subtract m variable, which probably will be undefined.
Because Me-m is not a valid property name to be used as property hence you are forced to use as Maps read this or check here for a valid propert name
That's because '-' has a meaning in javaScript, so if you write Json.Me-m JavaScript interprets: 'Substract the value of the variable m to the value of the attribute Me of the object ``Json`'.
In javascript, you can access any member of an object by name, using [], and inside a string, javascript is not going to try to evaluate anything, so when you write Json[Me-m], it's interpreted as: 'Retrieve the value of the member named Me-m of the object Json'
The reason is simple: in Javascript each object it's an indexed key/value dictionary, accessing to the variable with the "." it's a shortcut, and obviously the fact of the "dictionary object" it's a performance issue, but despite of this matter, javascript it's really fast in comparison with other scripting language.
Answering your question, by desing an index can be a string containing the "-" char, but not a property... so if you have a property with that char, it won't be accessible with the "." notation.
Because you are passing a special character in key part of obj and for accessing that value of obj we need to use [].
eg. json['Me-m']
My response object has a field called "50", so right now I'm trying to access and save that data doing something like this:
var thing = $scope.data.array[0].50;
However I'm getting an error on the console when I simply reload the page with the function not even running. When I get rid of the 50, everything is fine. There is indeed a field called "50" inside the $scope.data.array[0] and I do not have access to change the response. Is there something wrong with this because the field is called "50" and maybe JS is interrupting that as a number instead??
Also when I changed "50" to something random like "af", then I get no errors on refresh.
this doesn't work
var thing = $scope.data.array[0].50;
this works
var thing = $scope.data.array[0].af;
The following should work if your first element of the array has a property called "50".
var thing = $scope.data.array[0]["50"];
Property accessors provide access to an object's properties by using the dot notation or the bracket notation.
Syntax
object.property
object["property"]
JavaScript objects are also associative arrays (hashes). Using these you can associate a key string with a value string as shown in the example above.
The reason as to why you don't get an error when accessing $scope.data.array[0].af; is because "af" is valid identifier for a property. Dot notation only works with property names that are valid identifiers. An identifier must start with a letter, $, _ or unicode escape sequence.
For all other property names, you must use bracket notation.
How does one add a variable string in this javascript statement?
where name may correspond to any valid string , say WebkitTransform or Moztransform,etc
document.getElementById('test').style.VARIABLE_NAME = 'rotate(15deg)';
My code doesn't seem to work when i set the VARIABLE_NAME to WebkitTransform, but it works fine if I use WebkitTransform directly, as in without naming it via a variable.
Thanks in advance :)
There are two ways to access members of a Javascript object.
Dot notation, which uses an identifier to access the member:
obj.member;
Bracket notation, which uses a string to access the member:
obj['member']
The latter uses a string to locate the member and you can just as easily use any expression. The value of the expression will be converted to a string so these are equivalent:
obj[{}]
obj['[object Object]']
If your expression is already a string it will be used as is, and in your case your variable holds a string so you can just do:
document.getElementById('test').style[VARIABLE_NAME] = 'rotate(15deg)';
There are 2 ways of accessing values in javascript objects. The first one is by using the dot operator(e.g. object.memberName). The second one is by using the square bracket notation(e.g. object['memberName']).