Is there a standard function to check for null, undefined, or blank variables in JavaScript?

前端 未结 30 3566
眼角桃花
眼角桃花 2020-11-21 23:37

Is there a universal JavaScript function that checks that a variable has a value and ensures that it\'s not undefined or null? I\'ve got this code,

相关标签:
30条回答
  • 2020-11-22 00:16

    If you want to avoid getting true if the value is any of the following, according to jAndy's answer:

    • null
    • undefined
    • NaN
    • empty string ("")
    • 0
    • false

    One possible solution that might avoid getting truthy values is the following:

    function isUsable(valueToCheck) {
        if (valueToCheck === 0     || // Avoid returning false if the value is 0.
            valueToCheck === ''    || // Avoid returning false if the value is an empty string.
            valueToCheck === false || // Avoid returning false if the value is false.
            valueToCheck)             // Returns true if it isn't null, undefined, or NaN.
        {
            return true;
        } else {
            return false;
        }
    }
    

    It would be used as follows:

    if (isUsable(x)) {
        // It is usable!
    }
    // Make sure to avoid placing the logical NOT operator before the parameter (isUsable(!x)) and instead, use it before the function, to check the returned value.
    if (!isUsable(x)) {
        // It is NOT usable!
    }
    

    In addition to those scenarios, you may want to return false if the object or array is empty:

    • Object: {} (Using ECMA 7+)
    • Array: [] (Using ECMA 5+)

    You would go about it this way:

    function isEmptyObject(valueToCheck) {
        if(typeof valueToCheck === 'object' && !Object.keys(valueToCheck).length){
            // Object is empty!
            return true;
        } else {
            // Object is not empty!
            return false;
        }
    }
    
    function isEmptyArray(valueToCheck) {
        if(Array.isArray(valueToCheck) && !valueToCheck.length) {
            // Array is empty!
            return true;
        } else {
            // Array is not empty!
            return false;
        }
    }
    

    If you wish to check for all whitespace strings (" "), you may do the following:

    function isAllWhitespace(){
        if (valueToCheck.match(/^ *$/) !== null) {
            // Is all whitespaces!
            return true;
        } else {
            // Is not all whitespaces!
            return false;
        }
    }
    

    Note: hasOwnProperty returns true for empty strings, 0, false, NaN, null, and undefined, if the variable was declared as any of them, so it might not be the best to use. The function may be modified to use it to show that it was declared, but is not usable.

    0 讨论(0)
  • 2020-11-22 00:16
    function notEmpty(value){
      return (typeof value !== 'undefined' && value.trim().length);
    }
    

    it will also check white spaces (' ') along with following:

    • null ,undefined ,NaN ,empty ,string ("") ,0 ,false
    0 讨论(0)
  • 2020-11-22 00:17

    The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null.

    let customer = {
      name: "Carl",
      details: {
        age: 82,
        location: "Paradise Falls" // detailed address is unknown
      }
    };
    let customerCity = customer.details?.address?.city;
    

    The nullish coalescing operator may be used after optional chaining in order to build a default value when none was found:

    let customer = {
      name: "Carl",
      details: { age: 82 }
    };
    const customerCity = customer?.city ?? "Unknown city";
    console.log(customerCity); // Unknown city
    
    0 讨论(0)
  • 2020-11-22 00:20

    This condition check

    if (!!foo) {
        //foo is defined
    }
    

    is all you need.

    0 讨论(0)
  • 2020-11-22 00:20

    Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.

    function myFunction() {
        var data;  //The Values can be like as null, blank, undefined, zero you can test
    
        if(!(!(data)))
        {
            alert("data "+data);
        } 
        else 
        {
            alert("data is "+data);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 00:22

    You may find the following function useful:

    function typeOf(obj) {
      return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
    }
    

    Or in ES7 (comment if further improvements)

    function typeOf(obj) {
      const { toString } = Object.prototype;
      const stringified = obj::toString();
      const type = stringified.split(' ')[1].slice(0, -1);
    
      return type.toLowerCase();
    }
    

    Results:

    typeOf(); //undefined
    typeOf(null); //null
    typeOf(NaN); //number
    typeOf(5); //number
    typeOf({}); //object
    typeOf([]); //array
    typeOf(''); //string
    typeOf(function () {}); //function
    typeOf(/a/) //regexp
    typeOf(new Date()) //date
    typeOf(new WeakMap()) //weakmap
    typeOf(new Map()) //map
    

    "Note that the bind operator (::) is not part of ES2016 (ES7) nor any later edition of the ECMAScript standard at all. It's currently a stage 0 (strawman) proposal for being introduced to the language." – Simon Kjellberg. the author wishes to add his support for this beautiful proposal to receive royal ascension.

    0 讨论(0)
提交回复
热议问题