JavaScript check if variable exists (is defined/initialized)

前端 未结 29 1776
孤城傲影
孤城傲影 2020-11-22 00:59

Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))



        
29条回答
  •  眼角桃花
    2020-11-22 01:39

    In many cases, using:

    if (elem) { // or !elem
    

    will do the job for you!... this will check these below cases:

    1. undefined: if the value is not defined and it's undefined
    2. null: if it's null, for example, if a DOM element not exists...
    3. empty string: ''
    4. 0: number zero
    5. NaN: not a number
    6. false

    So it will cover off kind of all cases, but there are always weird cases which we'd like to cover as well, for example, a string with spaces, like this ' ' one, this will be defined in javascript as it has spaces inside string... for example in this case you add one more check using trim(), like:

    if(elem) {
    
    if(typeof elem === 'string' && elem.trim()) {
    ///
    

    Also, these checks are for values only, as objects and arrays work differently in Javascript, empty array [] and empty object {} are always true.

    I create the image below to show a quick brief of the answer:

提交回复
热议问题