-4

I have a function which has a parameter:

function checkThis(isAlive) {
    // Blah blah
}

How do I check if the parameter isAlive was passed, even if it was passed as false?

isAlive must be a boolean.

daCoda
  • 3,583
  • 5
  • 33
  • 38

3 Answers3

1

If you wanna check if the parameter was passed you should check if its value is undefined, otherwise it was set:

function checkThis(isAlive) {
    if (isAlive === undefined) {
      console.log("isAlive was not set")
    } else {
      console.log(`isAlive was set and its value is ${isAlive}`)
    }
}

checkThis()
checkThis("I am")
checkThis(false)
Telmo Trooper
  • 4,993
  • 1
  • 30
  • 35
1

How do I check if the parameter isAlive was passed, even if it was passed as false?

This is how I did it:

function checkThis(isAlive) {
   if (isAlive !== undefined && !isAlive) {
      console.log("isAlive is defined AND it is false");
    }
}
daCoda
  • 3,583
  • 5
  • 33
  • 38
0

You can check arguments.length

function checkThis(isAlive) {
    return arguments.length && isAlive === false ? 'Passed false arguments' : isAlive
}

console.log(checkThis())
console.log(checkThis(undefined))
console.log(checkThis("I am"))
console.log(checkThis(false))
Code Maniac
  • 37,143
  • 5
  • 39
  • 60