Unhandled type to empty string not working

时间:2019-01-15 18:11:34

标签: javascript

I am trying to create an isEmpty function that will verify any value and return it to empty string if value is null or undefined.

My below function for some reason is not working and value still comes out as unhandled. When I do straight up typeof, it seems to be working fine. Is there anything I am missing?

const isEmpty = value => {
  value === undefined ||
    typeof value === "undefined" ||
    value === null ||
    (typeof value === "object" && Object.keys(value).length === 0) ||
    (typeof value === "string" && value.trim().length === 0);
};

  const data = {};
  data.handle = !isEmpty(data.handle) ? data.handle : "";
  console.log("data.handle is still undefined: " + typeof data.handle);

 if (typeof data.handle === "undefined") {
 data.handle = "";
 console.log("empty string yes!!!");
   }

 

2 个答案:

答案 0 :(得分:2)

MDN - Arrow Functions

Arrow functions can have either a "concise body" or the usual "block body".

In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement.

Because you've wrapped your method in curly brackets, it is considered block body.

Either add a return before it, or easier yet, make it a concise body by removing the curly brackets:

const isEmpty = value =>
  value === undefined ||
  typeof value === "undefined" ||
  value === null ||
  (typeof value === "object" && Object.keys(value).length === 0) ||
  (typeof value === "string" && value.trim().length === 0);

const data = {};
data.handle = !isEmpty(data.handle) ? data.handle : "";
console.log("data.handle is still undefined: " + typeof data.handle);

if (typeof data.handle === "undefined") {
  data.handle = "";
  console.log("empty string yes!!!");
}

答案 1 :(得分:1)

you are missing your return statement, thus your function returns undefined

const isEmpty = value => {
  //you are not returning anything
  return value === undefined ||
    typeof value === "undefined" ||
    value === null ||
    (typeof value === "object" && Object.keys(value).length === 0) ||
    (typeof value === "string" && value.trim().length === 0);
};

const data = {};
data.handle = !isEmpty(data.handle) ? data.handle : "";
console.log("data.handle is still undefined: " + typeof data.handle);

if (typeof data.handle === "undefined") {
  data.handle = "";
  console.log("empty string yes!!!");
}