当我有一个条件 `if (bool = true)` 时,永远不会命中 else 分支。为什么?

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

这是挑战:

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'.>

这是我写的:

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."

除了大家已经指出的if (bool = true)部分(你可以用if (bool)),你忘了在else语句中添加return。应该是:

} else {
    return 'Everyone is busy this weekend'
}

完整代码:

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."

但是如果你想给你的老师留下深刻印象,请这样做:

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

部分帮手:
Arrow function expressions
Conditional (ternary) operator