How [1,2] + [4,5,6][1] = 1,25 in JavaScript [duplicate] - javascript

This question already has answers here:
Why is [1,2] + [3,4] = "1,23,4" in JavaScript?
(14 answers)
Closed 7 years ago.
I got this question from Interview,
[1,2] + [4,5,6][1]
JavaScript giving answer 1,25.
How it's happening? Please explain clearly.

Lets start with the last part and write it more verbose
var arr = [4,5,6];
var value = arr[1];
Is the same as
[4,5,6][1]
and as arrays are zero based, that gives 5, so we really have
[1,2] + 5;
The first part is equal to
[1,2].toString(),
and that returns the string "1,2" because the array is converted to a string when trying to use it in an expression like that, as arrays can't be added to numbers, and then we have
"1,2" + 5
Concatenating strings with numbers gives strings, and adding the strings together we get
"1,25"

It breaks down like this:
Starting with:
[1,2] + [4,5,6][1]
First, each side gets evaluated, and since the right-hand side is an array initializer and lookup, it comes out to 5:
[1,2] + 5
Now the + operator starts its work. It isn't defined for arrays, the first thing it does is try to convert its operands into either strings or numbers. In the case of an array, it'll be a string as though from Array#toString, which does Array#join, giving us:
"1,2" + 5
When you use + where either side is a string, the result is string concatenation.

First, [4,5,6][1] evaluates to the number 5
Then, the + operator is being applied to a first argument which is an Array and not a Number, so javascript assumes you're doing a string concatenation, not addition. Your array [1,2] becomes a string, which is "1,2". You can see this yourself with [1,2].toString().
The number 5 is now being appended to a string, so it to gets converted to a string, and appended together to get "1,25".

Related

Addition of two strings gives unintended result [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 3 years ago.
I would like to get a numeric value in a string which is in the format 1 111.
I used a regex to extract it:
([0-9]*)\s([0-9]*)
then I thought that I will obtain the correct result with this operation:
regex_result[1]*1000+regex_result[2]
But actually I just have to addition them and I do not understand why.
var str= "Bit rate : 5 333 kb/s"
var bitrate= str.match(/Bit\srate\s*:\s([0-9]*)\s([0-9]*)\s/);
console.log(bitrate);
//attempted result, but incorrect code
console.log(bitrate[1]+bitrate[2]);
//attempted correct code, but wrong result
console.log(bitrate[1]*1000+bitrate[2]);
Here, the second captured group just so happens to be 3 characters long, so multiplying the first captured group by 1000 and adding it to the second group will just so happen to produce the same result as plain concatenation.
But you have to add them together properly first. Your second attempt isn't working properly because the right-hand side of the + is a string, and a number + a string results in concatenation, not addition:
var str = "Bit rate : 5 333 kb/s"
var bitrate = str.match(/Bit\srate\s*:\s([0-9]*)\s([0-9]*)\s/);
console.log(bitrate[1] * 1000 + Number(bitrate[2]));
If the input isn't guaranteed to have exactly 3 digits in the second capturing group, the concatenation method won't work.
You can parse them as ints instead of manipulating strings
var str= "Bit rate : 5 333 kb/s"
var bitrate= str.match(/Bit\srate\s*:\s([0-9]*)\s([0-9]*)\s/);
console.log(bitrate);
console.log(parseInt(bitrate[1] * 1000) + parseInt(bitrate[2]));

Post incrementing a string in javascript [duplicate]

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;

Unexpected result when using the subtraction operator with string values in Javascript [duplicate]

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.

Type of message in javascript window alert

I am trying to alert the following,
1. alert(1+1+1+1+1);
//output: 5
2. alert('1'+1+1+1+1);
//output: 11111
3. alert(1+1+1+1+'1');
//output: 41
4. alert(1+1+'1'+1+1);
//output: 2111
Does anyone can explain about the type of message in alert ?
Thank you in Advance.
Alright so in javasciprt, number + number + number = number (Your case 1)
Whereas, a number after string concatenates with the String, and results in a string as output '1'+1 = '11' + 1 = '111' and so on. (Your case 2)
In the third case, the string just comes at the end of the number which get's casted to string and result will simply be number followed by string in string form.. 2+'432' = '2432'.
Last case is the mix of all the above 1+1 = 2 + '1' = '21'+1 = '211'+1 = '2111'.
Javascript is a weakly typed language with operator overloading. That is why you are getting those 'strange' behaviours.
Wow, operator overloading. huh?
The + in javascript has multiple functions. One being: adding up numbers and another one is concatenating strings together. this is called operator overloading. compared to PHP, adding up numbers is + but concatenating strings is .
The big problem with operator overloading is. What if we have String + Number. Or Number + String ?
Different rules apply:
1+1+1+1+1
This is easy, adding up 5 numbers.
'1'+1+1+1+1
This is harder one. What he sees is a String, so he concatenates it with the next part (the 2nd 1). Then he continues. String(11) + 1, gives String(111) and so on.
The 3rd example is fun. he starts adding up all the numbers, untill he reaches the last + sign. And it no has Number(4) + String(1). So he converts the Number to a string and Concatenates them together.
Same goes for the last example. If one of the two is a String, the + sign is interpreted as a Contatenation.
I was reading w3school's Automatic type conversion and I think this is relevant from your question.
It says:
When JavaScript tries to operate on a "wrong" data type, it will try to convert the value to a "right" type.
It says that the result is not always what you expect:
5 + null // returns 5 because null is converted to 0
"5" + null // returns "5null" because null is converted to "null"
"5" + 1 // returns "51" because 1 is converted to "1"
"5" - 1 // returns 4 because "5" is converted to 5

Javascript: array plus number [duplicate]

This question already has answers here:
What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012?
(5 answers)
Closed 9 years ago.
Some operations in javascript returns unexpected results. One is extremely strange:
[] + 1 = "1"
Can anybody explain why it works like that?
[] are converted to an empty string due to + operator. so "" + 1 => "1" (number converted to string too)
Javascript's rules for addition between differeent types are as follows:
Given the following addition.
value1 + value2
To evaluate this expression, the following steps are taken (§11.6.1):
Convert both operands to primitives (mathematical notation, not JavaScript):
prim1 := ToPrimitive(value1)
prim2 := ToPrimitive(value2)
PreferredType is omitted and thus Number for non-dates, String for dates.
If either prim1 or prim2 is a string then convert both to strings and return the concatenation of the results.
Otherwise, convert both prim1 and prim2 to numbers and return the sum of the results.
Source
In this case the array gets converted to an empty string, and then the + performs string concatenation
ECMAScript 11.6.1 defines addition. Steps 5 and 6 of addition call ToPrimitive (9.1) for each operand and operate on those results:
For an array (or any object), ToPrimative calls the toString method of the object. The result of calling toString on an empty array is the empty string (per the behavior described in 15.4.4.2.
For a number, ToPrimitive returns the number (since numbers are already primitive).
We're left adding the empty string and the number 1. When either operand in addition is a string, the addition acts as a concatenation operation (per addition's step 7), so we end up with "" + "1" = "1".

Categories