1

I noticed that the correct

return str.slice(0, res);

returns the same value as the incorrect

var str = "some_string";
return str.slice(str, res);

In this case str is a string and res is a numeric quantity.

My guess is that some how because slice expects a numeric quantity and does not get one ( for the first parameter ), it converts what it finds to a 0.

Is this expected behavior?

4
  • 1
    Lets have a look: es5.github.io/#x15.4.4.10. Yes, it is expected, if str cannot be converted to a value different from NaN. See es5.github.io/#x9.4. Commented May 27, 2014 at 17:48
  • Looking at the annotation that @Felix linked to, note 5. "Let relativeStart be ToInteger(start)." Commented May 27, 2014 at 17:51
  • I posted the wrong like (arrays instead of strings), but both behave the same in this regard. Commented May 27, 2014 at 17:54
  • Do you consider the one-character string 5 (as opposed to the integer 5) to be a "numeric quantity"? Commented May 27, 2014 at 17:56

2 Answers 2

1

JavaScript provides implicit type coercion. That means if an integer is expected (as is the case here), it will convert the value provided to an integer. If no sensible value can be divined, zero is used.

If an integer is provided, great!

If a string is provided and it looks like a integer (e.g. str.slice("5", res)) it will be converted into the expected integer.

If a string is provided and it doesn't look like a number (e.g. str.slice("abc", res)), 0 is used.

Sign up to request clarification or add additional context in comments.

Comments

0

My guess is that some how because slice expects a numeric quantity and does not get one ( for the first parameter ), it converts what it finds to a 0.

That's basically what happens. .slice calls ToInteger on the first argument, which in turn calls ToNumber. But if the value cannot be converted to a number (if the result is NaN), it returns 0.

So, if you pass a numeric string as start, .slice would start at the mathematical value of that string. Any other string converts to 0.

2 Comments

Thanks, I always went to MDN to learn more about JS methods, but the ES spec is better it seems.
Yeah, MDN is good to get an idea about what is available and how to use it, but if you want an in-depth explanation of why things work the way they do, you have to go to the spec.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.