Search code examples
javascriptstringcomparison

How to compare string in javascript so that empty equals null


what can be the fastest code to have this check :

two strings are different only if they have different characters ?

so that

null == undefined == ''

now i use

if(!s1 && !!s2 
||
!!s1 && !s2
||
!!s1 && !!s2 && s1 != s2
)

but does not cover all cases


Solution

  • (s1 || '') == (s2 || '')
    

    || will convert any falsey value to an empty string.

    This will work as long as the variables are guaranteed to hold either a string, null, or undefined. If it can have a number, 0 will also be converted to an empty string, so 0 == '' would be true.

    Numeric strings are strings, so this will still work for them.