Syntax in Mozilla docs/ECMAScript specs - javascript

You often see this kind of syntax for describing methods:
Math.max([value1[,value2, ...]])
Function.prototype.call (thisArg [ , arg1 [ , arg2, … ] ] )
Why are parameters denoted like this using brackets and leading commas?

Brackets are used for argument specifications to indicate that the argument is optional.
This likely comes from the format used in UNIX/Linux man pages (although they may have borrowed that syntax from some other earlier source for all I know). The man page on man-pages has a description of how arguments should be represented (emphasis mine):
SYNOPSIS briefly describes the command or function's interface.
For commands, this shows the syntax of the command and
its arguments (including options); boldface is used for
as-is text and italics are used to indicate replaceable
arguments. Brackets ([]) surround optional arguments,
vertical bars (|) separate choices, and ellipses (...)
can be repeated.

Javascript doesn't have strict requirements for function parameters. functions can have as many parameters as you want to put in them. You can call a function that only has two parameters with 3 parameters and javascript will ignore the ones that aren't noted.
However, the order of the variables is still important. In other words, you can't use just the first and third parameters, if you want to use the third parameter you have to specify something for the second.
the square brackets mean the parameter is not required. The comma is just to tell you that you need a comma if you are going to specify a parameter there.

Related

Dust JS Dot Into string Key Name

I'm not sure if I'm doing something wrong, but I have "dates" as a key for the object and Dust seems to just output exactly what I put in rather than evaluate properly.
{#.weeks pos=items}
{pos['2016-02-15].id}
{/.weeks}
Output:
{pos.'2016-02-15'.id}
How can I output the ID rather than output the string?
Dust does not allow the character - as part of an array key.
As you mentioned in your comment, - is allowed in Dust references, but the rules are slightly different.
Dust references must not start with a number, and contain the characters 0-9a-zA-Z_$-. This mirrors the rules for real Javascript variables, except for the hyphen.
Array keys are allowed to start with numbers, but cannot contain hyphens. So when you use a date as part of the key, Dust uses the array key evaluation path since the date starts with a number.
This would work, for example, using the array-key evaluation path:
{#.weeks pos=items}
{pos[20160215].id}
{/.weeks}
And so would this, because it uses the reference evaluation path:
{#.weeks pos=items}
{pos[date-2016-02-15].id}
{/.weeks}
You'll have to munge your data slightly.
I think you've uncovered an inconsistency in the way Dust handles reference naming. In early Dust, references were only allowed to be valid JS variable names. This restriction was relaxed later on but there are clearly some rough bits around it.

Find all function signatures with more than 2 arguments in javascript

I need to find all function signatures accepting more than X arguments (say 2).
I tried something like function\s*\((\w*,){3,10} (which would catch all signature with 3-10 args, but it did not work. Variations on it are yielding unexpected results. I guess I'm just not that good at regex, but any help is appreciated.
update: I should point out that I am writing a sort of code inspection tool. Among the many things, I want to spot functions that accept more than 2 arguments (as I promote the usage of functions with few arguments, and 1 argument in case of constructors). So I cannot call arguments.length etc.
Just think "easy":
A method typically has (...): \(\)
A method with 3 parameters has 2 , inside the brackets: \(,{2,2}\)
each , NEEDS to be preceeded AND followed by strings: \((?:\w+,\w+){2,2}\)
no double matches occur, so does not work - let's make the leading string mandatory, the following optional, but finally it needs to stop with a string:
\((?:\w+,\w*){2,2}\w+\)
usually a method declaration starts with function name: function\s+\w+\s*\((?:\w*,\w*){2,2}\)
finally, there could be whitespaces arround the paremeters: function\s+\w+\s*\((?:\s*\w+\s*,\s*\w*\s*){2,2}\w+\s*\)
There you go. This should cover all "common" method declarations, except nameless lambda-expressions:
function\s+\w+\s*\((?:\s*\w+\s*,\s*\w*\s*){2,2}\w+\s*\)
Debuggex Demo
Matching two to two commas will find signatures with 3 parameters.
Matchint two to five commas will find signatures with 3 upto 6 parameters.
First of all, JavaScript is not a regular language, as a result, one cannot use a regex to fully grasp the language, and thus there is a possibility that you will either accept false positives, or false negatives.
A regex that probably comes close is:
function(?:\s+\w+)*\s*\(([^),]*)(\s*,\s*[^),]*){2,}\)
The regex works as follows:
function searches for the function keyword.
next there is an optional group \s+\w+ this group is used to identify with the name of the function: it is possible to define an anonymous function with no name, so the group must be optional.
Next \s*\( there is an arbitrary number of space and a bracket to open the parameter list;
Now between the brackets, we start looking for the parameters. To cover (most) cases, we will define a parameter as [^,)]* (a sequence of characters not containing a comma nor the closed bracket).
Now for the next parameters, we need to skip a comma, this is enforced by the \s*,\s* pattern (\s* is actually unnecessary). Next again a group for a parameter name and of course we need to skip at least two commas.
Finally, an (optional) closing bracket.
You'd want to use function\s*\w+\s*\(\s*(\w+,?){3,10} to match non-anonymous (named) functions, and remove the \w+\s* to get function\s*\(\s*(\w+,?){3,10} for anonymous functions.
These can be combined to get function\s*(?:\w+\s*)?\(\s*(\w+,?){3,10} (the ?: is the non-capturing group)

"#" character in javascript?

Recently I found some interesting codes on a website.
<div class="inputArea">
<textarea type="text" id="textInput" class="chatInput lightBorder"></textarea>
</div>
<b>Send</b>
When I click the "Send" button (it's a hyperlink, but it looks like a button on the page") and it will fire the js code "sendMsg#.inputArea". What it does is to send a message in the textarea to the server. It acts like the sendMsg is a function and .inputArea is a parameter passed to that function. But it does not seem to follow the EMAC standard. However, it works. How is it possible? It now looks like black magic to me. Can someone explain how the # character works in the code?
Updated Answer
...now that you've shown what you think is "JavaScript code."
This isn't JavaScript code:
<b>Send</b>
<!-- Not JavaScript Code ----------------------^^^^^^^^^^^^^^^^^^ -->
That's just an attribute value on an element. (And an invalid one, a doesn't have a click attribute.) Presumably code in their JavaScript understands what to do with it. You're confusing that with an onclick attribute, which would (normally) contain JavaScript code.
Original Answer
You can't use # in a property name literal, variable name, or function name (collectively, an IdentifierName) in JavaScript.*
how to declare a special character in js
You can't. The characters allowed in IdentifierName are defined by the specification and are not extensible.
You can use any character you like as a property name (but not variable or function name), but not as a literal, only if you use brackets notation and a string, e.g.:
var obj = {"SendMsg#": "foo"};
console.log(obj["SendMsg#"]); // "foo"
* That said, JavaScript is very liberal about the characters you can use in IdentiferName, so while # isn't allowed, I couldn't absolutely guarantee there isn't some other Unicode character that looks a bit like it that's allowed. But I suspect not, as the Unicode page for # doesn't list any characters likely to be confused with #.
# isn't special at all in JavaScript, other than the fact that it isn't valid in identifiers - as in you can't use it for function and variable names. You can't declare custom operators in javascript, so unless you get to speak to the one who built that site, there's no way to tell what they do with # in strings.
On another note, many special characters are valid in JS, so you can name a function $, _ or even q̊̆̓̍u̐͂e̷̜r̤̻̫ͅy̎ if you want. But # isn't one of them.

Why are JSON attribute names quoted? [duplicate]

According to Crockford's json.org, a JSON object is made up of members, which is made up of pairs.
Every pair is made of a string and a value, with a string being defined as:
A string is a sequence of zero or more
Unicode characters, wrapped in double
quotes, using backslash escapes. A
character is represented as a single
character string. A string is very
much like a C or Java string.
But in practice most programmers don't even know that a JSON key should be surrounded by double quotes, because most browsers don't require the use of double quotes.
Does it make any sense to bother surrounding your JSON in double quotes?
Valid Example:
{
"keyName" : 34
}
As opposed to the invalid:
{
keyName : 34
}
The real reason about why JSON keys should be in quotes, relies in the semantics of Identifiers of ECMAScript 3.
Reserved words cannot be used as property names in Object Literals without quotes, for example:
({function: 0}) // SyntaxError
({if: 0}) // SyntaxError
({true: 0}) // SyntaxError
// etc...
While if you use quotes the property names are valid:
({"function": 0}) // Ok
({"if": 0}) // Ok
({"true": 0}) // Ok
The own Crockford explains it in this talk, they wanted to keep the JSON standard simple, and they wouldn't like to have all those semantic restrictions on it:
....
That was when we discovered the
unquoted name problem. It turns out
ECMA Script 3 has a whack reserved
word policy. Reserved words must be
quoted in the key position, which is
really a nuisance. When I got around
to formulizing this into a standard, I
didn't want to have to put all of the
reserved words in the standard,
because it would look really stupid.
At the time, I was trying to convince
people: yeah, you can write
applications in JavaScript, it's
actually going to work and it's a good
language. I didn't want to say, then,
at the same time: and look at this
really stupid thing they did! So I
decided, instead, let's just quote the
keys.
That way, we don't have to tell
anybody about how whack it is.
That's why, to this day, keys are quoted in
JSON.
...
The ECMAScript 5th Edition Standard fixes this, now in an ES5 implementation, even reserved words can be used without quotes, in both, Object literals and member access (obj.function Ok in ES5).
Just for the record, this standard is being implemented these days by software vendors, you can see what browsers include this feature on this compatibility table (see Reserved words as property names)
Yes, it's invalid JSON and will be rejected otherwise in many cases, for example jQuery 1.4+ has a check that makes unquoted JSON silently fail. Why not be compliant?
Let's take another example:
{ myKey: "value" }
{ my-Key: "value" }
{ my-Key[]: "value" }
...all of these would be valid with quotes, why not be consistent and use them in all cases, eliminating the possibility of a problem?
One more common example in the web developer world: There are thousands of examples of invalid HTML that renders in most browsers...does that make it any less painful to debug or maintain? Not at all, quite the opposite.
Also #Matthew makes the best point of all in comments below, this already fails, unquoted keys will throw a syntax error with JSON.parse() in all major browsers (and any others that implement it correctly), you can test it here.
If I understand the standard correctly, what JSON calls "objects" are actually much closer to maps ("dictionaries") than to actual objects in the usual sense. The current standard easily accommodates an extension allowing keys of any type, making
{
"1" : 31.0,
1 : 17,
1n : "valueForBigInt1"
}
a valid "object/map" of 3 different elements.
If not for this reason, I believe the designers would have made quotes around keys optional for all cases (maybe except keywords).
YAML, which is in fact a superset of JSON, supports what you want to do. ALthough its a superset, it lets you keep it as simple as you want.
YAML is a breath of fresh air and it may be worth your time to have a look at it. Best place to start is here: http://en.wikipedia.org/wiki/YAML
There are libs for every language under the sun, including JS, eg https://github.com/nodeca/js-yaml

Comments in angularjs expression

I have some HTML tags which have ng-clicks and ng-ifs. Inside the respective expressions, I make function calls and pass in parameters, some of which are literals (mostly just true or false). So I would like to add a comment as to what a literal means, but angular doesn't seem to be able to parse this correctly. (I realize passing literals is not the brightest idea but I would nevertheless like to know the answer)
<button class='someclass' ng-click='somefunction(val1, val2, true /* explanation for literal */)' > </button>
How do I add comments in angular expressions?
No, comments are not supported. Parser sees / as an mathematical operator (see source code) which expects primary expression after it: e.g. something starting with (, or [, etc. However there is no valid expression in javascript that can include * immediately after / character. So parser throws an exception: Token '*' not a primary expression.
While the Angular documentation doesn't explicitly say that JavaScript comments are not supported. I would assume they are not.
Angular Expressions are only a subset of some JavaScript (and some added features like filters).
Why can't you pass these comments as separate parameters instead of appending other parameters?
Even though you achieve doing this somehow it would be not very good design.

Categories