The + + operator in javascript - javascript

When I have one plus, I get the wrong answer e.g.
var b = [069];
var total = 0;
total = total + b
console.log(total) // total = 069
However, when I add a second plus so the equation looks like this
total = total + + b // total = 69
I get the correct answer of 69. The above is just a simplified example of my issue.
This works fine, however whilst using JSHint I get a warning saying
confusing pluses
How can I get the correct answer without using the + + ? Also, what is this operator called?

Javascript unfortunately does a lot of implicit conversions... with your code
b + [69]
what happens is that [69] (an array containing the number 69) is converted to a string, becoming "69". This is then concatenated to b that also is converted in this case to a string "0". Thus the result "069".
If however you add another unary + in front of the array the string gets converted back to a number and you get a numeric result added to b.
0 + [69] → 0 + "69" → "0" + "69" → "069"
0 + + [69] → 0 + + "69" → 0 + 69 → 69
Exact rules are quite complex, but you can be productive with Javascript just considering the simplified form that for binary +:
if both are numbers the result is numeric addition
otherwise they're converted both to string and result is concatenation
One thing that is somewhat surprising is that implicit conversion of an array to a string is just the conversion of elements to string adding "," between them as separator.
This means that the one-element array [1] is converted to "1"... and implies apparently crazy consequences like [1] == 1.

Posting my comment as an answer
+ in front of a variable would cast it to a number if I'm correct.
Try this in your console:
"5" would return "5" (string), where
+"5" would return 5 (number).
You could use total = parseInt(total) + parseInt(b); to get a correct result, as parseInt() would try to make a number out of any input parameter it gets.
Theoritecally, you could just parse the total as a number, but it would be prone to an error like "1" + "0" = "10" resulting in 10, which should mathematically be 1.

Related

Why it only add the number with += and not +

I am learning to code and trying out some JavaScript programming and came across this which I don't understand. Please help!
I don't understand why it wouldn't add the number with '+' but does with '+='.
let number = 10;
number + 10; //Return 10
number += 10; //Return 20
console.log(number);
There is an important distinction to make between and expression and an instruction. An expression evaluates to a value, but doesn't necessarily have an effect. An instruction doesn't necessarily evaluate to a value, but has some effect.
In your example, number + 10 is an expression that evaluates to 20. But it has no effect by itself.
By contrast, number += 10 is an instruction that modifies the value of variable number.
Note that number += 10 is essentially equivalent to number = number + 10.
The last line in your code, console.log(number), is also an instruction: it prints the value of number.
Have you tried the instruction console.log(number + 10)?
'+=' operator come from C language
and it's a shortcut for
number = number + 10
so in your code all works,
but number + 10 is just operation without assignment;
The line number + 10 will calculate the value but you need to assign this value to the variable (to store it in the variable).
Indeed, you need to write number = number + 10.
About the syntax += : It only makes the code easier to read, the two following make exactly the same thing :
number = number + 10
number += 10
For more informations Addition assignment

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

Numbers are concatenated instead of added together

I need the two numbers to be added but somehow they are concatenated. Where am I doing it wrong?
var a;
var b;
var parsedInta;
var parsedIntb;
a=window.prompt("enter your first number");
b=window.prompt("enter your second number");
parsedInta=parseInt(a);
parsedIntb=parseInt(b);
alert("The Sum is" + parsedInta+parsedIntb);
It concatenates the result rather than addition.
You have to introduce parentheses to force the numeric addition to happen before the alert string is built:
alert("The Sum is " + (parsedInta + parsedIntb));
Without the parentheses, the + operator is naturally left-associative, so the first "addition" carried out is the string concatenation between "The Sum is" and the first value (which is treated as a string).
edit — note that the + operator prefers string concatenation over numeric addition. If either operand of + is a string, then the other operand is converted to a string and the two are concatenated.
This is beacuse the + operator is used also to do string concatenation. Since in your "The Sum is" + parsedInta+parsedIntb you are working with a string the language thinks you want to use parseinta and parseintb as strings.
You can solve by simply doing the sum before the string creation:
var sum = parseInta + parseIntb;
alert("The Sum is" + sum);
Or also by using parseInt directly in the sum line:
var sum = parseInt(a) + parseInt(b);
alert("The Sum is" + sum);
The probleme is that you are doing implicit type casting using "+" operator which will convert the number to string so your code will be like :
alert("the sum is "+number1+number2); //The number 1 will be converted to a string
,the same for the second number
So if i enter 10 in the first prompt and 10 in the second prompt the alert will show : the sum is 1010 because the first 10 is converted to a string and the second 10 will be converted to a string
But if i use parenthese like :
alert("the sum is "+(number1+number2));
Here the two number will be added and it will be coverted to a string after the addition.
P.S : don't use window object because it's a global object so you can ignore it
And sorry for my bad english i hope that you will understand
This is JavaScript. Don't expect the language to make sense.
This is because the + operator is overloaded for strings. If either of its operands is a string, + will turn the other operand into a string and concatenate them.
Since this awful operator is also left-associative, you will get
("The Sum is" + parseInta) + parsedIntb
which is a string plus a number (which is a string) plus a number, which is also a string.
Parenthesize the rightmost addition instead:
alert("The Sum is" + (parsedInta + parsedIntb));
And maybe consider starting to learn programming with a sane language.

Javascript String to int conversion

I have the following JS immbedded in a page:
var round = Math.round;
var id = $(this).attr("id");
var len = id.length;
var indexPos = len -1; // index of the number so that we can split this up and used it as a title
var pasType = id.substring(0, indexPos); // adult, child or infant
var ind = round(id.substring(indexPos)); // converts the string index to an integer
var number = (id.substring(indexPos) + 1); // creates the number that will go in the title
window.alert(number);
id will be something like adult0, and I need to take that string and split it into adult and 0 - this part works fine.
The problem comes in when I try to increment the 0. As you can see I use Math.round to convert it to an integer, and then add 1 to it - I expect 0 to be 1 after this. However, it doesn't seem to be converting it to integer, because I get 01, not 1. When testing this with adult1 the alert I get is 11.
I'm using this question for reference, and have also tried var number += id.substring(indexPos);, which breaks the JS (unexpected identifier '+=')
Does anyone know what I'm doing wrong? Is there a better way of doing this?
The parseInt() function parses a string and returns an integer,10 is the Radix or Base
[DOC]
var number = parseInt(id.substring(indexPos) , 10 ) + 1;
This is to do with JavaScript's + in operator - if a number and a string are "added" up, the number is converted into a string:
0 + 1; //1
'0' + 1; // '01'
To solve this, use the + unary operator, or use parseInt():
+'0' + 1; // 1
parseInt('0', 10) + 1; // 1
The unary + operator converts it into a number (however if it's a decimal it will retain the decimal places), and parseInt() is self-explanatory (converts into number, ignoring decimal places).
The second argument is necessary for parseInt() to use the correct base when leading 0s are placed:
parseInt('010'); // 8 in older browsers, 10 in newer browsers
parseInt('010', 10); // always 10 no matter what
There's also parseFloat() if you need to convert decimals in strings to their numeric value - + can do that too but it behaves slightly differently: that's another story though.
Convert by Number Class:-
Eg:
var n = Number("103");
console.log(n+1)
Output: 104
Note:- Number is class. When we pass string, then constructor of Number class will convert it.
JS will think that the 0 is a string, which it actually is, to convert it to a int, use the: parseInt() function, like:
var numberAsInt = parseInt(number, 10);
// Second arg is radix, 10 is decimal.
If the number is not possible to convert to a int, it will return NaN, so I would recommend a check for that too in code used in production or at least if you are not 100% sure of the input.
Although parseInt is the official function to do this, you can achieve the same with this code:
number*1
The advantage is that you save some characters, which might save bandwidth if your code has to lots of such conversations.
Use parseInt():
var number = (parseInt(id.substring(indexPos)) + 1);` // creates the number that will go in the title
If you are sure id.substring(indexPos) is a number, you can do it like so:
var number = Number(id.substring(indexPos)) + 1;
Otherwise I suggest checking if the Number function evaluates correctly.

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