While I do know that the following question is stupid simple, it is related to a specific situation that I have been unable to find through Google. The following code is in Javascript.
Suppose there is a variable
x = x + 1;
I can see from a tutorial that this is supposed to work. However, how are we supposed to use this variable in a calculation?
I have tried with the following codes
var name = name + 1;
alert(name);
The above outputs "NaN"; whatever that is...
var name = name + 1;
name = 2;
alert(name);
The above outputs 2 which is simply overriding the original variable.
name = prompt("input any number");
var name = name + 1
alert(name);
The above outputs the input provided + 1 as a string, i.e. 01 where the input is "0" without quotes.
I remember from a ruby lesson that we use .to_i in order to convert a string to an integer. How do we go about doing this in Javascript?
var name = name + 1;
The above code declares a new variable called name which contains whatever name contained before, plus 1. Since name only just came into existence, it doesn't have a numeric value ("Not A Number", or NaN). Adding 1 to NaN gives NaN.
+ means different things in different contexts. If the two operands are numbers, then it does addition. If one operand is a String, it does String concatenation, so
var x = "2"; // x is the String "2"
alert(x+2); // "22"
var x = 2; // x is the number 2
alert(x+2); // 4
If you want to convert a String to a number, you can do
if (x) x = parseInt(x, 10);
where the second argument is the radix (i.e. the base of the number system), and you should use it. If someone entered 02 for example, the radix prevents javascript from treating that as an octal (or other) number.
Of course, you always need to make sure your variables are defined before you use them. I bet your NaN result is coming from the variable not being defined.
Your issue is that you never initialize name. For example:
var name = 0;
alert(name); // Name is 0
name = name + 1;
alert(name); // Name is 1
If you don't initialize it, it will give you NaN: Not a Number.
To turn a string into a number, use parseInt or parseFloat:
var name = prompt("input any number"); // I input 3
name = parseFloat(name);
name = name + 1;
alert(name); // Name is 4
Use parseInt to convert a string to a number.
The line x = x + 1 says "take the existing value of x, add one to it, and store the resulting value back in x again".
The line var name = name + 1 is meaningless since name does not have an existing value when the statement is executed. It is the same as saying undefined + 1 which is NaN (Not a Number).
Here are some examples of how the + operator works in JavaScript:
1 + 2 // number + number is a number -> 3
"1" + 2 // string + anything is a string => "12"
1 + "2" // anything + string is a string => "12"
"1" + "2" // string + string is a string => "12"
NaN means "not a number". Since name has no value when it is first declared, saying "var name = name + 1" doesn't have a numerical meaning, since name is in the process of being declared when used for the first time.
In the second example, name is determined to be a string. Javascript isn't as sensitive to types as some other languages, so it uses + as a concatenation operator instead of a numerical one, since it makes more sense in context,
Related
I'm attempting to update a value in an object and set it to the current value + another number. So for instance, if an object's value is 5, I want it to update like this: object key : current value (5) + 7
container[response["id"]]["quantity"] += quantity;
console.log(container[response["id"]].attr("quantity"));
This is what I'm currently attempting.. I end up with 57 instead of 12.
Any ideas?
You get as a string and + with strings concatenate them. First parse to the number using parseInt() or parseFloat() than add.
let number = parseInt(container[response["id"]]["quantity"]);
number += quantity;
container[response["id"]]["quantity"] = number;
The issue is, the value return by response["id"]]["quantity"] is a string. And when you try to add a number using + to a string, then it will concatenate it, something like 5 + 7 is 57. To deal with this, you have to parse the number to Int or to Float by using parseInt() or parseFloat(). Ex:
let num = parseInt(container[response["id"]]["quantity"]);
num += quantity;
container[response["id"]]["quantity"] = num;
When I use prompt() method in JavaScript as follows:
var n=prompt("Enter an integer"); //passing 2 as value
n=(n+n);
document.writeln("n+n value is:"+n);
Then (n+n) gets concatenated as 22 instead of addition as 4
But when I don't use prompt() ie.:
var n=2;
n=(n+n)
document.writeln("n+n value is:"+n);
then it works fine for addition and answer is 4
Why is it so?
prompt("Enter an integer"); returns string
convert it after, you can use parseInt()
var n = parseInt(prompt("Enter an integer"));
SEE FIDDLE DEMO
Use parseInt to convert String to Int
var n = parseInt( prompt("Enter an integer") ); //passing 2 as value
n=(n+n);
document.writeln("n+n value is:"+n);
More info here
A variable declared with datatype var can hold any type of variable which is assigned to it at a moment of time.
eg.
var j = 1; // here j will be an integer datatype and will act as int after this
var j = "1"; //here j will be a string datatype and will act as int after this
in your first case
var n=prompt("Enter an integer");
here a string will be saved in variable 'n'. hence n will act as a string variable. Therefore (n+n) will result in concatenation of two strings.
In your second case
var n = 2;
In here n is holding an integer therefore n acts as int variable.
Thats why (n+n) results into a SUM instead of concatenation.
Change
var n =prompt("Enter an integer")
to
var n = Number( prompt("Enter an integer") )
As if you do console.log(typeof n) you will get a string which means n is actually a string.
So concatenation of
n = '2' + '2';
is '22'
Hence you need to change it to a number. For this you can use Number() or parseInt().
Here's an easy one for you true believers: You can use + to convert a string to a number,
var thing = "12"
alert(thing);
alert(typeof thing); // string
thing = +thing;
alert(typeof thing); // number
if (thing == 112) alert("!"); // number
Can someone explain:
What is the name of this process?
How does + convert a string to a number?
Javascript uses a dynamic type system. For me it's a 'cast' operation.
The operator + could be a String operator ('a' + 'b') or an Number operator (1+2). It could be used also between Strings and numbers (remembering that 0 + '12' = 12 and '0'+'12' = '012')
By default, i think that the JS interpreter considered +thing as 0 + things so it casts this variable to a number
This is all in the context of a larger program, so Im going to try keep it simple, showing the offending lines only. I have an array of values that are numbers in string form a la "84", "32", etc.
Yet THIS line
console.log(unsolved.length + " " + unsolved[0] + " " + parseInt(unsolved[0]) + " " + parseInt("84"));
prints:
4 "84" NaN 84
"84" is the array element Im trying to parseInt! Yet it won't work unless I take it out of the context of an array and have it explicitly written. What's going on?
You can try removing the quotations from the string to be processed using this function:
function stripAlphaChars(source) {
var out = source.replace(/[^0-9]/g, '');
return out;
}
Also you should explicitly specify that you want to parse a base 10 number:
parseInt(unsolved[0], 10);
parseInt would take everything from the start of its argument that looks like a number, and disregard the rest. In your case, the argument you're calling it with starts with ", so nothing looks like a number, and it tries to cast an empty string, which is really not a number.
You should make sure that the array element is indeed a string which is possible to parse to a number. Your array element doesn't contain the value '84', but actually the value '"84"' (a string containing a number encapsulated by ")
You'll want to remove the " from your array elements, possible like this:
function removeQuotationMarks(string) {
return (typeof string === 'string') ? string.replace(/"|'/g, '') : string;
}
unsolved = unsolved.map(removeQuotationMarks);
Now all the array elements should be ready to be parsed with parseInt(unsolved[x], 10)
First we need to replace " to ' in give data using Regex and replace and then we need to cast.
var i = 1;
var j = "22"
function stringToNumber(n) {
return (typeof n === 'string') ? parseInt(Number(n.replace(/"|'/g, ''))) : n;
}
console.log(stringToNumber(i)); // 1
console.log(stringToNumber(j)); // 22
If I have a variable that is given a "numeric" value from a PHP echo...
var names_each = <?php echo $ind_name_each; ?>;
...and $ind_name_each is derived from a MySQL column of type decimal(5,2),
is it a number or a string in JavaScript?
if all_total = 6.00
and names_each = 5.00
and I do this:
all_total = parseInt(names_each) + all_total;
I get 56.00
all_total = names_each + all_total;
I get 5.006.00
all_total = parseFloat(names_each) + all_total;
I get 56.00
I need some understanding here.
Convert all_total from string to int / float too...
Because now, + in all three examples is string concatenation.
Both variables are strings:
var names_each = '5.0', all_total = '6.0';
so the + operation concatenates those strings:
console.log(names_each + all_total); // '5.0' + '6.0' => '5.06.0'
console.log(parseInt(names_each) + all_total); // 5 + '6.0' => '5' + '6.0' => '56.0'
but if you parse them to numbers first, then you can use + to add them:
all_total = parseInt(names_each) + parseInt(all_total);
console.log(all_total); // 5 + 6 => 11
In JavaScript, if either side of the + operator is a string value then both sides are converted to a string and the result of the operator is the string concatenation of those values. Here are some examples:
1 + 2 // 3
"1" + "2" // "12"
"1" + 2 // "12"
1 + "2" // "12"
Note that the last 3 cases have the same result.
Happy coding.
On your examples it's not clear where all_total comes from in the first place, but it must be a string, since you are getting string concatenation instead of addition.
To answer your first question, names_each is not a string, it's a number.
The output of this PHP file
var names_each = <?php echo $ind_name_each; ?>;
Should be something like this:
var names_each = 5;
or
var names_each = 5.1;
So, it's not a string, but an actual number in js. If the other side of your attempted addition is a string, you get string concatenation.
Your variables are strings, not numbers.
Therefore, unless you explicitly convert them to numbers, you get string concatenation.
The following will tell you what they are:
console.log(typeof names_each);
console.log(typeof all_total);
Here are some examples:
typeof "6.00" // The result is "string"
typeof 6.00 // The result is "number"
If you add some logging to your application, you should be able to see where it is turning into a string.
Also, you should know that the following occurs:
5.00 == "5.00" // The result is "true"
5.00 === "5.00" // The result is "false"
Using the triple equals prevents the JavaScript engine from implicitly casting the type of your variable. So, with === you will get a strict comparison with no auto-type casting.