Hedge
Hedge

Reputation: 16748

Shortest way to convert bool value to its string representation (e.g. 'true')

Basically I need to convert a 'boolean' type value into its equivalent as a string (true or false) and I am wondering whether there is a shorter (even if its slower) way than doing boolVal ? 'true' : 'false?

So is there a shorter way to accomplish the following? All ES2015-2018 goodies can be used if it helps :)

const boolVal = true
const boolStr = boolVal ? 'true' : 'false'

EDIT: I created a small benchmark of the presented solutions. https://jsperf.com/bool-to-string-conversion

benchmark of bool to string conversion

Upvotes: 0

Views: 1251

Answers (3)

Bartłomiej Gładys
Bartłomiej Gładys

Reputation: 4615

You can use String() as a function

const t = String(true)
const f = String(false)

console.log(t, f, typeof t, typeof f);

EDIT

String() is slower than toString()

const time = 10000000

  console.time('toString')
  for(let i =0 ; i< time; i++)
    true.toString()
  console.timeEnd('toString')

  console.time('String(bool)')
  for(let i =0 ; i< time; i++)
    String(true)
  console.timeEnd('String(bool)')

But... What if we are not sure that our boolean value exist?

const u = undefined;
const n = null;

// String()
console.log('String( undefined ): ', String(u), typeof String(n));
console.log('String( null ): ', String(n), typeof String(n));

// toString() :) 

console.log( u.toString() );

Upvotes: 2

Peshraw H. Ahmed
Peshraw H. Ahmed

Reputation: 469

this should work i think:

boolStr = boolVal.toString()

Edit: I tested and it works. https://jsbin.com/bapuvoqibo/edit?html,console,output

You can check out this link

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/toString

Upvotes: 1

31piy
31piy

Reputation: 23859

You can call toString() on the variable to get its string equivalent:

var a = true.toString();
var b = false.toString();

console.log(a, b, typeof a, typeof b);

Upvotes: 7

Related Questions