This question already has answers here:
What exactly is Type Coercion in Javascript?
(9 answers)
Closed 2 years ago.
I have array, by which at some point am mapping the array and calculating sum and percentages. So while implementing the logic i saw that, when i use '*' directly its working but when i use '+' it just adds the two string
For example:
const a = '100';
const b = '10';
const c = a * b;
const d = a + b;
console.log(d)
When i checked the d , it gives '10010' and when c it gives '1000' ! How is this ?
But when i use parseInt(a) + parseInt(b) it works perfectly with 110 as output
In JavaScript there are no primitive datatypes like int, float etc. There are only variables which can be initialized with everything you need. For your example
const a = 100;
const b = 10;
const c = a * b;
const d = a + b;
console.log(d);
should work perfectly, because I removed ''. With '' the constant thinks it is a string provided. Without '' there are just the numbers saved in the constants. Also + doesn't work in your example, because as I said the constants think the numbers are a string due to ''. So it just puts this two "strings" together and not summing them up.
Related
This question already has answers here:
Why would I use Math.imul()?
(3 answers)
Is floating point math broken?
(31 answers)
Closed 10 days ago.
I need to rewrite some legacy Java code performing arithmetic transformations from Java to TypeScript/JavaScript. The problem is the legacy code uses the int Java type (signed 32-bits) and relies on overflows. I almost got what I want using Int32Array in JavaScript, but I still have a difference I can't explain. Look below.
Java:
int current = -1599751945;
int next = current * 0x08088405 + 1;
System.out.println("next = " + next);
Output: next = 374601940
Javascript:
const a = new Int32Array(4)
a[0] = -1599751945
a[1] = 0x08088405
a[2] = 1
a[3] = a[0]*a[1] + a[2]
console.log('a[3] = ' + a[3])
Output: a[3] = 374601952
Can someone explain the difference? And how can I get same result in JavaScript? I tried shift operations, coerce with |0, methods to convert etc., but best result is the one above.
Use Math.imul() in JavaScript. That should produce the correct result.
const a = new Int32Array(4)
a[0] = -1599751945
a[1] = 0x08088405
a[2] = 1
a[3] = Math.imul(a[0], a[1]) + a[2]
console.log('a[3] = ' + a[3])
Additional details as to why can be found here.
I can't provide a definitive answer as to exactly why you get these exact numbers; but consider that all numbers in JS are doubles.
So, whereas current * 0x08088405 is done using integer arithmetic in Java, a[0]*a[1] is done using double arithmetic in JS, so these intermediate results are different; and the limited precision of a double means that adding 1 to that doesn't actually change the value:
console.log(a[0]*a[1]) => -215607868985706270
console.log(a[0]*a[1] + a[2]) => = -215607868985706270
Compare this to Java, where integer arithmetic is used:
int[] a = { -1599751945, 0x08088405, 1};
System.out.println(a[0]*a[1]) => 374601939
System.out.println(a[0]*a[1] + a[2]) => 374601940
If we make Java do this in double arithmetic:
double[] a = { -1599751945, 0x08088405, 1};
System.out.println(a[0]*a[1]); => -2.15607868985706272E17
System.out.println(a[0]*a[1] + a[2]); => -2.15607868985706272E17
You can see that this is almost the same, but differs in the least significant digit:
-215607868985706270 // JS
-215607868985706272 // Java
I don't know why there is such a difference here.
Floating point numbers only support precision up to a specific number of digits. JavaScript promotes numbers larger than 32 bits to floating point numbers.
Java is "more correct" here.
// -215607868985706285 is the 64 bit result of your multiplication
console.log(-215607868985706285); // will print -215607868985706285
See Is floating point math broken? for a general discussion of this topic.
This question already has answers here:
How to compare an array of strings in Javascript?
(6 answers)
Closed 3 months ago.
I have a little problem to solve. I want to compare two texts if they are the same.
let currentValue = "24960307.W 25880305.W 24880208.W 25650156.W"
let newValue = "24880208.W 24960307.W 25650156.W 25880305.W"
// is the same text just diferent order
// when i did includes
let x = currentValue.includes(value);
console.log(x);
//response in console
false
I tried with includes and localeCompare but still show that text is different.
A quick solution to normalize order is to split, sort, rejoin, then compare. This avoids any fancy parsing.
let currentValue = "24960307.W 25880305.W 24880208.W 25650156.W"
let newValue = "25880305.W 24880208.W 25650156.W 24960307.W"
const a = currentValue.split(' ').sort().join(' ')
const b = newValue.split(' ').sort().join(' ')
console.log(a === b)
let x = a.localeCompare(b) === 0
console.log(x);
I asked a similar question here TypeScript: How to replace a particular number in a string, and then update its value?
Really appreciate the answers there. It answered my questions.
I am run into a new issue. Thought it s more helpful to raise a new question while referring to the old question.
I have a column that is full of 10-digits string.
Sometimes that entire 10-digits only contain numerical values (e.g. 3345678901), but sometimes there is dash included (e.g. 3345678---)
I would like to be able to:
Input an index number X
Locate the corresponding number in the string
Add or subtract a particular number A to/from that number to update the string
Update the string
Example 1 (all numerical): 3345678901
Input index number "4"
The corresponding number is 6
Increase that number by +2 to 8
Update the string to 3345878901
Example 2 (numerical & non-numerical): 3345678---
Input index number "4"
The corresponding number is 6
Increase that number by +2 to 8
Update the string to 3345878---
Example 3 (numerical & non-numerical): 3345678---
Input index number "7"
The corresponding value is -
Increase (or rather, update) that number by +2 to 2
Update the string to 33458782--
For example 1, I know I could do following (as a contributor from the OG post has pointed out):
const givenStr = "3345678901";
let givenStrArray = givenStr.split('').map(Number);
const inputIndex = 4;
const increaseAmount = 2;
givenStrNumber += increaseAmount
console.log(givenStrNumber);
But, how do I go about Example 2 and 3 though? Since there are string '-' involved? In this case map(Number) would lead to Null values that would break the code.
Any help would be greatly appreciated!
Check for NaN. This is a tiny snippet that would give you a hint:
// ...
// ...
const increment = 2;
let givenStrArray =
givenStr
.split('')
.map((digiit) => isNaN(digit) ? increment : Number(digit + increment);
// ...
// ...
Here's a simple little snippet. Break the sting apart, map through each item, when we find the index we need to update we update it and return it, then join them all back together.
Multiple conditional ternary operator have been used here, you can find out more about how they work here: Conditional (ternary) operator
const givenStr = "334567----",
inputIndex = 6,
increaseAmount = 2
let givenNumber = givenStr
.split('')
.map((v,i) => i === inputIndex ? isNaN(v) ? increaseAmount : +v + increaseAmount : v)
.join('')
console.log(givenNumber);
This should do the trick
let str = '3345678---'
let NumericStrArray = str.split('').map(x => Number.isNaN(Number(x)) ? x: Number(x))
let ipIndex = 7
let incAmount = 2
let val = NumericStrArray[ipIndex]
NumericStrArray[ipIndex] = typeof val === 'string' ? incAmount : val + incAmount
let result = NumericStrArray.join('')
This question already has answers here:
What does a comma do in assignment statements in JavaScript?
(4 answers)
Closed 4 years ago.
I found some code which looks like this
var v = color.val(), sel_c = (v == '') ? "#234872" : v;
I'm not sure why it was written like this, but I was wondering how to read it. If we'd just have
var v = color.val();
or
var sel_c = (v == '') ? "#234872" : v;
I'd understand. But what does it mean when you separate it with commas? Its as if we were trying to set multiple variables at once or something...
The comma operator is used to separate multiple statements.
In the case of variable assignment it is just a way to leave out subsequent var keywords. Each variable is set in turn
Yap, totally valid to omit having to write var, let or const multiple times
const a = 1,
b = a + 1,
c = b + 1;
console.log(a, b, c);
Is the same as
const a = 1;
const b = a + 1;
const c = b + 1;
just a few var, let or const fewer to write.
The following is the equivalent of the code you posted:
var v= color.val();
var sel_c;
if(v==''){
sel_c="#234872"
}else{
sel_c=v;
}
As for why it was written as you posted it - I believe it is to conserve "space". And by space I dont mean bytes of data, but rather lines in the code editor. At least that is the reason I always get. I personally think that written like that the code is less readable, even if more compact.
This:
var v = color.val(), sel_c = (v == '') ? "#234872" : v;
equals to:
var v = color.val();
var sel_c = (v == '') ? "#234872" : v;
The only benefit of writing it on one line is that your code will be a bit "shorter".
I personally find it ugly and hard to read.
I have two variables, 'a' and 'b' in my JavaScript, and i want to add them together - i assume this code:
var a = 10;
var b = 30
var varible = a + b;
This, puts the two numbers next to each other... any ideas why... the result should be 40?
You probably have strings instead of integers. That is your code really is like this:
var a = "10";
var b = "30";
var c = a + b; // "1030"
There are several ways to convert the strings to integers:
a = parseInt(a, 10); // Parse the string
b = b * 1; // Force interpretation as number
new is a reserved word, I'd use something else in any case.
And with a normal variable name of c it worked for me:
var a = 10;
var b = 30
var c = a + b;
alert(c);
did the expected and alerted 40
new is a keyword in JavaScript. you should not use it to declare your variables or functions. change the variable name from new to something else
Are you sure you didn't do this:
var a = '30';
var b = '40';
Here, I show '30' as a string rather than a number, and I would expect the "+" operator to concatenate two strings. Since this is contrived code, you may not be entirely sure where your variables were initially assign or what type they have. You can check it like this:
var a = '30';
var b = '40';
alert( typeof(a) + '\n' + typeof(b) );
If either of those say 'object' or 'string' rather than 'number' this is your problem. One way this might happen that you didn't expect is with an input. Say you have code like this:
<input id="a" value="30" />
<input id="b" value="40" />
<script language="javascript">
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
</script>
Here, the value of a text input is always a string initially.
If you want to convert a variable to a number first you should use something like myVar - 0 to coerce a numeric operation or the more-formal parseInt() or parseFloat() functions (don't forget the radix parameter for parseInt()). And always check isNaN() on the results.
I'm really surprised that noone has until now suggested the obvious: "Casting" with JavaScript (I set it in quotes, because it is no real casting).
var a = "1"; // string
var b = Number(a); // number
var c = String (b); // string again
a + b; // "11"
b + a; // 2
a + c; // "11"
Now, why is this no real casting? Because you don't create a new variable of type "number" but a new object "Number" and initialize it with something that could be numerical.
One or both is a string. If you get the values from a HTML input or something, they definitely are. Make sure they're both integers by using parseInt:
var newValue = parseInt(a,10) + parseInt(b,10);
Also, 'new' is a keyword. You can't use that for a variable name :)