This question already has answers here:
Javascript ++ vs +=1
(3 answers)
Closed 5 years ago.
I was going through exercise problem from Stoyan stefanov book named Object oriented Javascript.
Problem :
var s = 'ls';
s++;
When I execute this in chrome, I get NaN.
For the same code above if I do
var s = 'ls';
s = s+1;
I get output as ls1
Can anyone please explain the reason behind it?
++ tries to convert x as number first. Hence failed because x is having string value and return NaN.
When you do ++ its attempting to increment a number. When you use the + sign, it's either adding or concatenating. Its "smart" and see's that s is a string, so it concatenates it with 1. With ++, you can't increment a string so you get NaN (Not a number)
s++ is an increment operation which is commonly performed for numbers hence the output nan( not a number). In the second case you are doing a concatenation operation. So the ‘ls’ + 1 gives ‘ls1’.
You can't increment strings via ++. That operator is reserved exclusively for the number primitive. Instead Try:
var s = 'ls';
s += 1;
console.log(s);
The above is syntactic sugar for what you originally posted (string concatenation):
s = s + 1;
Related
Why does the following snippet of code convert my variable of type string to type number?
let stringInteger = '42';
let convertToInteger = +stringInteger;
console.log(typeof convertToInteger)
More specifically, why does prefixing + to the variable have this effect? Note, I'm asking why not what it does.
It's the Unary Plus Operator.
Your question is answered here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus_()
It's called a Unary Plus operator. It basically tries to convert non-integer variables into integers (ie +'true' and +'false' can be 1 and 0). You can read more about it on MDN and you can read more about the differences between this and other ways to parse integers in js here.
This question already has answers here:
Why does JavaScript handle the plus and minus operators between strings and numbers differently?
(7 answers)
Closed 5 years ago.
Why does Javascript give an output of 0 when I use the odd operator?
What is the difference between subtraction and addition with a string?
var x = 1;
console.log(x+'1') // Outputs 11
console.log(x-'1') // Outputs 0 -- but why?
So how can I do mathematical calculations?
The + operator has one of two three meanings in javascript. The first is to add numbers, the second is to concatenate strings. When you do 1 + '1' or '1' + 1 the operator will convert one operand that is not a string to a string first, because one other operand is already evaluated to be a string. The - operator on the other hand has just one purpose, which is to subtract the right operand from the left operand. This is a math operation, and so the JS engine will try to convert both operands to numbers, if they are of any other datatype.
I'm not sure though why typecasting to strings appears to have precedence over typecasting to numbers, but it obviously does.
(It seems to me the most likely that this is a pure specification decision rather than the result of other language mechanics.)
If you want to make sure that the + operator acts as an addition operator, you can explicitly cast values to a number first. Although javascript does not technically distinguish between integers and floats, two functions exist to convert other datatypes to their number equivalents: parseInt() and parseFloat() respectively:
const x = 10;
const result = x + parseInt('1'); // 11
const y = 5;
const result2 = y + parseFloat('1.5'); // 6.5
const result3 = y + parseInt('1.5'); // 6
Edit
As jcaron states in the comment below, the + operator has a third meaning in the form of an unary + operator. If + only has a right operand, it will try to convert its value to a number almost equivalent as how parseFloat does it:
+ '1'; // returns 1
+ '1.5'; // returns 1.5
// In the context of the previous example:
const y = 5;
const result2 = y + +'1.5'; // 6.5
Dhe difference with parseFloat is that parseFloat will create a substring of the source string to the point where that substring would become an invalid numeric, whereas unary + will always take the entire string as its input:
parseFloat('1.5no-longer-valid'); // 1.5
+ '1.5no-longer-valid'; // NaN
That is because + is a concatenation operator. So javascript considers it to be a concatenation operator rather than a mathematical operator.But it is not the case with / ,* ,/ etc.
This happens because + its also used to concatenate strings. Then, JS always will find the better way to make the correct typecasts basing on types. In this case, the x+'1' operation, will be identified as string type + string type.
Otherwise, x-'1', will become int type - int type.
If you want to work with specific types, try to use type cast conversions, link here.
This question already has answers here:
Evaluating a string as a mathematical expression in JavaScript
(26 answers)
Closed 7 years ago.
Hey guys i want to extract/evaluate the answer 2/4 in a string even ehen doing Number ("2/4") it gives me NaN as a result which is fairly reasonable! So my question is how can i evaluate this fraction from a string?
You can do eval("2/4"), which will properly result in 0.5.
However, using eval is a really bad idea...
If you always have a fraction in format A/B, you can split it up and compute:
var s = "11/47";
var ssplit = s.split('/');
document.body.innerText = ssplit[0] / ssplit[1];
Note that Division operator / will implicitly cast strings "11" and "47" to 11 and 47 Numbers.
You are looking for eval. Note
parseFloat("2/4")
2
parseFloat("4/2")
4
eval("4/2")
2
eval("2/4")
0.5
function myFunction() {
var str = "3/4";
var res = str.split("/");
alert(parseFloat(res[0]/res[1]));
}
Try with eval function :
eval("2/4");
Parsing the string only valid for numbers like 0-10 and a decimal (.) and all other if included will then result in NaN.
So, what you can do is like this:
Number(2/4)//0.5
parseFloat(2/4)//0.5
Number('2')/Number('4');//0.5
parseFloat('2')/parseFloat('4');//0.5
Number('2/4');//NaN as / is not parsable string for number
parseFloat('2/4');//2 as upto valid parsable string
parseFloat('1234/4');//1234
So, you can split string then use that like #Yeldar Kurmangaliyev answered for you.
(function(str){
var numbers = str.split("/").map(Number);
return numbers[0] / numbers[1];
})("2/4")
Keep in mind this does not check for invalid input.
This question already has answers here:
Javascript concatenating numbers, not adding up
(3 answers)
Closed 7 years ago.
var tt = gas+0.1
document.write (vartt);
Duplicate
You could make use of Number function too.
var tt = Number(gas) + 0.1;
document.write(tt);
The user entered a string. If you want to do arithmetic with it instead of string concatenation, you must convert to a number. There are many different ways to do that including parseInt(gas, 10), parseFloat(gas), Number(gas) and +gas:
Here's one implementation:
var tt = parseFloat(gas) + 0.1;
document.write(tt);
Also, your document.write() statement was not correct either. The variable name is just tt, not vartt.
Unless you are using <input type="number" /> for the input, the user provided data will be a string. By default, when you try to add a string + a number it will cast that number to a string. You can do what Видул Петров suggested and add the unary + to gas to force cast it to a number, however if it's still a string that can't be cast to a number (like someone entering in the word 'five' vs '5'), youll get NaN as a result unless you have the proper control over the incoming data.
This question already has answers here:
Coerce to number
(4 answers)
Closed 9 years ago.
Going though the asm.js documentation I've observed this strange (to me at least, quite new to JS) snippet all over the sample code:
function test(x) {
x = +x; // THIS
...
return +(x*y);
}
What is the purpose of the + on the first line?
Its simply used for casting a value with another type to number. Additonally it will return NaN if the value after that + symbol could not get converted into a number.
FIDDLE
From the book Javascript and Jquery - The Missing Maunal
var numOfShoes = '2';
var numOfSocks = 4;
var totalItems = +numOfShoes + numOfSocks;
Adding a + sign before a variable (make sure there’s no space between the two) tells
the JavaScript interpreter to try to convert the string to a number value—if the string
only contains numbers like “2”, you’ll end up with the string converted to a number.
In this example, you end up with 6 (2 + 4). Another technique is to use the Number()
command like this:
var numOfShoes = '2';
var numOfSocks = 4;
var totalItems = Number(numOfShoes) + numOfSocks;
Number() converts a string to a number if possible. (If the string is just letters and not
numbers, you get the NaN value to indicate that you can’t turn letters into a number.)
Perhaps I am reading this wrong but from the specs http://asmjs.org/spec/latest/#parameter-type-annotations
is that casting it as a double?