why javascript show string all arithmetic operation? - javascript

as you show below, when javascript doing an arithmetic operation all value concatenation with the string it shows a string value but I have some confusion...
var x = 10;
var y = 20;
var sum = x + y;
console.log("sum is :" + sum); //this is number
But confusion is
var x = 10;
var y = 20;
console.log("sum is : " + 10 + 20 ); //why this is string
var x = 10;
var y = "The value is " + x; // why this is string
var x = 10;
var y = 20;
var sum = x + y;
var z = 'sum is' + sum; //why this string
console.log("sum is : " + sum) // why this is not string coz it is also concatenation with string.

JavaScript will concatenate and coerce in a certain order of operations. You can add parentheses to add numbers before coercing to a string.
console.log("sum is : " + 10 + 20); // sum is : 1020
console.log("sum is : " + (10 + 20)); // sum is : 30

The unary + operator can be used to convert a variable to a number:
var y = "5"; // y is a string
var x = + y; // x is a number
If the variable cannot be converted, it will still become a number, but with the value NaN (Not a Number):
var y = "John"; // y is a string
var x = + y; // x is a number (NaN)
When JavaScript tries to operate on a "wrong" data type, it will try to convert the value to a "right" type.
5 + null // returns 5 because null is converted to 0
"5" + null // returns "5null" because null is converted to "null"
"5" + 2 // returns "52" because 2 is converted to "2"
"5" - 2 // returns 3 because "5" is converted to 5
"5" * "2" // returns 10 because "5" and "2" are converted to 5 and 2
So if you put numbers inside parenthesis like (10 + 20) then it will perform arithmetic operation first then it will do the concatenation outside. If either one of them would be string then it would do the concatenation inside as well.
var console.log("sum is : " + (10 + 20) ); // sum is : 30
var console.log("sum is : " + (10 + '20') ); // sum is : 1020

When you are adding a number with a string it counts the number as a string, like console.log("sum is : " + 10 + 20 ).
But when 10 and 20 is under a variable it counts the number as a variable value.
If you want to use numbers with a string use "sum is: " + parseInt(10) like this.

Related

Function that returns a multiplication table fails with negative numbers

Hello I was having issue with this function. I wanted to create a function that takes a number, a starting point and a final point, and writes the multiplication table of the number from the starting point to the ending point. For example, tabmul(10,2,4) returns
10.2 = 20
10.3 = 30
10.4 = 40
This is all good but it doesn't work for negative numbers. For example,
tabmul(10,-4,-1) should generate
10.-4 = -40
10.-3 = -30
10.-2 = -20
10.-1 = -10
but it doesn't return anything. This is my code:
function tabmul(a,b,c){ \\function that generates the multiplication table
var myarray = new Array();
var x
for(x=b; x<=c; x++){
myarray[x - b] = a*x;
document.write(a + "." + x + "=" + myarray[x - b] + "<br>")
}
}
var a = prompt("Enter the number whose table you want to calculate: ","");
var b = prompt("Enter the place where you want the table to start","");
var c = prompt("Enter the place where you want the table to end","");
\\ this checks if the starting point is smaller or equal than the ending point of the table
if (0 <= c-b) {
tabmul(a,b,c);
} else {
alert("The starting point is bigger than the ending point");
}
You are comparing strings. This is because prompt returns strings. you need to convert a,b,c to numbers. Also you are using wrong symbols for comments, you need to correct those.
function tabmul(a,b,c){ //function that generates the multiplication table
a = Number(a);
b = Number(b);
c = Number(c);
var myarray = new Array();
var x
for(x=b;x<=c;x++){
myarray[x-b] = a*x;
document.write(a+"."+x+"="+myarray[x-b]+"<br/>")
}
}
var a = prompt("Enter the number whose table you want to calculate: ","");
var b = prompt("Enter the place where you want the table to start","");
var c = prompt("Enter the place where you want the table to end","");
if(0 <= c-b){ //this checks if the starting point is smaller or equal than the ending point of the table
tabmul(a,b,c);
}
else{
alert("The starting point is bigger than the ending point");
}
1)Make normal names for function arguments.
2)Use indentation and 'let' in 'for' loop instead of 'var' right before:
for(let x = b; x <= c; x++){}
3)Don't forget semicolons.
function multiplication(val, start, end) {
if(end - start <= 0) return;
for(let i = start; i <= end; i++) {
console.log(val + ' * ' + i + ' = ' + val * i);
}
}
multiplication(10, -4, -1);
10 * -4 = -40
10 * -3 = -30
10 * -2 = -20
10 * -1 = -10
You should also convert your input to a number using Number or parseInt to make sure it is numeric.
After that you can run into problems referring to an array by index using a negative number.
myarray[x-b] // can fail if x-b<0. Also for a large number n it will insert empty elements in your array up to N.
For example take the following:
var myarray= new Array();
myarray[-4]=1;
console.log(JSON.stringify(myarray));
// result "[]"
myarray= new Array();
myarray[10]=1;
console.log(JSON.stringify(myarray));
// result "[null,null,null,null,null,null,null,null,null,null,1]"
You could convert it to a string:
myarray['"' + (x-b) + '"'] = a*x;
Or you could just use push() and your indexes will start with zero.:
for(x=b;x<=c;x++){
myarray.push(a*x);
document.write(a+"."+x+"="+myarray(myarray.length-1)+"<br/>")
}

why the odd results adding floats in javascript?

I have javascript code like this:
var strikePrice = parseFloat(this.props.data.strike).toFixed(1);
var commission = parseFloat(this.props.commission / 100).toFixed(2);
var callInMoney = parseFloat(strikePrice + this.state.callPrice + commission).toFixed(2);
var putInMoney = parseFloat(strikePrice - this.state.putPrice - commission).toFixed(2);
console.log("strikePrice: " + strikePrice + " commission: " + commission);
console.log("callprice: " + this.state.callPrice + " putprice: " + this.state.putPrice);
console.log("call: " + callInMoney + " put: " + putInMoney);
and the output is this:
strikePrice: 34.0 commission: 0.08
callprice: 0 putprice: 0
call: 34.00 put: 33.92
That is wrong. The call should be 34.08 (8 cents higher) just like the put is 8 cents lower.
Why is the results not correct?
Thank you
Matt
toFixed returns a string so you're actually doing some string concatenation rather than the arithmetic you expect.
Check out what happens when you just print out your initial addition.
var strikePrice = parseFloat('34').toFixed(1);
var commission = parseFloat('0.08').toFixed(2);
console.log(strikePrice + 0 + commission);
Instead, you'll need to convert those strings to numbers first.
var strikePrice = parseFloat('34').toFixed(1);
var commission = parseFloat('0.08').toFixed(2);
strikePrice = parseFloat(strikePrice);
commission = parseFloat(commission);
console.log(strikePrice + 0 + commission);
This expression:
strikePrice + this.state.callPrice + commission
Evaluates to this value:
"34.000.08"
Because commission is a string value, which is because [toFixed()][1] takes an integer and returns a string.
You need to refactor your code so that commission is a float value, or so that you call parseFloat() again on the parameters of line 3.
I can't comment on why putInMoney works for you. For me it gave "NaN".

NaN , Returning in browser

I get back
Nan ,
what does this mean?
In the distinctPlayer variable are two values 110 and 115. I want to have for this two Player the name and the sum of Note.
The first query of finalTotal gives for 110 the sum of Note 8 + 2 = 10 and for 115 the sum of Note 4 + 3 = 7 back.
The second query ... name of 110 is Dave and for 115 is Tom.
The while loop have an execution of 2 times. Then I try to safe each line of while in a variable. First line is Dave: 10 and second line is Tom: 7. But I don't get this back. At the moment the result is NaN ,
In the html the function is defined as
<p>
<pre>{{otherHelperFunction}}</pre>
</p>
And here is the function
var d = 0;
while(distinctPlayer[d]) {
var finalTotal = Spieltag.find({SpielerID: distinctPlayer[d]}).map(function (doc) {
total =+ doc.Note;
});
var finalName = Spieltag.find({SpielerID: distinctPlayer[d]}).map(function (doc) {
return doc.Name;
});
var finalReturn =+ finalName +" "+ finalTotal;
d++;
}
return finalReturn;
NaN means Not a Number. Try the following:
var finalReturn = finalName + " " + finalTotal;
The addition assignment operator is += which can be used as follows:
var a = 1;
a += 1 // a now has a value of 2
The += operator in this case represents a = a + 1.
You're using =+, the correct syntax is +=
Let's go,
NaN is Not a Number, you are trying treat as number what not Number.
You are using =+, you should use +=.
Probabily the doc.Note not is number.
JavaScript have function isNaN, this return a boolean.

Why I got NaN in this javaScript code?

First I test that every variable got a number value:
09-11 18:15:00.420:
d_drop: -1.178791867393647
drop_at_zero: 0.0731037475605623
sightHeight: 4.5
d_distance: 40
zeroRange: 10
09-11 18:15:00.420:
d_drop: true
drop_at_zero: true
sightHeight: true
d_distance: true
zeroRange: true
function isNumber (o) {
return ! isNaN (o-0) && o != null;
}
var d_drop; // in calculation this gets value 1.1789
var d_path = -d_drop - sightHeight + (drop_at_zero + sightHeight) * d_distance / zeroRange;
console.log("Path: " + d_path + " cm");
and in the log:
09-11 18:15:00.430: D/CordovaLog(1533): Path: NaN cm
WHY? I have tried to figure that out couple of hours now and no success, maybe someone has an idea, I haven't!
Thanks!
Sami
-------ANSWER IS that parse every variable when using + operand-----------
var d_path = parseFloat(-d_drop) - parseFloat(sightHeight) + (parseFloat(drop_at_zero) + parseFloat(sightHeight)) * parseFloat(d_distance) / parseFloat(zeroRange);
The addition operator + will cast things as strings if either operand is a string. You need to parse ALL of your inputs (d_drop, sightHeight, etc) as numbers before working with them.
Here's a demo of how the + overload works. Notice how the subtraction operator - is not overloaded and will always cast the operands to numbers:
var numberA = 1;
var numberB = 2;
var stringA = '3';
var stringB = '4';
numberA + numberB // 3 (number)
numberA - numberB // -1 (number)
stringA + stringB // "34" (string)
stringA - stringB // -1 (number)
numberA + stringB // "14" (string)
numberA - stringB // -3 (number)
http://jsfiddle.net/jbabey/abwhd/
At least one of your numbers is a string. sightHeight is the most likely culprit, as it would concatenate with drop_at_zero to produce a "number" with two decimal points - such a "number" is not a number, hence NaN.
Solution: use parseFloat(varname) to convert to numbers.
If you're using -d_drop as a variable name, that is probably the culprit. Variables must start with a letter.
var d_drop = -1.178791867393647,
drop_at_zero = 0.0731037475605623,
sightHeight = 4.5,
d_distance = 40,
zeroRange = 10;
var d_path = d_drop - sightHeight + (drop_at_zero + sightHeight) * d_distance / zeroRange;
console.log("Path: " + d_path + " cm"); // outputs: Path: 12.613623122848603 cm

JavaScript string and number conversion

How can I do the following in JavaScript?
Concatenate "1", "2", "3" into "123"
Convert "123" into 123
Add 123 + 100 = 223
Covert 223 into "223"
You want to become familiar with parseInt() and toString().
And useful in your toolkit will be to look at a variable to find out what type it is—typeof:
<script type="text/javascript">
/**
* print out the value and the type of the variable passed in
*/
function printWithType(val) {
document.write('<pre>');
document.write(val);
document.write(' ');
document.writeln(typeof val);
document.write('</pre>');
}
var a = "1", b = "2", c = "3", result;
// Step (1) Concatenate "1", "2", "3" into "123"
// - concatenation operator is just "+", as long
// as all the items are strings, this works
result = a + b + c;
printWithType(result); //123 string
// - If they were not strings you could do
result = a.toString() + b.toString() + c.toString();
printWithType(result); // 123 string
// Step (2) Convert "123" into 123
result = parseInt(result,10);
printWithType(result); // 123 number
// Step (3) Add 123 + 100 = 223
result = result + 100;
printWithType(result); // 223 number
// Step (4) Convert 223 into "223"
result = result.toString(); //
printWithType(result); // 223 string
// If you concatenate a number with a
// blank string, you get a string
result = result + "";
printWithType(result); //223 string
</script>
Step (1) Concatenate "1", "2", "3" into "123"
"1" + "2" + "3"
or
["1", "2", "3"].join("")
The join method concatenates the items of an array into a string, putting the specified delimiter between items. In this case, the "delimiter" is an empty string ("").
Step (2) Convert "123" into 123
parseInt("123")
Prior to ECMAScript 5, it was necessary to pass the radix for base 10: parseInt("123", 10)
Step (3) Add 123 + 100 = 223
123 + 100
Step (4) Covert 223 into "223"
(223).toString()
or
String(223)
Put It All Togther
(parseInt("1" + "2" + "3") + 100).toString()
or
(parseInt(["1", "2", "3"].join("")) + 100).toString()
r = ("1"+"2"+"3") // step1 | build string ==> "123"
r = +r // step2 | to number ==> 123
r = r+100 // step3 | +100 ==> 223
r = ""+r // step4 | to string ==> "223"
//in one line
r = ""+(+("1"+"2"+"3")+100);
These questions come up all the time due to JavaScript's typing system. People think they are getting a number when they're getting the string of a number.
Here are some things you might see that take advantage of the way JavaScript deals with strings and numbers. Personally, I wish JavaScript had used some symbol other than + for string concatenation.
Step (1) Concatenate "1", "2", "3" into "123"
result = "1" + "2" + "3";
Step (2) Convert "123" into 123
result = +"123";
Step (3) Add 123 + 100 = 223
result = 123 + 100;
Step (4) Convert 223 into "223"
result = "" + 223;
If you know WHY these work, you're less likely to get into trouble with JavaScript expressions.
You can do it like this:
// step 1
var one = "1" + "2" + "3"; // string value "123"
// step 2
var two = parseInt(one); // integer value 123
// step 3
var three = 123 + 100; // integer value 223
// step 4
var four = three.toString(); // string value "223"
To convert a string to a number, subtract 0.
To convert a number to a string, add "" (the empty string).
5 + 1 will give you 6
(5 + "") + 1 will give you "51"
("5" - 0) + 1 will give you 6
parseInt is misfeatured like scanf:
parseInt("12 monkeys", 10) is a number with value '12'
+"12 monkeys" is a number with value 'NaN'
Number("12 monkeys") is a number with value 'NaN'
Below is a very irritating example of how JavaScript can get you into trouble:
If you just try to use parseInt() to convert to number and then add another number to the result it will concatenate two strings.
However, you can solve the problem by placing the sum expression in parentheses as shown in the example below.
Result: Their age sum is: 98; Their age sum is NOT: 5048
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
var myFather = new Person("John", "Doe", "50", "blue");
var myMother = new Person("Sally", "Rally", 48, "green");
document.getElementById("demo").innerHTML = "Their age sum is: "+
(parseInt(myFather.age)+myMother.age)+"; Their age sum is NOT: " +
parseInt(myFather.age)+myMother.age;
</script>
</body>
</html>
Simplest is
when you want to make a integer a string do
var a,b, c;
a = 1;
b = a.toString(); // This will give you string
Now, from the variable b which is of type string we can get the integer
c = b *1; //This will give you integer value of number :-)
If you want to check above is a number. If you are not sure if b contains integer
then you can use
if(isNaN(c*1)) {
//NOt a number
}
else //number
We can do this by using unary plus operator to convert them to numbers first and simply add. see below:-
var a = "4";
var b = "7";
var sum = +a + +b;

Categories

Resources