Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this javascript syntax?

Tags:

javascript

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

like image 585
switz Avatar asked Oct 18 '14 18:10

switz


People also ask

What is JavaScript syntax example?

Your First JavaScript CodeThe comment ends with a "//-->". Here "//" signifies a comment in JavaScript, so we add that to prevent a browser from reading the end of the HTML comment as a piece of JavaScript code. Next, we call a function document. write which writes a string into our HTML document.

What is '$' in JavaScript?

Updated on July 03, 2019. The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.

What is the syntax of JavaScript value?

JavaScript Values The JavaScript syntax defines two types of values: Fixed values and variable values. Fixed values are called literals. Variable values are called variables.

Why do we use this in JavaScript?

“This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function. If the function being referenced is a regular function, “this” references the global object.


1 Answers

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()
like image 159
thefourtheye Avatar answered Oct 10 '22 04:10

thefourtheye