convert the literal value with parentheses [duplicate] - javascript

This question already has answers here:
Calling member function of number literal
(3 answers)
Closed 3 years ago.
I'm new to Javascript, and I saw code like this:
var myData1 = (5).toString() + String(5);
and the author says he placed the numeric value in parentheses and then called the toString method. This is because you have to allow JavaScript to convert the literal value into a number before you can call the methods that the number type defines.
I'm confused, isn't that 5 is already a number, why 5 needs be converted as (5) to be a number?

The author is partly right. This has nothing todo with turning the literal into a number, this is just about a syntactical distinction: The. can either be used to express fractional numbers (1.1) or it can be used for property access (obj.prop). Now if you'd do:
1.toString()
that would be a syntax error, as the dot is treated as a number seperator. You could do one of the following to use the property access dot instead:
1.0.toString() // as the first dot is the number seperator already, the second dot must be property access
1..toString() // same here
(1).toString() // the dot is clearly not part of the number literal

Related

user. and number later [duplicate]

This question already has answers here:
Can I get a javascript object property name that starts with a number?
(2 answers)
Closed 8 years ago.
I've got an object where one of the properties starts with a number. I've read that this was allowed, but I'm getting this error:
SyntaxError: identifier starts immediately after numeric literal
var stats = {"LOAD_AVG":{"1_MIN":0.08,"5_MIN":0.08,"15_MIN":0.08},"COUNTS":{"TOTAL":888,"RUNNING":1,"SLEEPING":887,"STOPPED":0,"ZOMBIE":0},"CPU":{"USER_CPU_TIME":8.9,"SYSTEM_CPU_TIME":2.4,"NICE_CPU_TIME":0,"IO_WAIT_TIME":1,"HARD_TIME":0,"SOFT_TIME":0.1,"STEAL_TIME":0},"MEMORY":{"PHYSICAL":{"TOTAL":"3921.98mb","IN_USE":"3682.652mb (93.9%)","AVAILABLE":"239.328mb (6.1%)","BUFFERS":"266.492mb (6.8%)"},"SWAP":{"TOTAL":"4194.296mb","IN_USE":"64.264mb (1.5%)","AVAILABLE":"4130.032mb (98.5%)","CACHE":"1191.328mb (28.4%)"}}};
//works fine
window.alert(stats.COUNTS.TOTAL);
//doesn't work
window.alert(stats.LOAD_AVG.1_MIN);
Here's a fiddle.
How can I access the properties that begin with a number without rewriting the PHP that generated it?
You can use bracket access for properties that aren't valid JavaScript identifiers, that goes for property names with spaces or other language symbols like +, *
window.alert(stats.LOAD_AVG["1_MIN"]);
You can use bracket access anywhere really
window.alert(stats["COUNTS"]["TOTAL"]);

eval() function in java script throwing error with direct value [duplicate]

This question already has answers here:
Why can't I access a property of an integer with a single dot?
(5 answers)
Closed 4 years ago.
I tried to evaluate string function toString() in console.
In one scenario it is working fine and in another scenario it is not working as expected.
Scenario 1:
eval(99.toString());
output:
Invalid or unexpected token ...
Scenario 2:
var a = 99;
eval(a.toString());
Output:
99
Please help me to understand the difference between both the scenarios.
That has nothing to do with eval.
The error is produced by 99.toString. The reason is that 99. is read as a number (equivalent to 99.0) and then toString is just a random word that doesn't fit the syntax:
99.0 toString // what the parser sees
To fix it, you need to keep . from being treated as part of the number. For example:
99 .toString() // numbers can't contain spaces, so '99' and '.' are read separately
(99).toString() // the ')' token prevents '.' from being read as part of the number
99.0.toString() // '99.0' is read as a number, then '.toString' is the property access
99..toString() // same as above, just with '99.' as the number
99['toString']() // using [ ] for property access, no '.' at all
A numeric literall (99) is not and object with properties. A variable with value 99 like var x = 99 is and object and you can use methods like x.toString()
eval expects a script input (string), in example:
var x = eval('var a = 99; a.toString()');
console.log(x);

Call method directly on number [duplicate]

This question already has answers here:
Why can't I access a property of an integer with a single dot?
(5 answers)
Closed 4 years ago.
I recently implemented a very simple method to extend the base JavaScript Number Class and tried to call it directly on an entered number in the browser console.
123.myMethod();
But it is not working as expected, it only says: "Invalid or unexpected token"
I was unsure, if I can call Number Methods directly on entered numbers, so I tried standard methods like .toFixed():
123.toFixed(1);
But this also isn't working.
Only if I write a float, I can call Number methods:
123.0.toFixed(1);
It also works, if I put the Integer inside brackets:
(123).toFixed(1);
So my question is:
Why are Integers not implicitly casted to Number and why can't I use Number methods on them?
The . tells the JavaScript interpreter to be a decimal point, so it is expecting more numbers. In JavaScript there is only floats, no integers.

whats the difference between string literals, and just a string? [duplicate]

This question already has answers here:
What is the difference between string primitives and String objects in JavaScript?
(12 answers)
Closed 4 years ago.
I’m studying JavaScript and this is a statement I came across:
new String("Hello");
This will create a new string that is the same as string literal "hello", although it will be classed as an object rather than a primitive values. For this reason it is preferable to use the string literal notation.
What is a String literal?
Why is new String("Hello") classed as Object?
A literal string (or literal <any data type>) means that you just reference the data directly.
For example
"Hello".length // returns 5
The "Hello" is a string literal since we are just referencing it "as-is".
You could do exactly the same thing with a string object:
var strObj = new String("Hello");
strObj.length // returns 5
These two examples are pretty much identical (for the sake of this example). Both create a string variable and measure it's length.
The first uses a string literal and the second uses a string object.
Here is another example using numbers - if you do a direct calculation such as:
5 + 2
you'll be using number literals - again, when you only reference the data directly, it is considered a "literal".

Why does a method like `toString` require two dots after a number? [duplicate]

This question already has answers here:
Why does 10..toString() work, but 10.toString() does not? [duplicate]
(3 answers)
Closed 5 years ago.
What is the logic behind 42..toString() with ..?
The double dot works and returns the string "42", whereas 42.toString() with a single dot fails.
Similarly, 42...toString() with three dots also fails.
Can anyone explain this behavior?
console.log(42..toString());
console.log(42.toString());
When you enter 42.toString() it will be parsed as 42 with decimal value "toString()" which is of course illegal. 42..toString() is simply a short version of 42.0.toString() which is fine. To get the first one to work you can simply put paranthesis around it (42).toString().
it is like 42.0.tostring() so it show's decimal point you can use (42).toString() 42 .toString() that also work there is space between 42 and dot. This is all because in javascript almost everything is object so that confusion in dot opt.
With just 42.toString(); it's trying to parse as a number with a decimal, and it fails.
and when we write 42..toString(); taken as 42.0.toString();
we can get correct output by
(42).toString();
(42.).toString();
Can refer Link for .toString() usage

Categories

Resources