FAQ: Code Challenges: JavaScript Fundamentals - truthyOrFalsy()

Can you please tell me what I’m doing wrong with my code:

const truthyOrFalsy = value => {
  if (value === true) {
    return true;
  } else {
    return false;
  }
}

console.log(truthyOrFalsy(0));

I got this error message:

If an argument that evaluates to truthy is passed in to the function, the function should return true

const truthyOrFalsy = x => Boolean(x);

This is one of those problems where a LOT of things work as a solution. But there is the one really really simple solution that solves all of the world’s problems…

const truthyOrFalsy = value => value ? true : false;

thinking about why this works is incredibly simple and also makes my brain hurt.

1 Like

My solution:

const truthyOrFalsy = (value) => {

if (value)

{return true}

else {return false}

}

Using logical operators…

const truthyOrFalsy = x => !! x;

Hello,
Why when you type NaN as the name of the value you get a syntax error??

You should see false

Can you show a screenshot of the error message, please? We’re not able to reproduce the error in sandbox.

I’m not seeing what I’m missing. the code is giving me an error!

const truthyOrFalsy = (username, Stranger) => {
if (username) {
truthyOrFalsy = username;
} else {
truthyOrFalsy = ‘Stranger’

}
};

// Uncomment the line below when you’re ready to try out your function
console.log(truthyOrFalsy(0)) // Should p

you can do it right even without the ternary operator

const truthyOrFalsy= num => {
if(num){
return true
}else {
return false
}
}

can you please explain or rewrite the code, I don’t fully understand it! thank you

The thing to do would be go back over all the previous lessons and look for tidbits that might have been missed the first time through.

1 Like

Hello friends! Could anyone explain what is wrong about my approach with this question? It seems to be running and functioning as the question intended.

const truthyOrFalsy = value => {
  if (Boolean(value) === false){
    return 'false';
  } else {
    return 'true';
  }
}

Only truthy values can make it into the first branch.

meaning, into the first condition(denoted in parenthesis)?
i ask because the body of the initial if-statement returns a truthy value (a string)

Boolean returns should not be strings. However, I did just run your code and the returns are correct. Just not used to seeing a comparison to false in an if condition. I wouldn’t recommend writing it like that for an interview question.

What condition should I put to make this code work?

const truthyOrFalsy = () => *CONDITION* ? true : false;

This piece of code works:

const truthyOrFalsy = value => value ? true : false;

However, I want to write the code without defining any variable value and passing it as a parameter for my function.

I keep getting a synthax error: unexpected Identifier when i use 0n. I tried this in JSFiddle but I dont get this error. see print screen. I also tried this with the solution.