user3639366
user3639366

Reputation: 9

Javascript typeof() behaves unexpectedly

A variant of W3Schools...http://www.w3schools.com/js/tryit.asp?filename=tryjs_typeof .... Seems to think '4' is a string, is this expected? I don't think so.

<!DOCTYPE html>
<html>
<body>
<p>The global function typeof() returns the type of variables:</p>
<button id='Clothing-4' onclick="myFunction(this)">4</button>
<p id="demo"></p>
<script>
function myFunction(button) {
    var buttonID=button.id; //Button ID is [type]-[action]
    var buttonparts = buttonID.split('-');
    itemType=buttonparts[0];
//Tried using buttonparts[1];
    var buttonAction=buttonID.substr(buttonID.indexOf('-')+1,buttonID.length)
    document.getElementById("demo").innerHTML = 
    "|"+buttonAction+"|" + "<br>" + 
    typeof(buttonAction) + "<br>" + 
    typeof("john") + "<br>" + 
    typeof(3.14) + "<br>" +
    typeof(false) + "<br>" +
    typeof({name:'john', age:34});
}
</script>
</body>
</html>

Upvotes: 0

Views: 108

Answers (3)

Daniel
Daniel

Reputation: 1940

Yes, it is expected. The button's id is represented as a string; you know this as you are using string related functions (substr()) to extract the character 4. Notice how I said character. If you pull a character (or characters) from a string, expect them to be strings. JavaScript will not automatically parse every character you extract from a string to see if it's a number. You must do that yourself with something like parseInt().

Remember, typeof doesn't do any parsing. It looks at the actual type of the object representing the value you pass it. It will point out the difference between 4 being a Number and "4" being a string.

Upvotes: 1

Mofi
Mofi

Reputation: 49086

The value of the button element is here a string. The string value is "4". The object holding "4" is a string object. The first byte of this string object has the hexadecimal value 34 and not decimal value 4.

Therefore function typeof returns correct string as type of the object. You would need the function parseInt to convert the number string into a number value.

Upvotes: 0

Chirag Vidani
Chirag Vidani

Reputation: 2577

When you specify a value of type string, the typeof() will return it as string, as you specified typeof('4'), the 4 is specified as string so it returns string

If you passtypeof(4) then it will return number

Upvotes: 0

Related Questions