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

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

Related

What is the behavior of "+ +" (plus-space-plus) in JavaScript? [duplicate]

An interesting thing I've never seen before was posted in another question. They had something like:
var i = + +1;
They thought the extra + converted it to a string, but they were simply adding to a string which is what caused it to convert.
This, however, lead me to the question: what is going on here?
I would have actually expected that to be a compiler error, but JavaScript (at least in Chrome) is just fine with it... it just basically does nothing.
I created a little JSFiddle to demonstrate: Demo
var i = 5;
var j = + +i;
document.body.innerHTML = i === j ? 'Same' : 'Different';
Anyone know what's actually occurring and what JavaScript is doing with this process?
I thought maybe it would treat it like ++i, but i doesn't increment, and you can even do it with a value (e.g., + +5), which you can't do with ++ (e.g., ++5 is a reference error).
Spacing also doesn't affect it (e.g., + + 1 and + +1 are the same).
My best guess is it's essentially treating them as positive/negative signs and putting them together. It looks like 1 == - -1 and -1 == + -1, but that is just so weird.
Is this just a quirky behavior, or is it documented in a standard somewhere?
Putting your the statement through the AST Explorer, we can see that what we get here is two nested Unary Expressions, with the unary + operator.
It's a unary expression consisting of + and +i, and +i is itself a unary expression consisting of + and i.
The unary expression with the unary + operator, will convert the expression portion into a number. So you're essentially converting i to a number, then converting the result of that to a number, again (which is a no-op).
For the sake of completion, it works on as many levels as you add:
var i = 5;
console.log(+ + + + + +i); // 5
console.log(i); // still 5
It's in the specification.
Digging through, we can see from §14.6.2.2 that the increment and decrement operators are listed before (and should be preferred) over the unary operators. So precedence alone won't explain this.
Looking up the the punctuation table in §11.7, we can see that every single instance of ++ (the operator) in the spec shows the two together, without whitespace. That's not conclusive, until you check...
The whitespace rules in §11.2, specifically:
White space code points may occur within a StringLiteral, a RegularExpressionLiteral, a Template, or a TemplateSubstitutionTail where they are considered significant code points forming part of a literal value. They may also occur within a Comment, but cannot appear within any other kind of token.
JS does not allow arbitrary whitespace mid-operator.
The JS syntax in both PegJS and Esprima corroborate this, matching on the literal two-character string ++.
For me it's very clear;
var a = +3;
var b = +a; // same as a, could be -a, for instance
var c = + +a; // same as above, same as +(+a)
If you do ++variable the javascript interpreter sees it as the increment operator.
If you do + +variable the javascript interpreter sees it as Unary plus, coercing the value to a number, twice.
So
var a = 1;
var b = +a;
var c = +b;
console.log(c);// still 1
is the same as
var c = + +1;
So the simple answer is that two plus signs can not be separated by a space to be interpreted as incrementation, the space makes it so the interpreter sees two seperate spaces, which is what it really is
The + operators converts into a number, two + operators with a space in between does nothing additional.
Even though it might look very similar, + + and ++ are not at all the same thing for an AST interpreter. The same applies to token separation: varfoo is not the same as var foo.
In the expression + + +i, each + is considered as distinct unary operator, which simply convert your variable to a number. For the incrementation operation, which is ++, no spaces are allowed, neither between the + and the variable token. In the example below, the last line is not valid:
var x = "4";
console.log(+ + +x);
console.log(+ + ++x);
console.log(+ ++ +x);

The + + operator in 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.

Why plus sign in front of JavaScript equation with toFixed?

I was just going through the source code of particles.js and came across the following line of code:
this.speed.x = +((-options.maxSpeedX / 2) +
(Math.random() * options.maxSpeedX)).toFixed(2);
That line of code can be found HERE too.
Now the + sign right at the beginning of the expression has no difference in the equation. E.g.
(-2 + 5) = 3
Now...
+(-2 + 5) = 3
Another example:
(-5 + 2) = -3
Now..
+(-5 + 2) = -3
Why the plus sign at the beginning of the expression when it makes no difference to the outcome of the equation?
Your code is basically
x = +someNumber.toFixed(2);
Which is
x = +(someNumber.toFixed(2));
because the function call has a higher precedence than the + operator.
This makes
x = +(someNumberFormattedAsARoundedString);
Applying the unary plus operator converts the string back to a number. The net result is the rounding of the initial someNumber.
In this specific case you linked to, this looks like bad practice due to ignorance of what is a IEEE754 floating point number. It looks like the author tried to get fixed precision numbers, thus confusing the number storage and their representation (i.e. formatting).
.toFixed() returns a String. You need to cast it to Number. The unary plus + operator is used to convert/cast the string to number.
Returns
A string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If numObj is greater than 1e+21, this method simply calls Number.prototype.toString() and returns a string in exponential notation.
It is not required in the cases when the result is already a number. Example, +(-2 + 5).
However, in below operation it is required.
this.speed.x = +((-options.maxSpeedX / 2) +
(Math.random() * options.maxSpeedX)).toFixed(2);

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.

Categories