Write a clean convertToNumber function, if value is a number I have a function that creates filters for some data. The filters get added to an array and then (later) chained through the reduce function (the chaining part not part of my question).
The data I receive are all strings but can actually be numbers, eg {name:&quot;-45.6&quot;}. If it can be a number, I want the value to be converted to a number.
formFilters = (builder) =&gt; {
    const filters = [];
    builder.forEach(b =&gt; {
        let {filtername, operator, value} = b;

        if(!value) return;

        if(isNumber(value)){
            value = Number(value);
        }

        switch (operator) {
            case &quot;=&quot;:
                filters.push((item) =&gt; convertToNumber(item[filtername]) === value);
                break;
            case &quot;&lt;&quot;:
                filters.push((item) =&gt; convertToNumber(item[filtername]) &lt; value);
                break;
            case &quot;&gt;&quot;:
                filters.push((item) =&gt; convertToNumber(item[filtername]) &gt; value);
            
        }
    });
    return filters;
}

function convertToNumber(value){
    const number = Number(value);
    if (!Number.isNaN(number)) return number;
    return value;
}

This works but I'm wondering if there's a cleaner way of converting the value to a number if it is a number?
One problem with Number(value); is that it casts falsy values as 0 and truthy values as 1.
That means that an empty string becomes 0, which may not be what you expect.
You could make a regular expression test on the input to determine if it fits your expectations for a number.


let input = document.getElementById('input');
let result = document.getElementById('result');

function IsANumber() {
  let isItANumber = input.value.match(/^-?\d*\.?\d+$/);
  result.innerHTML = isItANumber ? 'true' : 'false';
}
&lt;input id="input" onchange="IsANumber()" onkeyup="IsANumber()" /&gt;&lt;br/&gt; Is a number: &lt;span id="result"&gt;&lt;/span&gt;



The example above will not fail in truthy/falsy cases, but it will determine strings like &quot;Infinity&quot; to not be numbers too.
Therefore it may need to be modified if you have to parse these to numeric values.