This forum is now read-only. Please use our new forums! Go to forums

banner
Close banner
0 points
Submitted by jurowe
over 8 years

11/12 Explaining parseInt()

So “Filling Out the Cases” makes a rather big jump in syntax vocabulary from lesson 10/12. First it throws a switch statement at the user with no explanation but also introduces the parseInt() function. Would someone be willing to explain parseInt() and how “switch(parseInt(key.which, 10))” is working in lesson 11/12? I don’t remember ever seeing it before, either in the CC jQuery lessons or the JavaScript ones.

Answer 55d80a979376767944000368

3 votes

Permalink

As the name suggests, the function parses an integer out of a string (or float) expression.

console.log(parseInt("1010", 2)); // binary to dec => 10
console.log(parseInt("A", 16)); // hexadecimal to dec => 10
console.log(parseInt("FF", 16)); // hexadecimal to dec => 255
console.log(parseInt("31", 8)); // octal to dec => 25

And we should toss in,

console.log(parseInt("42", 10)); // string dec to dec => 42

The second parameter is the radix or number base represented by the string. We can use this method to parse out the integral of a float, as earlier mentioned:

console.log(parseInt(Math.PI, 10)); // 3

JavaScript defaults to base 10 but best practice is to always include the radix in this expression.

key.which is pretty self-explanatory… Which key? key is the name we gave the transient KeyboardEvent Object in the parameter of the handler function. This lets us view all the properties of the event object, specifically the which property.

Tip: Since we are using the .keydown() method, this value will be uppercase ASCII for the letter keys if you wish to also incorporate a,s,w,d for the left hand.

Object data can be either string or number and still represent a number, as we’ve seen. Depending on the user agent, which might be a string, or it might be a number. parseInt() let’s us treat it as a number so it matches our case expressions, which are all numbers in this program.

I did my own study of the KeyboardEvent Object in Codebits. It only displays data and not methods. You might find it useful to examine. JavaScript is loaded with these kinds of objects, and this is a good one to understand.

points
Submitted by Roy
over 8 years

1 comments

jurowe over 8 years

This is very helpful. Thanks so much for taking the time to walk me through this!