Search code examples
javascriptif-statementecmascript-6undefined

What is the difference between val?.toLocaleString() and using an if statement to check undefined


I have this:

return '£' + val?.toLocaleString();

to check if val has a value, however I'm not sure how safe this is compared to the following:

if(val) {
    return '£' + val.toLocaleString();
}
return val

Could someone help me breakdown what the differences are here and why one is preferable, if that is the case?


Solution

  • First one if the val is undefined or null it will concate the value of val with undefined

    function format(val) {
      return '£' + val?.toLocaleString();
    }
    
    console.log(format())
    console.log(format(null))
    console.log(format(3))

    The second one will only make concatenation if val is a truthy value, else will return val as it's

    Just keep in mind that zero is a falsy value.

    function format(val) {
      if(val) {
        return '£' + val.toLocaleString();
      }
      return val
    }
    
    console.log(format())
    console.log(format(0))
    console.log(format(3))