When I have a condition `if (bool = true)`, the else branch is never hit. Why?

511 Views Asked by At

Here's the challenge:

Create a function makePlans that accepts a string. This string should be a name. The function makePlans should call the function callFriend and return the result. callFriend accepts a boolean value and a string. Pass in the friendsAvailable variable and name to callFriend.

Create a function callFriend that accepts a boolean value and a string. If the boolean value is true, callFriend should return the string 'Plans made with NAME this weekend'. Otherwise it should return 'Everyone is busy this weekend'.>

Here's what I wrote:

let friendsAvailable = true;

function makePlans(name) {
  return callFriend(friendsAvailable, name);
}

function callFriend(bool, name) {
  if (bool = true) {
    return 'Plans made with ' + (name) + ' this weekend'
  } else {
    'Everyone is busy this weekend'
  }

}

console.log(makePlans("Mary")) // should return: "Plans made with Mary this weekend'
friendsAvailable = false;
console.log(makePlans("James")) //should return: "Everyone is busy this weekend."

2

There are 2 best solutions below

0
neku894 On BEST ANSWER

Besides the if (bool = true) part that everyone has already pointed out (you could use if (bool) for this), you forgot to add return in else statement. It should be:

} else {
    return 'Everyone is busy this weekend'
}
4
Mister Jojo On

Complete code:

let friendsAvailable = true;

function makePlans(name)
  {
  return callFriend(friendsAvailable, name);
  }

function callFriend(bool, name)
  {
  if (bool)  // or  if (bool===true), but testing if true is true is a little bit redundant
    {
    return 'Plans made with ' + (name) + ' this weekend'
    } 
  else 
    {
    return 'Everyone is busy this weekend'
    }
  }

console.log(makePlans("Mary")) // should return: "Plans made with Mary this weekend'
friendsAvailable = false;
console.log(makePlans("James")) //should return: "Everyone is busy this weekend."

But if you want to impress your teacher do this:

const
  callFriend = 
    (bool, name) =>
      bool 
       ? `Plans made with ${name} this weekend` 
       : 'Everyone is busy this weekend' 

const makePlans = name => callFriend(friendsAvailable, name);


let friendsAvailable = true

console.log(makePlans('Mary')) 

friendsAvailable = false

console.log(makePlans('James')) 

some helpers:
Arrow function expressions
Conditional (ternary) operator