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!

2

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

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)
}

Comments

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));

Comments

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'));

1 Comment

You can use Boolean(myString) instead of myString ? true : false;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.