Finding Variable Type in JavaScript

Finding Variable Type in JavaScript

Use typeof:

> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"

So you can do:

if(typeof bar === 'number') {
//whatever
}

Be careful though if you define these primitives with their object wrappers (which you should never do, use literals where ever possible):

> typeof new Boolean(false)
"object"
> typeof new String("foo")
"object"
> typeof new Number(42)
"object"

The type of an array is still object. Here you really need the instanceof operator.

Update:

Another interesting way is to examine the output of Object.prototype.toString:

> Object.prototype.toString.call([1,2,3])
"[object Array]"
> Object.prototype.toString.call("foo bar")
"[object String]"
> Object.prototype.toString.call(45)
"[object Number]"
> Object.prototype.toString.call(false)
"[object Boolean]"
> Object.prototype.toString.call(new String("foo bar"))
"[object String]"
> Object.prototype.toString.call(null)
"[object Null]"
> Object.prototype.toString.call(/123/)
"[object RegExp]"
> Object.prototype.toString.call(undefined)
"[object Undefined]"

With that you would not have to distinguish between primitive values and objects.

what is the best way to check variable type in javascript

The best way is to use the typeof keyword.

typeof "hello" // "string"

The typeof operator maps an operand to one of six values: "string", "number", "object", "function", "undefined" and "boolean". The instanceof method tests if the provided function's prototype is in the object's prototype chain.

This Wikibooks article along with this MDN articles does a pretty good job of summing up JavaScript's types.

How to find out the variable type in JavaScript?

// test data
var myArray = ['a', 'b', 'c'];

// the usual typeof isn't very useful
alert(typeof myArray);

// this instance of method tests the array
// to see if it is an instance of the 'Array'
// constructor, which it is!
alert(myArray instanceof Array)

click here

Finding a type of a variable in JS

There're several issues in your code:

  1. You should check the type of x before you judge it's even or odd.

  2. The type of x can only be string since it's come from prompt, but you can still know if it's a valid number string by isNaN() function.

  3. If you want to know whether a type of a variable is number or not, it should be typeof x !== 'number'. typeof x === '!Number' will never be true(also the case matters).

Here's an example that how you could write the code:

let x = prompt("Enter your value: ");

if (isNaN(x)){
console.log("Whoops, it seems like you're mistaken");
} else if(x % 2 === 0) {
console.log("x is an even number");
} else {
console.log("x is an odd number")
}

Better way to get type of a Javascript variable?

Angus Croll recently wrote an interesting blog post about this -

http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/

He goes through the pros and cons of the various methods then defines a new method 'toType' -

var toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}

How to get a variable type in Typescript?

For :

abc:number|string;

Use the JavaScript operator typeof:

if (typeof abc === "number") {
// do something
}

TypeScript understands typeof /p>

This is called a typeguard.

More

For classes you would use instanceof e.g.

class Foo {}
class Bar {}

// Later
if (fooOrBar instanceof Foo){
// TypeScript now knows that `fooOrBar` is `Foo`
}

There are also other type guards e.g. in etc https://basarat.gitbook.io/typescript/type-system/typeguard

How does Javascript know what type a variable is?

JavaScript sets the variable type based on the value assignment. For example when JavaScript encounters the following code it knows that myVariable should be of type number:

var myVariable = 10;

Similarly, JavaScript will detect in the following example that the variable type is string:

var myVariable = "Hello World!";

JavaScript is also much more flexible than many other programming languages. With languages such as Java a variable must be declared to be a particular type when it is created and once created, the type cannot be changed. This is referred to as strong typing. JavaScript, on the other hand, allows the type of a variable to be changed at any time simply by assigning a value of a different type (better known as loose typing).

The following example is perfectly valid use of a variable in JavaScript. At creation time, the variable is clearly of type number. A later assignment of a string to this variable changes the type from number to string.

var myVariable = 10;
myVariable = "This is now a string type variable";

The variable’s data type is the JavaScript scripting engine’s interpretation of the type of data that variable is currently holding. A string variable holds a string; a number variable holds a number value, and so on. However, unlike many other languages, in JavaScript, the same variable can hold different types of data, all within the same application. This is a concept known by the terms loose typing and dynamic typing, both of which mean that a JavaScript variable can hold different data types at different times depending on context.

Complete article here: http://www.techotopia.com/index.php/JavaScript_Variable_Types

Another Article Which may help you: http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html

Useful links:

ECMAScript Language Specification

ECMAScript BNF Grammar

JAVAScript BNF Gramar

Check whether variable is number or string in JavaScript

If you're dealing with literal notation, and not constructors, you can use typeof:.

typeof "Hello World"; // string
typeof 123; // number

If you're creating numbers and strings via a constructor, such as var foo = new String("foo"), you should keep in mind that typeof may return object for foo.

Perhaps a more foolproof method of checking the type would be to utilize the method found in underscore.js (annotated source can be found here),

var toString = Object.prototype.toString;

_.isString = function (obj) {
return toString.call(obj) == '[object String]';
}

This returns a boolean true for the following:

_.isString("Jonathan"); // true
_.isString(new String("Jonathan")); // true

How to determine a variable type in TypeScript?

if (typeof obj === 'number') {
// do stuff
} else if (typeof obj === 'object') {
// do stuff
}


Related Topics



Leave a reply



Submit