0

Can someone please advise why the 'inputValue' variable in the below function is not being converted into a Number. I was expecting the second console.log to report that the variable is now a Number (since I applied parseInt to it). But apparently its still a String.

function checkIfNum(){
    var inputValue = document.getElementsByTagName('input')[0].value;
    console.log(inputValue);

    // Convert to a number
    parseInt(inputValue);

    console.log(typeof(inputValue));
}

3 Answers 3

3

You haven't done anything with the result of the parseInt so as it stands, you are doing typeof on the original value of inputValue which is a string. Assign the result of parseInt to inputValue and your code will work fine:

function checkIfNum(){
    var inputValue = document.getElementsByTagName('input')[0].value;
    console.log(inputValue);

    // Assign the result of parseInt
    inputValue = parseInt(inputValue, 10);

    console.log(typeof(inputValue));
}

JsFiddle (Stack Snippets appears to be down).

It's also worth nothing that I added a radix to your parseInt call to ensure it's parsed as decimal on some older browsers.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks RGraham - one day I'll get a programmer's brain.
@swisstony Hey, we all make mistakes! It's easier for other people to see problems in code than it is to see your own :)
1

Because you're not assigning the result of parseInt to anything, and specifically not to inputValue. To correct:

inputValue = parseInt(inputValue);

Comments

0

You must store the returned value from parseInt(inputValue) as a new variable or overwrite the existing one

function checkIfNum(){
var inputValue = document.getElementsByTagName('input')[0].value;
console.log(inputValue);

// Convert to a number
var newInputValue = parseInt(inputValue);

console.log(typeof(newInputValue));
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.