Skip to content

Latest commit

 

History

History
42 lines (35 loc) · 1.03 KB

2-convert-a-number-to-a-string!.md

File metadata and controls

42 lines (35 loc) · 1.03 KB

Problem:

We need a function that can transform a number into a string.

What ways of achieving this do you know?

Examples:

numberToString(123); // returns '123';`   
numberToString(999); // returns '999';`

Solution

function numberToString(num) {
  return num.toString();
}
function numberToString(num) {
  return String(num);
}

Note: String(value) vs value.toString()

  • value.ToString() will cause error if value is null or undefined
  • String(value) mostly works like value + ''
function numberToString(num) {
  return num + '';
}
function numberToString(num) {
  return '' + num;
}

Note: concatenation

  • Aything concatenated with string will coerced to string
const numberToString = num => `${num}`;