1.toString() SyntaxError in Javascript - javascript

Why the first line below gives error although the second and third lines work fine?
1.toString(); // SyntaxError
(1).toString(); // OK
1['toString'](); // OK

The . presents ambiguity. Is it a decimal, or a property accessor?
The interpreter sees it as a decimal, so you can use .. to allow both the decimal, then the property syntax.
1..toString();
Or use one of the other ways you show to resolve the ambiguity.

The parser is trying to treat 1. as the start of a floating-point literal -- only toString turns it into an invalid number.
Compare with:
1.0.toString()

In (1).toString(), (1) forces it to evaluate before .toString() so it works.
In 1.toString(), 1 is not a valid identifier so it does not work.

In Javascript, using the dot (.) can be interpreted in one of two ways:
As a Property Accessor (e.g., var prop = myObject.prop;).
As part of a Floating-point Literal (e.g. var num = 1.5;).
In the above case, the leading 1. in 1.toString() is interpreted as a floating point number, hence the error:
SyntaxError: identifier starts immediately after numeric literal (learn more)
This is the same error you get if you try and declare a variable that starts with a number: var 1person = 'john';
To prevent the interpreter from seeing the 1. as a decimal and instead see it as accessing a property on our literal 1, there are several ways to accomplish this:
// Via white-space after the numeric literal
1 .toString();
1
.toString();
// Via a grouping-operator, aka, parentheses
// #see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Grouping_operator
(1).toString();
// Via an additional dot. Made clearer with parentheses as `(1.).toString()`
1..toString();
// Via an explicit fractional part (because `1. === 1.0`)
1.0.toString();
// Via bracket notation
1['toString']();
1.['toString']();
1.0['toString']();

Related

5.constructor.name - SyntaxError [duplicate]

For example,
1.toFixed(2) // Uncaught SyntaxError: Invalid or unexpected token
(1).toFixed(2) // "1.00"
let num = 1
num.toFixed(2) // "1.00"
At the same time, you don't have to wrap parenthesis around strings to call methods on them
'yo'.repeat(3) // "yoyoyo"
What is the rule at play here and where else does it apply? Guessing it has something to do with the dot being misinterpreted as a decimal for numbers?
Because the interpreter is looking for more digits (decimal values), not keywords or methods.
As others have stated, JavaScript is looking for more numbers after the decimal point. It thinks you are trying to type a float like 1.2 and it doesn't like that t there, it's not a number.
Interestingly, you can do this without parenthesis or making variable by using 2 decimal points. Like this: 1..toFixed(2). I guess you can also do 1.0.toFixed(2) if you want.
When using a variable, Javascript is confident that you're not going to add decimals after the point.
When not using a variable, Javascript thinks that you are going to add decimals after the point.
When you wrap your number with parenthesis, you say that the number is finished, and everything is fine again.
You can also use .. if you don't like parenthesis. The first one for decimals, the second one to call the method.
let num = 1;
console.log(num.toFixed(2));
// console.log(1.toFixed(2)); // ERROR
console.log((1).toFixed(2));
console.log(1..toFixed(2));

Understanding Number.toString(radix) unexpected token exception

I'm trying to understand difference between 4 and (4).
4.toString(); // SyntaxError: Unexpected token ILLEGAL
(4).toString(); // "4"
I thought it's because toString() method is defined on Number (object) and 4 is a primitive datatype i.e.number which doesn't have toString() method.
However, how does it works for (4).toString()?
4 === (new Number(4)) // false
(4) === (new Number(4)) // false. (4) is not an instance of Number object
Dot (.) doesn't only means for member access operator. It also means for decimal point in floating-point literals. When JS interpreter meets dot after digit (4 in your case) it expects floating-point literal, i.e. digits after dot. That's why do you need grouping operator (parens) there.

Why can you call toString() on an integer variable but not a literal number?

How come this works:
var num = 1;
console.log(num.toString()); // "1"
But this does not?
console.log(1.toString()); // SyntaxError: Unexpected token ILLEGAL
Because the grammar expects a . after a number to be parsed as part of that number, as it would be for e.g. 1.5. You need to disambiguate the . if you want to use it as a member operator on a numeric literal:
1..toString(); // "1"
1.0.toString(); // "1"
(1).toString(); // "1"
In the first two cases the first . is parsed as a floating point. The second can only be parsed as a member operator because numeric literals can only contain a single floating point.
This is shown by the NumericLiteral grammar in the spec.

What is this javascript syntax?

Can someone explain in detail what is going on here? Specifically the double dot notation.
(3.14).toFixed(); // "3"
3.14.toFixed(); // "3"
(3).toFixed(); // "3"
3.toFixed(); // SyntaxError: Unexpected token ILLEGAL
3..toFixed(); // "3"
source
According to ECMA Script 5.1 Specifications, grammar for decimal literals are defined like this
DecimalLiteral ::
DecimalIntegerLiteral . [DecimalDigits] [ExponentPart]
. DecimalDigits [ExponentPart]
DecimalIntegerLiteral [ExponentPart]
Note: The square brackets are just to indicate that the parts are optional.
So, when you say
3.toFixed()
After consuming 3., the parser thinks that the current token is a part of a Decimal Literal, but it can only be followed by DecimalDigits or ExponentPart. But it finds t, which is not valid, that is why it fails with SyntaxError.
when you do
3..toFixed()
After consuming 3., it sees . which is called property accessor operator. So, it omits the optional DecimalDigits and ExponentPart and constructs a Floating point object and proceeds to invoke toFixed() method.
One way to overcome this is to leave a space after the number, like this
3 .toFixed()
3. is a number, so the . is the decimal point and doesn't start a property.
3..something is a number followed by a property.

JavaScript plus sign in front of function expression

I’ve been looking for information about immediately invoked functions, and somewhere I stumbled on this notation:
+function(){console.log("Something.")}()
Can someone explain to me what the + sign in front of the function means/does?
It forces the parser to treat the part following the + as an expression. This is usually used for functions that are invoked immediately, e.g.:
+function() { console.log("Foo!"); }();
Without the + there, if the parser is in a state where it's expecting a statement (which can be an expression or several non-expression statements), the word function looks like the beginning of a function declaration rather than a function expression and so the () following it (the ones at the end of the line above) would be a syntax error (as would the absense of a name, in that example). With the +, it makes it a function expression, which means the name is optional and which results in a reference to the function, which can be invoked, so the parentheses are valid.
+ is just one of the options. It can also be -, !, ~, or just about any other unary operator. Alternately, you can use parentheses (this is more common, but neither more nor less correct syntactically):
(function() { console.log("Foo!"); })();
// or
(function() { console.log("Foo!"); }());
Subsidiary to #TJCrowder's answer, + is usually used to force numerical casting of a value as this SO answer explains. In this instance it is called the 'unary plus operator' (for ease of googling).
var num = +variant;
So in front of a function it can be a way to force the function's result to be interpreted as a number. I doubt it happens yet, but theoretically the JIT could use that to compile the function as a numerical-only function etc. However, to prevent the unary plus being a concatenation when used in a larger expression, you would need parentheses:
blah + (+(function(){ var scope; return "4"; })());
So the short answer is that it prevents a syntax error, by using the function results in one way or another.
You can also instruct the engine that you're not even interested in the return value by using the void operator:
void function() { console.log("Foo!"); }();
Of course, putting braces around the whole thing also serves that purpose.
TL;DR (Quick Answer)
Plus Sign Casts (Converts) the proceeding operand to a Number if it isn't already.
Solution & Origins
The + sign before the function, actually called Unary plus and is part of a group called a Unary Operators and (the Unary Plus) is used to convert string and other representations to numbers (integers or floats).
A unary operation is an operation with only one operand, i.e. a single
input. This is in contrast to binary operations, which use two
operands
Basic Uses:
const x = "1";
const y = "-1";
const n = "7.77";
console.log(+x);
// expected output: 1
console.log(+n);
// expected output: 7.77
console.log(+y);
// expected output: -1
console.log(+'');
// expected output: 0
console.log(+true);
// expected output: 1
console.log(+false);
// expected output: 0
console.log(+'hello');
// expected output: NaN
When the + sign is positioned before a variable, function or any returned string representations the output will be converted to integer or float; the unary operator (+) converts as well the non-string values true, false, and null.
Advanced Uses
The right way to use the function you mentioned above will be:
+function(){return "3.141"}()
// expected output: 3.141
I love to use + to turn a new Date() object to a timestamp, like this:
+new Date()
// expected output: 1641387991035
Other Unary Operators
- The unary negation operator converts its operand to Number type
and then negates it.
~ Bitwise NOT operator.
! Logical NOT operator.
delete The delete operator deletes a property from an object.
void The void operator discards an expression's return value.
typeof The typeof operator determines the type of a given object.

Categories

Resources