For a variable x=5, how do I know it is number five or the character '5'?
Btw, in JS, do characters follow the ASCII table? Then can I manipulate a character variable. For example, if variable x is character a, can I do x=x+1 to make it character b?
For a variable x=5, how do I know it is number five or the character '5'?
Btw, in JS, do characters follow the ASCII table? Then can I manipulate a character variable. For example, if variable x is character a, can I do x=x+1 to make it character b?
To see if x is the number 5, as opposed to the string "5", you can use the identity operator:
if (x === 5) {
}
Identity will not do any implicit conversions; it will return true only if both operands are equal without any conversions.
For example, if variable x is character a, can I do x=x+1 to make it character b?
No. x = x + 1 will convert 1 to a string, perform string concatenation and return "a1"
=You can use
typeof x;
which returns a string describing the type of the variable, like number, string or object.
To get the character code of a character, use charCodeAt:
var mystring = 'a';
mystring.charCodeAt(0);
And to get a character from an augmented char code, use String.fromCharCode :
var nextLetter = String.fromCharCode( mystring.charCodeAt(0) + 1 ); // returns "b"
This creates a new string from the incremented char code from the first character in mystring.
Just get the type of the variable:
console.log(typeof '5'); // Returns 'string';
console.log(typeof 5); // Returns 'number';
As for your second question, no, it doesn't work:
console.log('b' + 1); // Returns 'b1'
var x = 5; console.log(typeof x); // outputs 'number'char type. It's either a String or a Number.If your var x is not an integer, this is the best way to change it to integer..
To change the x to integer
x = parseInt(x);
You can how add any value to the x, example:
x = x + 2;
Since we have changed the x to integer, we can now identify if this is equal to 5
if(x == 5){
//Your Codes Here
}