help with slice | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

help with slice

so I can do like this: function zero(x) { return (""+x).slice(2) } console.log(zero(123456789)); but why I can't do like this? function zero(x) { return (x).slice(2) } console.log(zero(123456789));

21st Mar 2019, 4:50 AM
Gabriel Junior
Gabriel Junior - avatar
3 Answers
+ 8
slice() function is a member function of String class. You can only use that with string, not with integers. But in the above mentioned program you have to use slice() with an int variable, i.e., x So, if you want to use that with any int, then you have to change int into string. So for converting into string ""+x is used.
21st Mar 2019, 4:52 AM
Letsintegreat
Letsintegreat - avatar
+ 6
Gabriel Junior Precisely, you are correct! 😋
21st Mar 2019, 4:59 AM
Letsintegreat
Letsintegreat - avatar
+ 2
oh so that's why function zero(x) { return String(x).slice(2) } console.log(zero(123456789)); also works
21st Mar 2019, 4:56 AM
Gabriel Junior
Gabriel Junior - avatar