Looking for a one line casting Number(oldValue) += 1; in JS - javascript

I'm creating totals for a row in a table with JavaScript. The cell values are typed as strings, so a += would concatenate a delta. Is there anything that lets me cast this value in one line, so I can still use += without saving the old value in a old = Number(value) in an extra lin of code?
row.totals.value += delta;
[string] [Integer]

I'm not certain you can +=, but you should be able to use this on one line:
row.totals.value = Number(rows.totals.value) + delta;

You can do it in the following way
let str = '123';
str = +str + 4;
console.log(str);

Unfortunately it won't be possible to do it without a casting of the LHS in conjunction with +=.
You'd also probably want to be using parseInt() or parseFloat() rather than Number(). Further reading.

Related

reversing a number in javascript (clarification)

I have a simple question to ask, in which I am slightly embarrassed to ask, but I realize that I won't learn unless I ask.
When looking at reversing a string, I recognize that reversing a string requires you to split up the string, reverse it, and then re-join it. Like so.
var stringReverse = function (n){
return n.split("").reverse().join("");
}
console.log(stringReverse("hello"));
However, I was trying to reverse a number, much of the principles were very similar except for one part. The code below is:
var reverse_a_number = function (n){
n = n + "";
return n.split("").reverse().join("");
}
console.log(reverse_a_number(32243));
My question is why am I needed to bring in the " n = n + " ";" to the code? I was assuming that the same principles would be similar regardless of it being a string, or an integer.
Much thanks in advance, and I apologize that this question is elementary.
why am I needed to bring in the " n = n + " ";" to the code?
Adding + "" will make a cast to String, this way you can use String functions (.split).
The integer have only functionality of a Number. If you want to treat the Number as a String you need to cast it (+ "") or convert it (.toString())
The .reverse() function come from Array object that is created when you use String function .split().
With .join() you come back to String from Array (of characters).
If you want to come back to Number after reverting, you can choose one of these functions.
To put it simply, the docs require it to be a string. You could combine your two methods by doing exactly what you're doing in reverse_a_number (it works for both). Also, don't be embarrassed to ask questions, it's how you learn :)
Number doesn't have reverse and split method directly and you should convert number to string that be able reverse it.
to convert it you can add an empty string after it, like you.
just it.
Javascript sets the type of a variable at runtime.
If she (yes, it's a girl) sees that you only have ciphers, she will consider it's an integer.
Adding + ""; casts it into a string, which is an array of chars.
Your string is stored a lil bit like : ['h', 'e', 'l', 'l', 'o']
an integer is stored as {0011001010101...}
Explanation
You are passing in a number, not a string. When you combine a number with a string ("") it assumes you want to make a string. So you are really converting it to a string. To an array, then back to a string. If you attempt to split a number, the compiler will throw an error. More exactly
TypeError: undefined is not a function (evaluating 'n.split('')')
So what you really are doing is making the number into a String. There are different methods you can use, take a look here.
n += '';(String) ->
.split() (Array) -> .split() (Array) -> .join() (String)
Your function is actually producing and returning a string
Alternative Function
I'm going to critique ;) , you could shorten, and improve this function using the following.
var reverse_a_number = function (n){
return +(n += "").split("").reverse().join("");
}
What does this do?
n = n + '' has a special operator, +=. We can shorten this to on-line by using this inside parenthesis. The + will convert it into a Integer
A number doesn't have the split method. You have to convert it into a string, which does have split.
You can use typeof to find out the type of a variable. The following code snippet demonstrates the types of a number and a string, and shows the value of the split attribute for each one. Note that split is undefined for the number.
var n = 42;
document.write(typeof n, '<br />', n.split, '<br />', '<br />');
var s = ''+n;
document.write(typeof s, '<br />', s.split);
If you want to reverse an integer by treating it as an integer, without using string operations, you can do the following.
function reverseInteger(n) {
var result = 0;
while (n != 0) {
var digit = n%10;
result = 10*result + digit;
n = (n-digit)/10;
}
return result;
}
var n = 3141590123456;
document.write(n, '<br />');
document.write(reverseInteger(n));
Note that the last digit of n is n%10. If we subtract the last digit and divide n by ten, the effect is to shift n one digit to the right. We keep doing this and build up result in reverse by multiplying it by ten on each iteration and adding the digit that we just removed from n.

Javascript is treating variables as Strings, why?

I have the variable y, which is a subtotal. Its value is different depending on what happens with the html, but throughout the script I declared it like this:
var y = 21.78;
etc. Why is it that on my last equation where I add up the total, it treats them as strings when I want to add the values?
var tax = (0.055*y).toFixed(2);
var totalprice = y+tax;
/* totalprice holds "21.781.20" instead of 22.98 */
According to:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number/toFixed
toFixed() returns:
A string representation of number that does not use exponential
notation and has exactly digits digits after the decimal place.
thus, y+tax is cast to a string since one of the operands is a string.
In my opinion, this would make sense as Javascript's intrinsic numeric types do not have the ability to store a specific number of decimal place digits, so a string would be the most appropriate data structure to store this with.
I would advise you do all your addition before calling toFixed(), since the method is most suitable for formatting display output.
var taxRate = 0.055;
var subtotal = 21.78;
var tax = (taxRate * subtotal).toFixed(2),
totalprice = ((1+taxRate) * subtotal).toFixed(2);
document.write(totalprice);
The .toFixed() method returns a string. Try applying that method as the last step after all other calculations.
Here's a simple fix. Put '+' in front of the tax variable to convert it to a number.
var y = 21.78;
var tax = (0.055*y).toFixed(2);
var totalprice = y+ (+tax);
totalprice === 22.98;
If you don't want any rounding errors when you use toFixed, then include this re-implementation of it in your script.
http://bateru.com/news/2012/03/reimplementation-of-number-prototype-tofixed/
In my experience, if there's any chance available, Javascript will see the "+" sign as concatenate rather than addition. It's driven me nuts on more than one occasion. I will generally do this rather than chance concatenation:
var totalprice = parseInt(y)+parseInt(tax);
When letter replaces value, multiply with 1 when you're in need of +.
var totalprice = (y*1) + tax .
Other operands work fine, it's just the + operand that needs special treatment when variable replace value.

It puts strings together instead of adding them Javascript

var x = e.pageX;
var myX = $(this).html();
var difference = myX - x;
var ex = myX + difference;
Everything workes until the last row. It doesn´t make an addition, it puts together the variables into one string. If myX is 10 and difference is 20 it will be 1020 when I want it to be 30.
How do I solve this?
You can force the variables to be integer using something like this :
var ex = parseInt(myX, 10) + parseInt(difference, 10);
This happen because your variables are considered as strings, and using the + operator on strings concatenates then togheter instead of adding their numeric values.
This is a common issue when trying to add a number to a string in Javascript. I think it was an oversight in the design of a dynamic language to use the same operator for addition and string concatenation.
I typically use this trick to get around it:
var ex = myx - 0 + difference
because subtracting something from a string will convert it to a number.
As Felix pointed out in the comments below, you can use the unary + operator to convert a string to a number, like this:
var ex = +myx + difference
This is because myX is a string and it is concatenating the numbers together into a new string.
What you need is to change myX into a number.
Use parseInt to do this.
parseInt(myX, 10)
A minus will force the variables to be parsed as an int but the plus will simply function as concatenation and even coerce the int to a string.

Javascript (+) sign concatenates instead of giving sum of variables

Why when I use this: (assuming i = 1)
divID = "question-" + i+1;
I get question-11 and not question-2?
Use this instead:
var divID = "question-" + (i+1)
It's a fairly common problem and doesn't just happen in JavaScript. The idea is that + can represent both concatenation and addition.
Since the + operator will be handled left-to-right the decisions in your code look like this:
"question-" + i: since "question-" is a string, we'll do concatenation, resulting in "question-1"
"question-1" + 1: since "queston-1" is a string, we'll do concatenation, resulting in "question-11".
With "question-" + (i+1) it's different:
since the (i+1) is in parenthesis, its value must be calculated before the first + can be applied:
i is numeric, 1 is numeric, so we'll do addition, resulting in 2
"question-" + 2: since "question-" is a string, we'll do concatenation, resulting in "question-2".
You may also use this
divID = "question-" + (i*1+1);
to be sure that i is converted to integer.
Use only:
divID = "question-" + parseInt(i) + 1;
When "n" comes from html input field or is declared as string, you need to use explicit conversion.
var n = "1"; //type is string
var frstCol = 5;
lstCol = frstCol + parseInt(n);
If "n" is integer, don't need conversion.
n = 1; //type is int
var frstCol = 5, lstCol = frstCol + n;
Since you are concatenating numbers on to a string, the whole thing is treated as a string. When you want to add numbers together, you either need to do it separately and assign it to a var and use that var, like this:
i = i + 1;
divID = "question-" + i;
Or you need to specify the number addition like this:
divID = "question-" + Number(i+1);
EDIT
I should have added this long ago, but based on the comments, this works as well:
divID = "question-" + (i+1);
divID = "question-" + parseInt(i+1,10);
check it here, it's a JSFiddle
Another alternative could be using:
divID = "question-" + (i - -1);
Subtracting a negative is the same as adding, and a minus cannot be used for concatenation
Edit: Forgot that brackets are still necessary since code is read from left to right.
Add brackets
divID = "question-" + (i+1);
using braces surrounding the numbers will treat as addition instead of concat.
divID = "question-" + (i+1)
The reason you get that is the order of precendence of the operators, and the fact that + is used to both concatenate strings as well as perform numeric addition.
In your case, the concatenation of "question-" and i is happening first giving the string "question=1". Then another string concatenation with "1" giving "question-11".
You just simply need to give the interpreter a hint as to what order of prec endence you want.
divID = "question-" + (i+1);
Joachim Sauer's answer will work in scenarios like this. But there are some instances where adding parentheses won’t help.
For example: You are passing “sum of value of an input element and an integer” as an argument to a function.
arg1 = $("#elemId").val(); // value is treated as string
arg2 = 1;
someFuntion(arg1 + arg2); // and so the values are merged here
someFuntion((arg1 + arg2)); // and here
You can make it work by using Number()
arg1 = Number($("#elemId").val());
arg2 = 1;
someFuntion(arg1 + arg2);
or
arg1 = $("#elemId").val();
arg2 = 1;
someFuntion(Number(arg1) + arg2);
var divID = "question-" + (parseInt(i)+1);
Use this + operator behave as concat that's why it showing 11.
Care must be taken that i is an integer type of variable. In javaScript we don't specify the datatype during declaration of variables, but our initialisation can guarantee that our variable is of a specific datatype.
It is a good practice to initialize variables of declaration:
In case of integers, var num = 0;
In case of strings, var str = "";
Even if your i variable is integer, + operator can perform concatenation instead of addition.
In your problem's case, you have supposed that i = 1, in order to get 2 in addition with 1 try using (i-1+2). Use of ()-parenthesis will not be necessary.
- (minus operator) cannot be misunderstood and you will not get unexpected result/s.
One place the parentheses suggestion fails is if say both numbers are HTML input variables.
Say a and b are variables and one receives their values as follows (I am no HTML expert but my son ran into this and there was no parentheses solution i.e.
HTML inputs were intended numerical values for variables a and b, so say the inputs were 2 and 3.
Following gave string concatenation outputs: a+b displayed 23; +a+b displayed 23; (a)+(b) displayed 23;
From suggestions above we tried successfully : Number(a)+Number(b) displayed 5; parseInt(a) + parseInt(b) displayed 5.
Thanks for the help just an FYI - was very confusing and I his Dad got yelled at 'that is was Blogger.com's fault" - no it's a feature of HTML input default combined with the 'addition' operator, when they occur together, the default left-justified interpretation of all and any input variable is that of a string, and hence the addition operator acts naturally in its dual / parallel role now as a concatenation operator since as you folks explained above it is left-justification type of interpretation protocol in Java and Java script thereafter. Very interesting fact. You folks offered up the solution, I am adding the detail for others who run into this.
Simple as easy ... every input type if not defined in HTML is considered as string. Because of this the Plus "+" operator is concatenating.
Use parseInt(i) than the value of "i" will be casted to Integer.
Than the "+" operator will work like addition.
In your case do this :-
divID = "question-" + parseInt(i)+1;

why do I get 24 when adding 2 + 4 in javascript

I am trying this:
function add_things() {
var first = '2';
var second = '4';
alert(first + second);
}
But it gives me 24 instead of 6, what am I doing wrong?
You're concatenating two strings with the + operator. Try either:
function add_things() {
var first = 2;
var second = 4;
alert(first + second);
}
or
function add_things() {
var first = '2';
var second = '4';
alert(parseInt(first, 10) + parseInt(second, 10));
}
or
function add_things() {
var first = '2';
var second = '4';
alert(Number(first) + Number(second));
}
Note: the second is only really appropriate if you're getting strings from say a property or user input. If they're constants you're defining and you want to add them then define them as integers (as in the first example).
Also, as pointed out, octal is evil. parseInt('010') will actually come out as the number 8 (10 in octal is 8), hence specifying the radix of 10 is a good idea.
Try this:
function add_things() {
var first = 2;
var second = 4;
alert(first + second);
}
Note that I've removed the single quotes; first and second are now integers. In your original, they are strings (text).
That is one of the "Bad Parts" of JavaScript, as a loosely typed language, the addition and concatenation operator is overloaded.
JavaScript is loosely typed, but that doesn't mean that it has no data types just because a value of a variable, object properties, functions or parameters don't need to have a particular type of value assigned to it.
Basically there are three primitive data types:
boolean
number
string
null and undefined are two special cases, everything else are just variations of the object type.
JavaScript type-converts values of types into a type suitable for the context of their use (type coercion).
In your example were trying to add two objects of type string, so a concatenation occur.
You can "cast" or type convert the variables to number in many ways to avoid this problem:
var a = "2";
var b = "4";
// a and b are strings!
var sum = Number(a) + Number(b); // Number constructor.
sum = +a + +b; // Unary plus.
sum = parseInt(a, 10) + parseInt(b, 10); // parseInt.
sum = parseFloat(a) + parseFloat(b); // parseFloat.
This is I think a very common mistake, for example when reading user input from form elements, the value property of form controls is string, even if the character sequence that it contain represents a number (as in your example).
The "Bad Part" which I talk, is about the dual functionality of the + operator, overloaded to be used for both, numeric addition and string concatenation.
The operation that the + operator will do is determined completely by the context. Only if the both operands are numbers, the + operator perform addition, otherwise it will convert all of its operands to string and do concatenation.
The single quotes cause the values to be treated as characters instead of numbers. '2' + '4' = '24' in the same way that 'snarf' + 'blam' = 'snarfblam'.
You could also force the interpreter to perform arithmetic when dealing with numbers in string forms by multiplying the string by 1 (since multiplication can't be done on a string, it'll convert to a number if it can):
// fun with Javascript...
alert(first * 1 + second * 1);
But it's probably best to go with CMS's suggestion of using Number() to force the conversion, since someone will probably come along later and optimize the expression by removing the 'apparently unnecessary' multiply-by-one operations.

Categories

Resources