Laz
0
Q:

javascript check type of variable var

var foo = "Hello";
console.log(typeof foo); // string
5
typeof("string"); //string
typeof(123); //number
10
> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"

if(typeof bar === 'number') {
   //whatever
}
3
//typeof() will return the type of value in it's parameters.
//some examples of types: undefined, NaN, number, string, object, array

//example of a practical usage
if (typeof(value) !== "undefined") {//asuming value is already set
  	//execute code
}
8
typeof("iAmAString");//This should return 'string'
//NO camelCase, as it is a JS Keyword
4
console.log(typeof 93);
// Output = "number"

console.log(typeof 'Maximum');
// Output = 'string'

console.log(typeof false);
// Output = "boolean"

console.log(typeof anUndeclaredVariable);
// Output = "undefined"
3
// You can use the built-in method 'typeof' in order to check the variable datatype

//examples:

typeof "hello" // "string"

//or
var a = 1;
typeof(a);
//the output will be > 'number'
0
var x = "Hello World";
typeof x; // "string"
1
> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"
0

New to Communities?

Join the community