This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why can't I access a property of an integer with a single dot?
I was reading an article, and came across the strange behaviour of javascript toFixed method. I don't understand the reason for the last statement. Can anyone explain please?
(42).toFixed(2); // "42.00" Okay
42.toFixed(2); // SyntaxError: identifier starts immediately after numeric literal
42..toFixed(2); // "42.00" This really seems strange
A number in JavaScript is basically this in regex:
[+-]?[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?
Note that the quantifiers are greedy. This means when it sees:
42.toFixed(2);
It reads the 42. as the number and then is immediately confronted with toFixed and doesn't know what to do with it.
In the case of 42..toFixed(2), the number is 42. but not 42.. because the regex only allows one dot. Then it sees the . which can only be a call to a member, which is toFixed. Everything works fine.
As far as readability goes, (42).toFixed(2) is far clearer as to its intention.
The dot is ambiguous: decimal point or call member operator. Therefore the error.
42..toFixed(2); is equivalent to (42.).toFixed(2)
Related
If I try to write
3.toFixed(5)
there is a syntax error. Using double dots, putting in a space, putting the three in parentheses or using bracket notation allows it to work properly.
3..toFixed(5)
3 .toFixed(5)
(3).toFixed(5)
3["toFixed"](5)
Why doesn't the single dot notation work and which one of these alternatives should I use instead?
The period is part of the number, so the code will be interpreted the same as:
(3.)toFixed(5)
This will naturally give a syntax error, as you can't immediately follow the number with an identifier.
Any method that keeps the period from being interpreted as part of the number would work. I think that the clearest way is to put parentheses around the number:
(3).toFixed(5)
You can't access it because of a flaw in JavaScript's tokenizer. Javascript tries to parse the dot notation on a number as a floating point literal, so you can't follow it with a property or method:
2.toString(); // raises SyntaxError
As you mentioned, there are a couple of workarounds which can be used in order make number literals act as objects too. Any of these is equally valid.
2..toString(); // the second point is correctly recognized
2 .toString(); // note the space left to the dot
(2).toString(); // 2 is evaluated first
To understand more behind object usage and properties, check out the Javascript Garden.
It doesn't work because JavaScript interprets the 3. as being either the start of a floating-point constant (such as 3.5) or else an entire floating-point constant (with 3. == 3.0), so you can't follow it by an identifier (in your case, a property-name). It fails to recognize that you intended the 3 and the . to be two separate tokens.
Any of your workarounds looks fine to me.
This is an ambiguity in the Javascript grammar. When the parser has got some digits and then encounters a dot, it has a choice between "NumberLiteral" (like 3.5) or "MemberExpression" (like 3.foo). I guess this ambiguity cannot be resolved by lookahead because of scientific notation - should 3.e2 be interpreted as 300 or a property e2 of 3? Therefore they voluntary decided to prefer NumberLiterals here, just because there's actually not very much demand for things like 3.foo.
As others have mentioned, Javascript parser interprets the dot after Integer literals as a decimal point and hence it won't invoke the methods or properties on Number object.
To explicitly inform JS parser to invoke the properties or methods on Integer literals, you can use any of the below options:
Two Dot Notation
3..toFixed()
Separating with a space
3 .toFixed()
Write integer as a decimal
3.0.toFixed()
Enclose in parentheses
(3).toFixed()
Assign to a constant or variable
const nbr = 3;
nbr.toFixed()
This question already has answers here:
Why can't I access a property of an integer with a single dot?
(5 answers)
Closed 6 years ago.
I know 1 is not an object, but when I type 1..toString(), it returns "1" in the console. Why is that?
Because the JavaScript parser assumes that 1. must be followed only by one or more digits to represent a float number. Using parentheses works: (1).toString().
Because it is interpreting 1. as the number. When you have 1.toString(), it is the same as saying (1.)toString(). Therefore 1..toString() is the same as (1.).toString()
The reason why the below works is:
1..toString()
The 1.. is considered as a floating point number. The console expects something like:
1.0
1.5
Or something. If you are giving something like:
1.toString();
The above is not a valid number. That's the reason. So to make the above work, you need a parenthesis to tell that the number is completed:
(1).toString();
This question already has answers here:
Evaluating a string as a mathematical expression in JavaScript
(26 answers)
Closed 8 years ago.
I am trying to create a simple graphing calculator where a user enters a function of f (like f(x) = x^2+2x+6). Basically the javascript replaces the x in the function with some number and then evaluates the function using eval(). The problem is, I want users to be able to type x^2 instead of default javascript which would be Math.pow(x,2). I'm guessing it's going to be some regular expression but I have little experience with them and find them really confusing, personally. Is it possible to convert a statement like x^3-x^2 to Math.pow(x,3)-Math.pow(x,2) ??
Help greatly appreciated.
You want to use a Regular Expression that looks something along the lines of
(.+)\^(.+)
This will match both selections, you then replace the instances of that string, using those matches like this.
Math.pow($1, $2)
Javascript has support for this kind of operation with the function option in String.prototype.replace
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter
1) Yes, it is possible. You can easily program it yourself if you parse what the user entered. Wherever you see x^n just turn it into Math.pow(x,n). And only then eval.
This will work for say polynomials of one variable.
2) If you want to solve this more generally (for a broader class of math functions),
you need to come up with some grammar and build an AST from the user input.
http://en.wikipedia.org/wiki/Abstract_syntax_tree
This question already has answers here:
What is the !! (not not) operator in JavaScript?
(42 answers)
Closed 9 years ago.
I was just trawling through the QUnit source code (1.12.0) and came across a line that confused me. I've done a bit of googling and haven't been able to come up with a reason for it.
Source: http://code.jquery.com/qunit/qunit-1.12.0.js line 520
result = !!result;
A similar thing appears further on in the code, except instead of storing the result in itself, it's storing the double negated variable in JSON.
Source: http://code.jquery.com/qunit/qunit-1.12.0.js line 957
result: !!result
As ! negates, I assume !! will negate then negate again, thus ending up with exactly what you started with. In which case, what is achieved by setting a variable equal to itself, negated twice? (Or in the latter example, returning itself negated twice instead of just returning itself.)
!! is used to convert the value to the right of it to its equivalent boolean value.
Also check this related Thread.
This question already has answers here:
Closed 10 years ago.
Why does calling 152..toString(2) return a binary string value of "10011000", when a call to 152.toString(2) throws the following exception?
"SyntaxError: identifier starts immediately after numeric literal"
It seems to me that it's intuitive to want to use the latter call to toString(), as it looks & feels correct. The first example just seems plain odd to me.
Does anyone know why JavaScript was designed to behave like this?
A . after a number might seem ambiguous. Is it a decimal or an object member operator?
However, the interpreter decides that it's a decimal, so you're missing the member operator.
It sees it as this:
(10.)toString(); // invalid syntax
When you include the second ., you have a decimal followed by the member operator.
(10.).toString();
#pedants and downvoters
The . character presents an ambiguity. It can be understood to be the member operator, or a decimal, depending on its placement. If there was no ambiguity, there would be no question to ask.
The specification's interpretation of the . character in that particular position is that it will be a decimal. This is defined by the numeric literal syntax of ECMAScript.
Just because the specification resolves the ambiguity for the JS interpreter, doesn't mean that the ambiguity of the . character doesn't exist at all.
The lexer (aka "tokenizer") when reading a new token, and upon first finding a digit, will keep consuming characters (i.e. digits or one dot) until it sees a character that is not part of a legal number.
<152.> is a legal token (the trailing 0 isn't required) but <152..> isn't, so your first example reduces to this series of tokens:
<152.> <.> <toString> <(> <2> <)>
which is the legal (and expected) sequence, whereas the second looks like
<152.> <toString> <(> <2> <)>
which is illegal - there's no period token separating the Number from the toString call.
10. is a float number an you can use toString on float
eg.
parseFloat("10").toString() // "10"