Search code examples
javascriptobject-type

Javascript Function is treating my string argument like an integer


I have a javascript function that contains an argument.

<a href="#" onclick="changeAvatar(0684839741);">Click here</a>

I need that argument to be a string because sometimes there will be Letters or a Leading 0 that I will need to preserve like in this example.

I checked to make sure that the argument that is passed in is a string with

x.constructor === String

But in my changeAvatar function, the argument comes through as no longer a string. Instead it is a number and removes the leading zero or breaks if it contains a letter.

How do I get the argument to retain it's type?


Solution

  • You've typed it as a javascript number as this line of javascript evaluates it to a number:

    changeAvatar(0684839741);
    

    If you want it to be a string, you have to do it this way where you explicitly declare it as a string like:

    changeAvatar('0684839741');
    

    which means the whole line should be this:

    <a href="#" onclick="changeAvatar('0684839741');">Click here</a>