This question already has answers here:
Why would a JavaScript variable start with a dollar sign? [duplicate]
(16 answers)
Closed 9 years ago.
I found an JavaScript file in a website using a variable like this:
var $variable
What kind is it?
Thanks, DGM
$ is a regular symbol like any other legal one in JS and can be used as or part of a variable as well:
var $ = {};
It's also the identifier for the jQuery object. So that's why you'll normally see variables named that way that represent jQuery objects:
var $variable = $('#element');
There's also Underscore.js that uses the underscore symbol _ as its root object.
It is a completely normal variable, starting with the dollar sign - which has no special meaning in JavaScript. It is a valid identifier just as like the underscore.
Sometimes, variable names prefixed with $ indicate that they contain an object wrapper created by one of the libraries that use $ as a constructor (for example jQuery); in contrast to a "plain value".
Javascript identifiers must start with a letter, an underscore or a dollar sign. So it is just a variable.
The intended use of the $ sign was for code generators, but some libraries use it for their own purposes.
It is perfectly valid to use $ in javascript variable names. Personally, I try to avoid this as it can be confused with jquery objects or php variables which may have crept into the javascript by mistake.
Related
This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
How do I reference a JavaScript object property with a hyphen in it?
(11 answers)
Closed 3 months ago.
I am unable to retrieve a value from a json object when the string has a dash character:
{
"profile-id":1234, "user_id":6789
}
If I try to reference the parsed jsonObj.profile-id it returns ReferenceError: "id" is not defined but jsonObj.user_id will return 6789
I don't have a way to modify the values being returned by the external api call and trying to parse the returned string in order to remove dashes will ruin urls, etc., that are passed as well. Help?
jsonObj.profile-id is a subtraction expression (i.e. jsonObj.profile - id).
To access a key that contains characters that cannot appear in an identifier, use brackets:
jsonObj["profile-id"]
In addition to this answer, note that in Node.js if you access JSON with the array syntax [] all nested JSON keys should follow that syntax
This is the wrong way
json.first.second.third['comment']
and will will give you the 'undefined' error.
This is the correct way
json['first']['second']['third']['comment']
For ansible, and using hyphen, this worked for me:
- name: free-ud-ssd-space-in-percent
debug:
var: clusterInfo.json.content["free-ud-ssd-space-in-percent"]
For anyone trying to apply the accepted solution to HomeAssistant value templates, you must use single quotes if you are nesting in doubles:
value_template: "{{ value_json['internet-computer'].usd }}"
If you are in Linux, try using the following template to print JSON value which contains dashes '-'
jq '.["value-with-dash"]'
It worked for me.
This question already has answers here:
What do the brackets around the arguments mean when reading documentation for a method? [duplicate]
(3 answers)
Closed 4 years ago.
I am using criso validator.js, of user Input,
but it Eslint is showing error in syntax on this lines
if (!Validator.isAlphanumeric([(data.password,'en-US')])) {
console.log(" Not an alphanumeric");
}
how to properly check user's entered password is Alphanumeric,
I know we can do it using regex but I wanted to do it by using their provided syntax as isAlphanumeric(str [, locale]).
here is their documentation screenshot of code.
The square brackets in the isAlphanumeric(str [, locale]) notation are not related to JavaScript Array literals. Instead, they denote that when calling isAlphanumeric, the first argument str (in your case, data.password) is required, and the second argument locale is optional.
In your case, you do want to pass in a locale. Here is how that would look:
if (!Validator.isAlphanumeric(data.password, 'en-US')) {
console.log("Not an alphanumeric");
}
In technical documentation, square brackets ([]) generally denote that an argument is optional. Tecnhnically this is just a convention (and probably comes from Unix CLI Usage Messages), but in my experience is so widely used that always interpreting square brackets as denoting an optional argument is usually a safe assumption to make.
This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
How do I reference a JavaScript object property with a hyphen in it?
(11 answers)
Closed 3 months ago.
I am unable to retrieve a value from a json object when the string has a dash character:
{
"profile-id":1234, "user_id":6789
}
If I try to reference the parsed jsonObj.profile-id it returns ReferenceError: "id" is not defined but jsonObj.user_id will return 6789
I don't have a way to modify the values being returned by the external api call and trying to parse the returned string in order to remove dashes will ruin urls, etc., that are passed as well. Help?
jsonObj.profile-id is a subtraction expression (i.e. jsonObj.profile - id).
To access a key that contains characters that cannot appear in an identifier, use brackets:
jsonObj["profile-id"]
In addition to this answer, note that in Node.js if you access JSON with the array syntax [] all nested JSON keys should follow that syntax
This is the wrong way
json.first.second.third['comment']
and will will give you the 'undefined' error.
This is the correct way
json['first']['second']['third']['comment']
For ansible, and using hyphen, this worked for me:
- name: free-ud-ssd-space-in-percent
debug:
var: clusterInfo.json.content["free-ud-ssd-space-in-percent"]
For anyone trying to apply the accepted solution to HomeAssistant value templates, you must use single quotes if you are nesting in doubles:
value_template: "{{ value_json['internet-computer'].usd }}"
If you are in Linux, try using the following template to print JSON value which contains dashes '-'
jq '.["value-with-dash"]'
It worked for me.
This question already has answers here:
JavaScript braces on new line or not? [closed]
(9 answers)
Closed 5 years ago.
I was used in this type of convention of indentation and curly brackets placement in college.
function code()
{
if(code)
{
code
}
}
but online tutorials in javascript tells me to do this style instead
function code(){
if(code){
code
}
}
this first one is also my preferred style because it is more clear and understandable. My question is why do I have to follow the second example? is there any advantages??
The official answer is that you can use either, but the practical answer is that it is safer to use the version where the opening curly brace is on the same line as the code block it defines.
In JavaScript, {} is the syntax for an object literal and JavaScript also has automatic semi-colon insertion. This automatic semi-colon insertion can cause functions written with the opening curly-brace on a different line than the function it defines the body of, to execute differently than you would expect. See this for details:
Why do results vary based on curly brace placement?
Mostly preference. I personally prefer the second way, but the only difference is when javascript's automatic semicolon insertion kicks in. There is no difference when dealing with function declarations or if statements.
This question already has answers here:
What is the difference between object keys with quotes and without quotes?
(5 answers)
Closed 5 years ago.
I'm not sure of the exact wording to use, but I have seen object assignments in javascript done two wasy
$('#test').dataTable({ fnInitComplete: myFunction });
and
$('#test').dataTable({ "fnInitComplete": myFunction });
Is there any actual difference between these, or any gotchas to be aware of?
There is no difference.
However, if the key is not a valid identifier (eg, it's a keyword, or it has spaces or punctuation), quotes are required.
Also, the JSON standard (which is not Javascript) always requires double-quotes.
The currently accepted answer is incorrect:
However, if the key is not a valid identifier (eg, it's a keyword, or it has spaces or punctuation), quotes are required.
The quotes aren’t required if you use a numeric literal as a property name. Also, keywords and reserved words are valid identifier names, and all identifier names (not just identifiers) are valid JavaScript property names.
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.
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.
The main difference is that with quotes, you can use keys with spaces, js keywords, etc that are illegal as normal symbols. That's why JSON requires them.
Without the quotes, the property name must be either a number, or a valid JavaScript identifier. With the quotes, you can use an arbitrary string. Quoting a string that's already a valid JS identifier is functionally identical to using just the identifier.