2

I'm new to JavaScript and is writing a simple website using Netbeans. Since JavaScript is dynamically typed language, I was wondering how can I find out the type of a variable in situations where I am unsure of.

For example, how can I find out the variable type of emailAddress or domainPart in the code below?

function getEmailAndDomainParts(){
                var emailAddress = document.getElementById("EmailAddress").value;
                var emailPart = emailAddress.substring(0, emailAddress.indexOf("@"));
                var domainPart = emailAddress.substring(emailAddress.indexOf("@") + 1);

                document.getElementById("Email").value = emailPart;
                document.getElementById("Domain").value = domainPart;
            }
halfer
  • 19,824
  • 17
  • 99
  • 186
Thor
  • 9,638
  • 15
  • 62
  • 137
  • You can't find out the type of a *variable* because they don't have a type, but you can find out the type of the *value* in the variable using the `typeof` operator. Having said that, **all of your values are strings.** If `emailAddress` didn't contain a string you couldn't use `.substring()` on it, and `.substring()` will always return a string. – nnnnnn Jun 28 '16 at 06:12
  • Did you try using typeof keyword? Something like: typeof emailAddress – Nguyen Tuan Anh Jun 28 '16 at 06:12
  • 2
    Please allows look around first, this question been answered many many times before – Daniel Brose Jun 28 '16 at 06:12

3 Answers3

1
// 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

  • You can also use `Array.isArray(myArray)` – Rajesh Jun 28 '16 at 06:18
  • This doesn't really answer the question. You wouldn't use `instanceof` to test for strings, numbers, and boolean values (and even if that worked you'd have to call it multiple times until you got a match). – nnnnnn Jun 28 '16 at 06:19
1

you can use typeof: The typeof operator returns a string indicating the type of the unevaluated operand

qunshan
  • 57
  • 3
1

As pointed out in the comments, you cannot check the type of your variable but you can check the type of your variable's value using typeof():

x = "hello";
y = 123;
z = true;
console.log(typeof(x)); //Will return "string"
console.log(typeof(y)); //Will return "number"
console.log(typeof(z)); //Will return "boolean"
Bubble Hacker
  • 6,425
  • 1
  • 17
  • 24
  • 1
    Note that `typeof` is an operator, not a function. (The parentheses don't hurt, but they're not needed.) – nnnnnn Jun 28 '16 at 06:21