Javascript Arithmetics - javascript

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.

Related

Generating random integer between two inputs Javascript

I'm trying to write a function (GetPositiveInteger) that generates a random integer between variables a and b. if a > b, it's supposed to switch the values of the two so that b=>a before generating the Number.
I don't know if I'm misunderstanding the question or what because I can't figure out where I'm meant to be converting a and b to integers and my program keeps just returning NaN. here's my code maybe someone could take a look at it?
function GetRandomInteger(a, b, c) {
a = Number(a), b = Number(b);
if (a > b) {
var a = 2,
b = 1,
c = a;
a = b;
b = c;
} else {
var x = parseInt(Math.random() * b) + a;
}
return x;
}
let x;
console.log(Number(GetRandomInteger(x)));
When a > b, you're setting them to specific numbers before swapping them, instead of swapping the original values.
The code that generates the random number shouldn't be in else, because you won't run that after swapping a and b. It should just be after the if.
You don't need the c parameter. Use a temporary variable declared inside the function when swapping.
Use Math.floor() to convert a floating point number to an integer. parseInt() is for parsing strings (it will work in this case because it first converts the float to a string, but it's better to use the more specific function).
You need to call the function with two arguments. In the example below I just hard-coded them, but you can use your function that asks the user for numbers. Just use it twice to set two variables.
function GetRandomInteger(a, b) {
a = Number(a), b = Number(b);
if (a > b) {
let temp = a;
a = b;
b = temp;
}
var x = Math.floor(Math.random() * b) + a;
return x;
}
console.log(GetRandomInteger(1, 10));
console.log(GetRandomInteger(15, 3));

what's the differences between (variable).toFixed(2) and +(variable).toFixed(2)?

I'm wondering what's the main differences between
(2.3444).toFixed(2) ==> 2.34
Also
+(2.3444).toFixed(2) ==> 2.34
Both of them giving the same results. Can any one explain when I need to use that + sign?
The first gives you a string, the second gives you a (now truncated) number.
var x = 2.344;
var a = x.toFixed(2);
var b = +x.toFixed(2);
console.log(a, typeof a);
console.log(b, typeof b);
A unary plus will attempt to convert it's operand to a number.
The reason this matters is because the first one will lead to string concatenation if you "add" a number to it.
var x = 2.344;
var strNumber = x.toFixed(2);
console.log(strNumber);
console.log(strNumber + 5); // Expected: 7.34, actual: 2.345

Explain +var and -var unary operator in javascript

I'm trying to understand unary operators in javascript, I found this guide here http://wiki.answers.com/Q/What_are_unary_operators_in_javascript most of it makes sense but what I don't understand is how the following examples would be used in an actual code example:
+a;
-a;
To my understanding the +a; is meant to make the variable the positive value of a and the -a; is meant to make the variable the negative value of a. I've tried a number of examples like:
a = -10;
a = +a;
document.writeln(a);
And the output is still -10;
I've also tried:
a = false;
a = +a;
document.writeln(a);
And the output is 0;
What is a practical code example of these unary operators?
The + operator doesn't change the sign of the value, and the - operator does change the sign. The outcome of both operators depend on the sign of the original value, neither operator makes the value positive or negative regardless of the original sign.
var a = 4;
a = -a; // -4
a = +a; // -4
The abs function does what you think that the + opreator does; it makes the value positive regardless of the original sign.
var a =-4;
a = Math.abs(a); // 4
Doing +a is practically the same as doing a * 1; it converts the value in a to a number if needed, but after that it doesn't change the value.
var a = "5";
a = +a; // 5
The + operator is used sometimes to convert string to numbers, but you have the parseInt and parseFloat functions for doing the conversion in a more specific way.
var a = "5";
a = parseInt(a, 10); //5
One example is that they can be used to convert a string to a number,
var threeStr = '3.0'
var three = +threeStr
console.log(threeStr + 3) // '3.03'
console.log(three + 3) //6
I would like to explain this from basic mathematical point:
The multiplying rules:
Positive x Positive = Positive: 3 x 2 = 6
Negative x Negative = Positive: (-2) x (-8) = 16
Negative x Positive = Negative: (-3) x 4 = -12
Positive x Negative = Negative: 3 x (-4) = -12
Considering you example:
a = -10;
a = +a
document.writeln(a);
+a = +(-10) = Positive x Negative = Negative = -10
a = false;
a = +a;
document.writeln(a);
false == 0, +a = +(+0) = Positive * Positive = Positive = 0 (maybe use true is a better example)
a = 1
b = -a
console.log(b)
output
-1
'+' operator in a variable 'a' simply means : a
'-' operator in a variable 'a' simply means : -a
Since, in above example
a=-10;
a= +a; // means a, ie, +(-10) which is -10
but,
a= -a; // means -a, ie, -(-10) which is +10
+a means a*1
and
-a means a*(-1)
Thats it!!!!!!
Try this
false == 0 // returns true
So,
a = false
a = +a //a * 1
console.log(a) // prints 0 as expected

Difference between += and =+ in javascript

I want to know why after running the third line of code the result of a is 5?
a = 10;
b = 5;
a =+ b;
Awkward formatting:
a =+ b;
is equivalent to:
a = +b;
And +b is just a fancy way of casting b to number, like here:
var str = "123";
var num = +str;
You probably wanted:
a += b;
being equivalent to:
a = a + b;
The + sign before the function, actually called Unary plus and is part of a group called a Unary Operators and (the Unary Plus) is used to convert string and other representations to numbers (integers or floats).
A unary operation is an operation with only one operand, i.e. a single input. This is in contrast to binary operations, which use two operands.
Basic Uses:
const x = "1";
const y = "-1";
const n = "7.77";
console.log(+x);
// expected output: 1
console.log(+n);
// expected output: 7.77
console.log(+y);
// expected output: -1
console.log(+'');
// expected output: 0
console.log(+true);
// expected output: 1
console.log(+false);
// expected output: 0
console.log(+'hello');
// expected output: NaN
When the + sign is positioned before a variable, function or any returned string representations the output will be converted to integer or float; the unary operator (+) converts as well the non-string values true, false, and null.

how to prevent chain when adding javascript variables containing numbers

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.

Categories