Adding strings to numbers and numbers to strings - javascript

I tried something in my console that I don't quite comprehend.
If you add 2 + 3 + "hello" it concatenates to "5hello"
However, if you reserve this and add 'hello' + 2 + 3 it concatenates to 'hello23'
Why? My guess is because JavaScript looks at the first data type and tries to convert it to that type? Can someone elaborate on this?

Addition (and other associative operators) are processed in order, left-to-right. So
2 + 3 + "hello"
is like writing
(2 + 3) + "hello"
or
5 + "hello"
first the addition, then the conversion/concatenation. On the other hand,
"hello" + 2 + 3
is like:
("hello" + 2) + 3
which works out to
"hello2" + 3
or
"hello23"

Simple order of operations really:
2 + 2 + "hello" //2 + 2 is evaluated first, resulting in 4. 4 + "hello" results in "4hello";
"hello" + 2 + 3 //"hello" + 2 is evaluated first, turning the result to a string, and then "hello2" + 3 is done.

As I understand it, 2 + 2 + "hello" is evaluated this way:
Find any operators and push them on the operator stack: stack: +, +
Find any symbols and push them on the operand stack: stack: 2, 2, "hello"
Take the first operator from the operator stack and
the first 2 operands from the operands stack, do: 2 + 2 = 4
Take the first operator and the first 2 operands, do: 4 + "hello"
= "4hello"
Mind you, JS automatic type conversion works this way with the + operator (which is both addition and concatenation), it may (and does) work differently in other places. 4 - "hello" will make no sense and "0" == true will evaluate to false whereas 0 == '' stands. This is one of the reasons Javascript is one of the most beloved languages of today.

This occurs due to the coercion. Type coercion means that when the operands of an operator are different types, one of them will be converted to an "equivalent" value of the other operand type. The operand to take into account depends on the hierarchy of "data-type" (though JavaScript is typeless) and the operations are executed from left-to-right. For instance:
//from left to right
2 + 3 + "hello"
//performs the addition, then does coercion to "string" and concatenates the text
(2 + 3) + "hello"
this results in "5hello"
In counterpart
//from left to right
'hello' + 2 + 3
//string concatenation is the first, all subsequent values will do coercion to string
"hello23"
Unless you use parentheses, which takes higher precedence
'hello' + (2 + 3)
It returns "hello5"

Related

Javascript "+" and "-" operators behavior and usage [duplicate]

I don't understand why JavaScript works this way.
console.log("1" + 1);
console.log("1" - 1);
The first line prints 11, and the second prints 0.
Why does JavaScript handle the first as a String and the second as a number?
String concatenation is done with + so Javascript will convert the first numeric 1 to a string and concatenate "1" and "1" making "11".
You cannot perform subtraction on strings, so Javascript converts the second "1" to a number and subtracts 1 from 1, resulting in zero.
+ is ambiguous. It can mean "concatenate" or "add". Since one side is a string, it is taken to mean "concatenate", hence the result is 11 (which, by the way, was one of my favourite jokes as a young child. That and "1 + 1 = window", as shown visually: │┼│ ニ ⊞)
- however has only one meaning: subtract. So it subtracts.
This kind of problem is not present in other languages such as PHP, where "concatenate" is . instead of +, making no ambiguity. Still other languages like MySQL don't even have a concatenation operator, instead using CONCAT(a,b,c...).
Because the spec explicitly tells to do so.
Page 75. Note the difference between 11.6.1 steps 5-8 and 11.6.2 steps 5-7.
11.6.1 - describes how addition operator works
1-4. ...
5. Let lprim be ToPrimitive(lval).
6. Let rprim be ToPrimitive(rval).
7. If Type(lprim) is String or Type(rprim) is String, then
7a. Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
8. Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim)
11.6.2 - describes how subtraction operator works
1-4. ...
5. Let lnum be ToNumber(lval).
6. Let rnum be ToNumber(rval).
7. Return the result of applying the subtraction operation to lnum and rnum
Summary
In case of addition if any of the operands when converted to primitive value without any hints suddenly becomes a string the second one is converted to a string too. In case of subtraction both operands are converted to a number.
There is no dedicated string concatenation operator in JavaScript**. The addition operator + performs either string concatenation or addition, depending on the type of operands:
"1" + 1 // "11"
1 + "1" // "11"
1 + 1 // 2
There is no opposite of concatenation (I think) and the subtraction operator - only performs subtraction regardless of the type of operands:
"1" - 1 // 0
1 - "1" // 0
1 - 1 // 0
"a" - 1 // NaN
** The . operator in PHP and & operator in VB are dedicated string concatenation operators.
+ is both an addition operator for numeric variables, and a concatenation operator for strings.
Whenever there's a string after a +, Javascript will choose to use the + as a concatenation operator and convert (typed) as many terms as possible around the string so it can concatenate them. That's just the behaviour of Javascript. (If you tried console.log(23 + 2 + "." + 1 + 5 + "02" + 02);, you'll get the result 25.15022. The number 02 was typed into the string 2 before being concatenated.
- can only be a subtraction operator, so when given a string, it will implicitly change the type of the string "1" into a numeric 1; if it didn't do that, there's no way "1" - 1 would make sense. If you tried console.log(23 + 2 + 1 + 5 - "02" + 03); you'll get 32 - the string 02 gets converted into the number 2. The term after the - must be able to be converted into a number; if you tried console.log(23 - 2 - "." - 1 - 5 - 02 - "02"); you'll get NaN returned.
More importantly, if you tried console.log(23 + 2 + "." + 1 + 5 - "02" + 03);, it will output 26.15, where everything before - was treated as a string (because it contains a string ".", and then the term after the - is treated as a number.
According to the standard EcmaScript 262. The + and - operators behave differently when strings are involved. The first converts every value to a string. The second converts every value to a number.
From the standard:
If Type(lprim) is String or Type(rprim) is String, then Return the
String that is the result of concatenating ToString(lprim) followed by
ToString(rprim)
This rules implies that if in the expression there is a string value, all values involved in the + operation are converted to a string. In JavaScript when the + operator is used with strings, it concatenates them. This is why console.log("5"+1) returns "51". 1 is converted to a string and then, "5" + "1" are concatenated together.
Nevertheless, the above rule doesn't apply for the - operator. When you are using a - all values are converted to numbers according to the Standard (see below). Therefore, in this case, "5" is converted to 5 and then 1 is subtracted.
From the standard:
5 Let lnum be ToNumber(lval).
6 Let rnum be ToNumber(rval).
Operator definition from the standard EcmaScript 262.
Operator + : http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.1
Operator - : http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.2
Using plus and a string "" you basically return a string because you are performing a concatenation:
typeof ("" + 1 + 0) // string
typeof (1 + 0) // number
When using - instead you convert to a number as string concatenation is possible:
typeof ("" - 1 + 0) // number

Quoted value being treated as a integer [duplicate]

This question already has answers here:
The + + operator in javascript
(2 answers)
Closed 5 years ago.
Why does this statement 1+ +"2"+3 returning 6 in javascript?
console.log(1+ +"2"+3) // 6.
Between the two plus (+) operands there is a single space. Even though we have a quoted string it's treating the string as a number, which is confusing to me.
Can someone please explain this?
Because the + in +"2" coerces "2" to 2, thus you get 1 + 2 + 3, thus 6. The unary¹ + has higher precedence than the binary² + (e.g., it happens first). MDN has a reasonably good precedence chart here.
E.g., starting with 1 + +"2" + 3, then:
The +"2" part is done first, resulting in 2 because that unary + converts the string to number (the same way Number("2") would). So now we have 1 + 2 + 3.
1 + 2 is done next because the binary + operator (whether addition or concatenation) is left-to-right associative. So that gives us 3 and we have 3 + 3 left.
3 + 3 is done, giving us 6.
E.g.:
1 + +"2" + 3
1 + 2 + 3
3 + 3
6
¹ A "unary" operator is an operator accepting only one operand, e.g. the + in +"2" (where "2" is the operand)
² A "binary" operator is an operator accepting two operands, e.g. the + in 1 + 2 (where 1 and 2 are the operands)
(There are also "ternary" operators which accept three operands; JavaScript's only current ternary operator is the conditional operator: test ? result1 : result2)

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

Need help understanding the + operator in Javascript

Why is 1 + + + 1 = 2 in Javascript?
What is this behavior called? Is it documented somewhere?
Thanks.
It's because of the spacing. The unary operator + can be applied as many times as necessary, and so your expression becomes:
1 + (+(+1))
That is,
1 + 1
. Normally, it appears you can't do this, i.e. 1 + ++ 1 will fail, but that's because two +s are parsed as a prefix increment which is invalid when not used on a variable. In the same way, 1 +++ 1 fails because it's parsed as 1++ + 1, and you can't increment 1.
It's parsed as...
1 + (+ (+ 1))
...which obviously evaluates to two.

concatenation in javascript?

i want to concatenate two string in javascript i.e.
$('#bio').css('font-color', result.titlecolor);
but i want to put the character # before the result.titlecolor i.e.
$('#bio').css('font-color','#' result.titlecolor);
is this right or wrong? thanks
$('#bio').css('color','#' + result.titlecolor);
(Edited to reflect #BoltClock's comment about 'color' versus 'font-color'.)
This:
'#' result.titlecolor
needs to be:
'#'+ result.titlecolor
In javascript the + operator concatenates to strings together (but remember strings are immutable, so you are creating a new string when you use it). It will also allow you to contatenate a string and a non-string together into a string, such as a number and a string. So this "The answer is : " + 42 becomes "The answer is : 42" The tricky part comes in because if you try and concatenate to numbers together such as 14 + 08, you don't get "1408" it adds the two numbers together to become 22. Logically this makes sense on a simple example, but it can become troublesome when are concatenating variables together which are loosely typed.
$('#bio').css('font-color', '#' + result.titlecolor);
$('#bio').css('font-color','#' + result.titlecolor);
The + operator serves as both the addition operator and string concatenation operator in JavaScript. So:
1 + 1 // is 2
'The answer is: ' + 42 // is 'The answer is: 42'
'1' + '1' // is '11' (!!!)
'1' + 1
1 + '1' // are also '11' (!!!!!)
As for your code, the CSS specification defines color but not font-color, so this is what you want:
$('#bio').css('color', '#' + result.titlecolor);
As a side note, if you ever run into the '1' + '1' or 1 + '1' problem (e.g. you are taking a numeric value from a text box), you have to convert the operands to numbers using the unary plus operator or the parseFloat function:
+'1' + +'1' // is 2

Categories