Chass Long
Chass Long

Reputation: 549

A strange implementation of return 'Yes', 'No' instead of true, false in javascript

Recently, I've seen this alternate implementation of this

function boolToWord( bool ){
  return bool ? "yes" : "no" ;
}  

to this

function boolToWord( bool ){
  return ['No','Yes'][+bool];
}

May I have some clarification as to what the ['No','Yes'][+bool]; doing? I'm only aware of that having +bool simply turning the boolean into 0 or 1 depending on the boolean value. But how is it using it as an index to select the value from the previous array ['No', 'Yes'] is this a javascript-only feature? What is this called? Thank you.

Upvotes: 1

Views: 2610

Answers (3)

Terry Lennox
Terry Lennox

Reputation: 30685

['No','Yes'] is an array, and we're going to access either index 0 or 1, corresponding to either false or true.

When we use the + operator on bool, e.g. +bool we're converting to an integer of 0 or 1;

Below is a more verbose version of boolToWord, logging intermediate values, not to be used in production, merely to illustrate the principle:

function boolToWord( bool ) {
  let index = +bool;
  let array = ['No','Yes'];
  console.log(`Bool: ${bool}, array index: ${index}, array:`, array );
  let result = array[index];
  console.log("Result:", result);
  return result;
}

boolToWord(false);
boolToWord(true);

Logging output for +false, +true:

console.log("+false = ",+false);
console.log("+true = ",+true);

Upvotes: 1

Yuriy Yakym
Yuriy Yakym

Reputation: 3911

['No', 'Yes'] is an array. Under index 0 you have No, and under index 1 you have Yes. When you use +bool it converts this boolean to a number:

  • +false === 0
  • +true === 1

so that having +bool you will either receive 0 or 1, and pick corresponding value from the array

Upvotes: 0

Mureinik
Mureinik

Reputation: 311393

['No', 'Yes'] is an array literal, and like any other array, it can be accessed by an index. Once bool is converted to an integer of 0 or 1 as you described, the array element is accessed. Note that arrays in Javascript are zero-based, so the first element of the array has index 0 and the second has index 1.

Upvotes: 1

Related Questions