user3293653
user3293653

Reputation:

Bug in use of slice() has no effect?

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?

Upvotes: 1

Views: 182

Answers (2)

ikegami
ikegami

Reputation: 386561

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.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 817030

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.

Upvotes: 0

Related Questions