how to prevent chain when adding javascript variables containing numbers - javascript

How can i prevent to javascript interpret my numeric vars from string vars?
var a = 100;
var b = -10
var c = a + b // 10-10 (string)
lets say i allways want
var c = a + b = 100+(-10) = 90 (number)

In your example c will always be 90, however;
var a = 100;
var b = "-10";
var c = a + b // "100-10" (string)
to prevent this convert the string to an integer;
var c = a + parseInt(b, 10);
or with a unary+
var c = a + +b;

Your code example...
var a = 100;
var b = -10
var c = a + b // 90 (number)
...won't do that unless one of the operands is a String. In your example, both are Number.
If you do have numbers inside of Strings, you can use parseInt() (don't forget to pass the radix of 10 if working in decimal) or possibly just prefix the String with + to coerce it to Number.

Your code works fine. See here.

JavaScript will always do the latter, as long as both of the variables you are adding are numbers.

The most concise way is prepending a + if you aren't certain whether the variables are numbers or strings:
var a = "100";
var b = "-10";
var c = +a + +b; // 90
This works since +"123" === 123 etc.

Related

Javascript Arithmetics

When we subtract/multiply/divide a number with a number(type as string), it will treat both variable as number.
But when we add a number with a number(type as string), it will treat second var as string and concat the variables.
For example
var a = 4;
var b = "4";
var c;
c = a + b;
console.log(c)
c = a - b;
console.log(c)
c = a * b;
console.log(c)
c = a / b;
console.log(c)
Result output is
"44"
0
16
1
Why there is different behaviour for addition in javascript?
Because "+" ist not only an arithmetic operator but also the "string concatination operator".
In your first example you concatenate 2 strings.
In your other examples the string is coerced to a number and then the arithmetic operation is executed.
There are some steps to prevent this from happening:
var a = 4;
var b = "4";
c = +b + a // 8
console.log(c);
c = parseInt(b) + a // 8
console.log(c);
c = b*1 + a // 8
console.log(c);
You just have to make sure that both variables have the type number when you add them together.
This is because + operator is also used for string concatenation. You can use the + operator incase you want to convert in into a number
var a = 4;
var b = "4";
console.log(a + b);
console.log(a + +b);
In JavaScript + operates both as ADD and string concatination. When you do a + b, a is implicitly coerced into a string. Whereas with other operators cannot be used on strings. Therefore a is implicitly coerced into number, so the math operation.

Why am i getting NaN error?

I have a program that reads a specific text file from a coding challenge that I've recieved and it takes the numbers and puts it into an array for me to solve a quadratic equation. When I go to display my answers I keep getting the NaN error on all of my values and I cant find where I messed up.
CODE
var lines = data[0].split("/n");
var numQuads = lines[0];
for (var i = 1; i < numQuads; i++){
var fields = lines[i].split(",");
var a = fields[0];
var b = fields[1];
var c = fields[2];
}
a = parseInt();
b = parseInt();
c = parseInt();
var discr = (b * b) - (4 * (a * c));
var sqrDiscr = Math.sqrt(discr);
var x = (-b + sqrDiscr) / (2*a);
var y = (-b - sqrDiscr) / (2*a);
var outputL = "The quadratic equation with coefficients A = " + a + " B = " + b + " C= " + c + " has no real roots!";
var outputW = "The quadratic equation with coefficients A = " + a + " B = " + b + " C= " + c + " has roots x = " + x + " and x = " + y;
if (discr >= 0) {
output += outputW + "\n";
}
else {
output += outputL + "\n\n";
}
You did not provide an argument to the parseInt function. It works like this: parseInt("2") for example. You probably want to use parseFloat instead of parseInt.
Another remark: your data array is undefined.
you have insert String in parseInt()
a = parseInt("67");
b = parseInt("3");
c = parseInt("2");
Should probably be:
a = parseInt(a);
b = parseInt(b);
c = parseInt(c);
the problem was var lines = data[0].split("/n");
I used the wrong character. It was supposed to be var lines = data[0].split("\n");
The problem is that you are not parsing anything with your parse int.
Take a look here for some docs on parseInt.
Anyway that's how it should look like in your code:
a = parseInt(a, 10);
b = parseInt(b, 10);
c = parseInt(c, 10);
d = parseInt(d, 10);
EDIT: following the suggestion of #d3l I looked into the parseInt parameters, according to this question there could be some unexpected behaviours of the parseInt function without adding the radix parameter. Hence I added it to my solution.
Assuming you are parsing integers we can specify 10 as base.

Convert string to expression in JavaScript

I am making a calculator in JavaScript and I want to know how to turn a string into an expression.
var numbers = "5+5+6";
numbers = +numbers;
document.querySelector('.screen').innerHTML = numbers;
Adding + before the variable does not seem to work. I would appreciate it if someone helped.
You can use the eval() function like this:
var numbers = "5+5+6";
document.querySelector('.screen').innerHTML = eval(numbers);;
Evaluate/Execute JavaScript code/expressions:
var x = 10;
var y = 20;
var a = eval("x * y") + "<br>";
var b = eval("2 + 2") + "<br>";
var c = eval("x + 17") + "<br>";
var res = a + b + c;
The result of res will be:
200
4
27
Without using eval, which is cheating - you could always write a simple calculator app.
First, take advantage of String.split() as follows
var numbers = "5+5+6";
numbers.split("");
// => ["5","+","5","+","6"]
Now all you need to do is figure out how to evaluate it while keeping the order of operations correct. Hint: it might involve trees.
Try using String.prototype.match() , Array.prototype.reduce() , Number() . See also Chrome App: Doing maths from a string
var numbers = "5+5+6";
var number = numbers.match(/\d+|\+\d+|\-\d+/g)
.reduce(function(a, b) {
return Number(a) + Number(b)
});
document.querySelector(".screen").innerHTML = number;
<div class="screen"></div>

javaScript change string char's position

Let's say i have three variables:
a, b, c
and i set them such values:
2,1,3
I have such string:
ilovemama
how could i change char position, via block's of three, in my case i have three blocks:
ilo
vem
ama
let's try on first block:
1 2 3
i l o
and i must change this position's via my a,b,c:
2 1 3
l i o
And so over, and then concat this block's into one line...
I think that i explain it normally.
I can do this on jQuery, but i can't imagine, how to do this on pure JS. i try a little bit, but this is without sense(
var string = 'some string'
a = string.charAt(0),
b = string.charAt(1),
c = string.charAt(2); // and so on
var newString = b + a + c; //oms
var otherString = c + b + a; //mos
.charAt(0) will select the first leter of the string(the one with index 0) and so on.
assigning the values to vars you can manipulate the string as I understand you want to do
for blocks,
doing;
var string='some string';
var a = string.slice(0, 3),
b = string.slice(3, 7),
c = string.slice(7, 11); and so on
Then the same
var newString = c +a +b; // will be = 'ringsome st'
To find an Index as you request in the comment you can use;
var str = "Hello There",
indexOfr = str.indexOf("r");
console.log(indexOfr); // outputs 9
A function could be;
function dynamo(string) {
var len = string.length-1,
parts = 3,
whereToCut = Math.floor(len/parts);
var a = string.slice(0, whereToCut),
b = string.slice(whereToCut, (whereToCut *2)),
c = string.slice((whereToCut *2), len+1);
return b + a + c;
//(or you could hwere some code to see what order you want, i dont understand your request there)
}
dynamo('what do you really want to do??');
//returns "u really wwhat do yoant to do??"

Using Heron's formula to calculate area - JavaScript

My code:
function calculate(sides) {
var sides = prompt("Triangle side lengths in cm
(number,number,number)"); //String will be size of 4
var nsides = sides.split(" "); //Splits content into array format
//Convert Array instances to integer values a,b,c
for(var loop=0;loop<=nsides.length;loop++) {
if(nsides[loop]!=",")
a = nsides[loop];
if(nsides[loop]!=",")
b = nsides[loop];
if(nsides[loop]!=",")
c= nsides[loop];
} //End for
//Area Calculation
var s = (a+b+c)*0.5 ; //represents the semiperimeter
var area = Math.sqrt(s*(s-a)*s(s-b)*(s-c)) //area calculation
//Result
sides = alert("The triangle's area is " + area + " square cm");
} //End function
//Main calculate(length);
I'm looking to set side a, b, and c to integers; however in order to do that I have to go through the array (I first converted it to an array from a string)
I'm going to add in some standard validation later; as of now I can't seem to place the values from the string entered into 3 separate integers being a b and c.
Other than that, is there a better way i can go about this?
Thanks.
Maybe I misunderstand your question, but is this what you're looking for?
var sides = prompt("Triangle side lengths in cm (number,number,number)");
var nsides = sides.split(",");
var a = +nsides[0];
var b = +nsides[1];
var c = +nsides[2];
//Area Calculation
//...
Note the use of + to force the strings from the array into numbers.
function calculate() {
var sides = prompt("Triangle side lengths in cm (number,number,number)"),
nsides = sides.split(","),
a = parseFloat(nsides[0]),
b = parseFloat(nsides[1]),
c = parseFloat(nsides[2]),
s = (a + b + c) / 2,
area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
alert("The triangle's area is " + area + " square cm");
return area; // return the area
}
First of all I removed your parameter, it was totally unnecessary and was overwritten by the declaration of sides in the first line. Then I changed the split to , so it follows your instructions. Then you need to parse the string to integers using parseInt and specifiying the radix 10, then you can go on with your calculations. Just a last thing, you wrote Math.sqrt(s*(s-a)*s(s-b)*(s-c)), see that s(s-b) causes an exception because you are using a number to be called as a function.

Categories