Javascript == operator between single value and array -
can please explain why below statements alert 'check passed' in javascript? code comparing string object against array, , expecting fail.
var somearray = ['current']; if('current' == somearray){ alert('check passed'); }else{ alert('check failed'); } it alerts 'check passed'.
when comparing == javascript tries coerce left , right values same types. in case tries coerce them both strings.
when arrays coerced strings(its tostring function called) each element of array joined together. in case ["current"] becomes "current" so:
"current" == somearray //becomes "current" == "current" with multiple elements
["current","values"] become "current,values"
if not want happen use value , type compare operator ===
if("current" === somearray){ alert('check passed'); }else{ alert('check failed'); } demo
var somearray = ["current"]; if("current" === somearray){ alert('check passed'); }else{ alert('check failed'); }
Comments
Post a Comment