The code in question is here:
var $item = $(this).parent().parent().find('input');
What is the purpose of the dollar sign in the variable name, why not just exclude it?
A '$' in a variable means nothing special to the interpreter, much like an underscore.
From what I've seen, many people using jQuery (which is what your example code looks like to me) tend to prefix variables that contain a jQuery object with a $ so that they are easily identified and not mixed up with, say, integers.
The dollar sign function $() in jQuery is a library function that is frequently used, so a short name is desirable.
In your example the $ has no special significance other than being a character of the name.
However, in ECMAScript 6 (ES6) the $ may represent a Template Literal
var user = 'Bob'
console.log(`We love ${user}.`); //Note backticks
// We love Bob.
The dollar sign is treated just like a normal letter or underscore (_). It has no special significance to the interpreter.
Unlike many similar languages, identifiers (such as functional and variable names) in Javascript can contain not only letters, numbers and underscores, but can also contain dollar signs. They are even allowed to start with a dollar sign, or consist only of a dollar sign and nothing else.
Thus, $ is a valid function or variable name in Javascript.
Why would you want a dollar sign in an identifier?
The syntax doesn't really enforce any particular usage of the dollar sign in an identifier, so it's up to you how you wish to use it. In the past, it has often been recommended to start an identifier with a dollar sign only in generated code - that is, code created not by hand but by a code generator.
In your example, however, this doesn't appear to be the case. It looks like someone just put a dollar sign at the start for fun - perhaps they were a PHP programmer who did it out of habit, or something. In PHP, all variable names must have a dollar sign in front of them.
There is another common meaning for a dollar sign in an interpreter nowadays: the jQuery object, whose name only consists of a single dollar sign ($). This is a convention borrowed from earlier Javascript frameworks like Prototype, and if jQuery is used with other such frameworks, there will be a name clash because they will both use the name $ (jQuery can be configured to use a different name for its global object). There is nothing special in Javascript that allows jQuery to use the single dollar sign as its object name; as mentioned above, it's simply just another valid identifier name.
The $ sign is an identifier for variables and functions.
https://web.archive.org/web/20160529121559/http://www.authenticsociety.com/blog/javascript_dollarsign
That has a clear explanation of what the dollar sign is for.
Here's an alternative explanation: http://www.vcarrer.com/2010/10/about-dollar-sign-in-javascript.html
Dollar sign is used in ecmascript 2015-2016 as 'template literals'.
Example:
var a = 5;
var b = 10;
console.log(`Sum is equal: ${a + b}`); // 'Sum is equlat: 15'
Here working example:
https://es6console.com/j3lg8xeo/
Notice this sign " ` ",its not normal quotes.
U can also meet $ while working with library jQuery.
$ sign in Regular Expressions means end of line.
When using jQuery, the usage of $ symbol as a prefix in the variable name is merely by convention; it is completely optional and serves only to indicate that the variable holds a jQuery object, as in your example.
This means that when another jQuery function needs to be called on the object, you wouldn't need to wrap it in $() again. For instance, compare these:
// the usual way
var item = $(this).parent().parent().find('input');
$(item).hide(); // this is a double wrap, but required for code readability
item.hide(); // this works but is very unclear how a jQuery function is getting called on this
// with $ prefix
var $item = $(this).parent().parent().find('input');
$item.hide(); // direct call is clear
$($item).hide(); // this works too, but isn't necessary
With the $ prefix the variables already holding jQuery objects are instantly recognizable and the code more readable, and eliminates double/multiple wrapping with $().
No reason. Maybe the person who coded it came from PHP. It has the same effect as if you had named it "_item" or "item" or "item$$".
As a suffix (like "item$", pronounced "items"), it can signify an observable such as a DOM element as a convention called "Finnish Notation" similar to the Hungarian Notation.
I'll add this:
In chromium browser's developer console (haven't tried others) the $ is a native function that acts just like document.querySelector most likely an alias inspired from JQuery's $
Here is a good short video explanation: https://www.youtube.com/watch?v=Acm-MD_6934
According to Ecma International Identifier Names are tokens that are interpreted according to the grammar given in the “Identifiers” section of chapter 5 of the Unicode standard, with some small modifications. An Identifier is an IdentifierName that is not a ReservedWord (see 7.6.1). The Unicode identifier grammar is based on both normative and informative character categories specified by the Unicode Standard. The characters in the specified categories in version 3.0 of the Unicode standard must be treated as in those categories by all conforming ECMAScript implementations.this standard specifies specific character additions:
The dollar sign ($) and the underscore (_) are permitted anywhere in an IdentifierName.
Further reading can be found on: http://www.ecma-international.org/ecma-262/5.1/#sec-7.6
Ecma International is an industry association founded in 1961 and dedicated to the standardization of Information and Communication Technology (ICT) and Consumer Electronics (CE).
"Using the dollar sign is not very common in JavaScript, but
professional programmers often use it as an alias for the main
function in a JavaScript library.
In the JavaScript library jQuery, for instance, the main function $
is used to select HTML elements. In jQuery $("p"); means "select all
p elements". "
via https://www.w3schools.com/js/js_variables.asp
I might add that using it for jQuery allows you to do things like this, for instance:
$.isArray(myArray);
let $ = "Hello";
let $$ = "World!";
let $$$$$$$$$$$ = $ + " " + $$;
alert($$$$$$$$$$$);
This displays a "Hello World!" alert box.
As you can see, $ is just a normal character as far as JavaScript identifiers or variable names go. In fact you can use a huge range of Unicode characters as variable names that look like dollar or other currency signs!
Just be careful as the $ sign is also used as a reference to the jQuery namespace/library:
$("p").text("I am using some jquery");
// ...is the same as...
jQuery("p").text("I am using some jquery");
$ is also used in the new Template Literal format using string interpolation supported in JavaScript version ES6/2015:
var x = `Hello ${name}`;
Related
When looking at examples of variable substitution in GStrings, I have noticed two difference syntaxes. This can be seen here: Groovy Templates
This has the example:
def text = 'Dear "$firstname $lastname",\nSo nice to meet you in <% print city %>.\nSee you in ${month},\n${signed}'
It looks like ${variable} is used more commonly when you have an expression, but $variable is used when you just have a single variable, but even here they mix it with $firstname and ${month}. Is there a reason to do it one way or another when you have a single variable and not an expression, or does it not matter?
It doesn't matter...
As you say, if you have an expression like "${name.toUpperCase()}", "${number}th" or "${list[0]}", then it has to be inside braces, but both "${name}" and "$name" are the same.
Indeed, so long as it's simple property access you can omit the braces, ie: "Hello $person.username"
It could be said that adding the braces can make your string templates easier to read, but that's a personal preference thing.
I came across an interesting article. Which states unless until we are defining JSON we should use only single quote.
var foo = 'bar'; //Right way
var foo = "bar"; //Wrong way
Can anyone put light on this, why is it so?
Any help greatly appreciated.
The most likely reason is programmer preference / API consistency.
Strictly speaking, there is no difference in meaning; so the choice comes down to convenience.
Here are several factors that could influence your choise:
House style: Some groups of developers already use one convention or the other.
Client-side requirements: Will you be using quotes within the strings? (See Ady's answer).
Server-side language: VB.Net people might choose to use single quotes for java-script so that the scripts can be built server-side (VB.Net uses double-quotes for strings, so the java-script strings are easy to distinguished if they use single quotes).
Library code: If you're using a library that uses a particular style, you might consider using the same style yourself.
When using single quotes, any apostrophe needs escaping. ('Joe\'s got a cool bike.') When using double quotes, they don't. ("Joe's got a cool bike.") Apostrophes are much more common in English strings than double quotes.
Personal preference: You might thing one or other style looks better.
Please check following post that might be helpful for you When to Use Double or Single Quotes in JavaScript
First of all this is just a style guide.
You can define your ECMAScript strings the way you like them.
It is syntactically correct to use single quotes or double quotes for strings.
But according to JSON Specifications, a JSON value can be a string in double quotes, or a number, or true or false or null, or an object or an array.
This is PascalCase: SomeSymbol
This is camelCase: someSymbol
This is snake_case: some_symbol
So my questions is whether there is a widely accepted name for this: some-symbol? It's commonly used in url's.
There isn't really a standard name for this case convention, and there is disagreement over what it should be called.
That said, as of 2019, there is a strong case to be made that kebab-case is winning:
https://trends.google.com/trends/explore?date=all&q=kebab-case,spinal-case,lisp-case,dash-case,caterpillar-case
spinal-case is a distant second, and no other terms have any traction at all.
Additionally, kebab-case has entered the lexicon of several javascript code libraries, e.g.:
https://lodash.com/docs/#kebabCase
https://www.npmjs.com/package/kebab-case
https://v2.vuejs.org/v2/guide/components-props.html#Prop-Casing-camelCase-vs-kebab-case
However, there are still other terms that people use. Lisp has used this convention for decades as described in this Wikipedia entry, so some people have described it as lisp-case. Some other forms I've seen include caterpillar-case, dash-case, and hyphen-case, but none of these is standard.
So the answer to your question is: No, there isn't a single widely-accepted name for this case convention analogous to snake_case or camelCase, which are widely-accepted.
It's referred to as kebab-case. See lodash docs.
It's also sometimes known as caterpillar-case
This is the most famous case and It has many names
kebab-case: It's the name most adopted by official software
caterpillar-case
dash-case
hyphen-case or hyphenated-case
lisp-case
spinal-case
css-case
slug-case
friendly-url-case
As the character (-) is referred to as "hyphen" or "dash", it seems more natural to name this "dash-case", or "hyphen-case" (less frequently used).
As mentioned in Wikipedia, "kebab-case" is also used. Apparently (see answer) this is because the character would look like a skewer... It needs some imagination though.
Used in lodash lib for example.
Recently, "dash-case" was used by
Angular (https://angular.io/guide/glossary#case-types)
NPM modules
https://www.npmjs.com/package/case-dash (removed ?)
https://www.npmjs.com/package/dasherize
Adding the correct link here Kebab Case
which is All lowercase with - separating words.
I've always called it, and heard it be called, 'dashcase.'
There is no standardized name.
Libraries like jquery and lodash refer it as kebab-case. So does Vuejs javascript framework. However, I am not sure whether it's safe to declare that it's referred as kebab-case in javascript world.
I've always known it as kebab-case.
On a funny note, I've heard people call it a SCREAM-KEBAB when all the letters are capitalized.
Kebab Case Warning
I've always liked kebab-case as it seems the most readable when you need whitespace. However, some programs interpret the dash as a minus sign, and it can cause problems as what you think is a name turns into a subtraction operation.
first-second // first minus second?
ten-2 // ten minus two?
Also, some frameworks parse dashes in kebab cased property. For example, GitHub Pages uses Jekyll, and Jekyll parses any dashes it finds in an md file. For example, a file named 2020-1-2-homepage.md on GitHub Pages gets put into a folder structured as \2020\1\2\homepage.html when the site is compiled.
Snake_case vs kebab-case
A safer alternative to kebab-case is snake_case, or SCREAMING_SNAKE_CASE, as underscores cause less confusion when compared to a minus sign.
I'd simply say that it was hyphenated.
Worth to mention from abolish:
https://github.com/tpope/vim-abolish/blob/master/doc/abolish.txt#L152
dash-case or kebab-case
In Salesforce, It is referred as kebab-case. See below
https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.js_props_names
Here is a more recent discombobulation. Documentation everywhere in angular JS and Pluralsight courses and books on angular, all refer to kebab-case as snake-case, not differentiating between the two.
Its too bad caterpillar-case did not stick because snake_case and caterpillar-case are easily remembered and actually look like what they represent (if you have a good imagination).
My ECMAScript proposal for String.prototype.toKebabCase.
String.prototype.toKebabCase = function () {
return this.valueOf().replace(/-/g, ' ').split('')
.reduce((str, char) => char.toUpperCase() === char ?
`${str} ${char}` :
`${str}${char}`, ''
).replace(/ * /g, ' ').trim().replace(/ /g, '-').toLowerCase();
}
This casing can also be called a "slug", and the process of turning a phrase into it "slugify".
https://hexdocs.pm/slugify/Slug.html
i have something like
<s:link view="/member/index.xhtml" value="My News" propagation="none"/>
<s:link view="/member/index.xhtml" value="#{msg.myText}" propagation="none"/>
where the value of myText in the messages.properties is
myText=My News
The first line of the example works fine and replaces the text to "My News", but the second that uses a value from the resource bundle escapes the ambersand, too "My News".
I tried also to use unicode escape sequences for the ambersand and/or hash with My\u0026\u0023160;News, My\u0026#160;News and My\u0026nbsp;News in the properties file without success.
(Used css no-wrap instead of the previous used xml encoding, but would be interested anyway)
EDIT - Answer to clarified question
The first is obviously inline, so interpreter knows that this is safe.
The second one comes from external source (you are using Expression Language) and as such is not safe and need to be escaped. The result of escaping would be as you wrote, basically it will show you the exact value of HTML entity.
This is related to security (XSS for example) and not necessary i18n.
Previous attempt
I don't quite know what you are asking for but I believe it is "how to display it?".
Most of the standard JSF controls contain escape attribute that if set to false won't escape the text. Unfortunately it seems that you are using something like SeamTools which does not have this attribute.
Well, in this case there is not much to be done. Unless you could use standard control, maybe you should go and try to actually save your properties file as Unicode (UTF-16 BigEndian in fact) and simply put valid Unicode non-breaking space character. Theoretically that should work; Unicode-encoded properties files are supported in latest version of Java (although I cannot recall if it was Java SE 5 or Java SE 6)...
With the rise of node.js, multi-line strings are becoming more necessary in JavaScript.
Is there a special way to do this in Node.JS, even if it does not work in browsers?
Are there any plans or at least a feature request to do this that I can support?
I already know that you can use \n\ at the end of every line, that is not what I want.
node v4 and current versions of node
As of ES6 (and so versions of Node greater than v4), a new "template literal" intrinsic type was added to Javascript (denoted by back-ticks "`") which can also be used to construct multi-line strings, as in:
`this is a
single string`
which evaluates to: 'this is a\nsingle string'.
Note that the newline at the end of the first line is included in the resulting string.
Template literals were added to allow programmers to construct strings where values or code could be directly injected into a string literal without having to use util.format or other templaters, as in:
let num=10;
console.log(`the result of ${num} plus ${num} is ${num + num}.`);
which will print "the result of 10 plus 10 is 20." to the console.
Older versions of node
Older version of node can use a "line continuation" character allowing you to write multi-line strings such as:
'this is a \
single string'
which evaluates to: 'this is a single string'.
Note that the newline at the end of the first line is not included in the resulting string.
Multiline strings are a current part of JavaScript (since ES6) and are supported in node.js v4.0.0 and newer.
var text = `Lorem ipsum dolor
sit amet, consectetur
adipisicing
elit. `;
console.log(text);
What exactly are you looking for when you mean multiline strings.
Are you looking for something like:
var str = "Some \
String \
Here";
Which would print as "Some String Here"?
If so, keep in mind that the above is valid Javascript, but this isn't:
var str = "Some \
String \
Here";
What's the difference? A space after the \. Have fun debugging that.
As an aside to what folks have been posting here, I've heard that concatenation can be much faster than join in modern javascript vms. Meaning:
var a =
[ "hey man, this is on a line",
"and this is on another",
"and this is on a third"
].join('\n');
Will be slower than:
var a = "hey man, this is on a line\n" +
"and this is on another\n" +
"and this is on a third";
In certain cases. http://jsperf.com/string-concat-versus-array-join/3
As another aside, I find this one of the more appealing features in Coffeescript. Yes, yes, I know, haters gonna hate.
html = '''
<strong>
cup of coffeescript
</strong>
'''
Its especially nice for html snippets. I'm not saying its a reason to use it, but I do wish it would land in ecma land :-(.
Josh
In addition to accepted answer:
`this is a
single string`
which evaluates to: 'this is a\nsingle string'.
If you want to use string interpolation but without a new line,
just add backslash as in normal string:
`this is a \
single string`
=> 'this is a single string'.
Bear in mind manual whitespace is necessary though:
`this is a\
single string`
=> 'this is asingle string'
Take a look at the mstring module for node.js.
This is a simple little module that lets you have multi-line strings in JavaScript.
Just do this:
var M = require('mstring')
var mystring = M(function(){/***
Ontario
Mining and
Forestry
Group
***/})
to get
mystring === "Ontario\nMining and\nForestry\nGroup"
And that's pretty much it.
How It Works
In Node.js, you can call the .toString method of a function, and it will give you the source code of the function definition, including any comments. A regular expression grabs the content of the comment.
Yes, it's a hack. Inspired by a throwaway comment from Dominic Tarr.
note: The module (as of 2012/13/11) doesn't allow whitespace before the closing ***/, so you'll need to hack it in yourself.
Take a look at CoffeeScript: http://coffeescript.org
It supports multi-line strings, interpolation, array comprehensions and lots of other nice stuff.
If you use io.js, it has support for multi-line strings as they are in ECMAScript 6.
var a =
`this is
a multi-line
string`;
See "New String Methods" at http://davidwalsh.name/es6-io for details and "template strings" at http://kangax.github.io/compat-table/es6/ for tracking compatibility.
Vanilla Javascipt does not support multi-line strings. Language pre-processors are turning out to be feasable these days.
CoffeeScript, the most popular of these has this feature, but it's not minimal, it's a new language. Google's traceur compiler adds new features to the language as a superset, but I don't think multi-line strings are one of the added features.
I'm looking to make a minimal superset of javascript that supports multiline strings and a couple other features. I started this little language a while back before writing the initial compiler for coffeescript. I plan to finish it this summer.
If pre-compilers aren't an option, there is also the script tag hack where you store your multi-line data in a script tag in the html, but give it a custom type so that it doesn't get evaled. Then later using javascript, you can extract the contents of the script tag.
Also, if you put a \ at the end of any line in source code, it will cause the the newline to be ignored as if it wasn't there. If you want the newline, then you have to end the line with "\n\".