Q:

how to get type of variable in javascript

function doSomething(x) {
  if(typeof(x) === 'string') {
    alert('x is a string')
  } else if(typeof(x) === 'number') {
    alert('x is a number')
  }
}
1
> 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 "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"
1
console.log(typeof 'blubber');
3

New to Communities?

Join the community