2

how can I simplify this function in javascript:

checkMyString() {
  if (myString === undefined) {
    return false;
  } else if (myString === '') {
    return false;
  }
  return true;
}

Thanks in advance!

Sundeep Pidugu
  • 2,377
  • 2
  • 21
  • 43
  • return !!myString – Yuriy Piskunov Dec 15 '20 at 14:36
  • 1
    Does this answer your question? [Is there a standard function to check for null, undefined, or blank variables in JavaScript?](https://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in) – Sundeep Pidugu Dec 15 '20 at 14:51

4 Answers4

5

Both undefined and '' are falsy values, you can just check if the values are not falsy with !! operator. Read more here What is the !! (not not) operator in JavaScript?

// undefined
!!myString
// => false

// empty string
!!myString
// => false
Abraham
  • 8,525
  • 5
  • 47
  • 53
1

Use || operator

checkMyString() {
  if (myString === undefined || myString === "") {
    return false;
  }
  return true;
}

Or you could just directly return an expression

checkMyString() {
  return !(myString === undefined || myString === "");
}

If you want to check for all falsy values i.e 0, false, "", undefined, null and NaN then you can simply use Boolean

checkMyString() {
  return Boolean(myString)
}
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
1

You could also just depend on the truthy value and coerce it to a boolean if you absolutely want it to be a boolean:

function checkMyString(str) {
  return !!str;
}

let myStr = undefined;
console.log("Checking: undefined", checkMyString(myStr));

myStr = "";
console.log("Checking: '':", checkMyString(myStr));

myStr = null;
console.log("Checking: null:", checkMyString(myStr));

myStr = "my string";
console.log("Checking string value", checkMyString(myStr));
VLAZ
  • 26,331
  • 9
  • 49
  • 67
chad_
  • 3,749
  • 2
  • 22
  • 22
0

Same as you check if a string has some value in vanilla javascript:

function checkMyString(myString) {
  return myString ? true : false;
}

// Result: false
console.log(checkMyString());

// Result: false
console.log(checkMyString(undefined));

// Result: false
console.log(checkMyString(null));

// Result: false
console.log(checkMyString(''));

// Result: true
console.log(checkMyString('Value'));
Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130