treecoder
treecoder

Reputation: 45101

Lodash -- array methods on strings

I have found that in lodash, the array methods also work on strings. For example:

> _.last('abc')
'c'

> _.indexOf('abc', 'x')
-1

Is this a standard behavior, and can this be relied on? The documentation does not say anything about it as far as I know.

Please note that the above methods are just examples. What I am more inclined to know is whether lodash expects its array methods to be used on strings. I need to write production code and I can not rely on something that works but the standard docs have not mentioned or acknowledged or guaranteed.

Upvotes: 0

Views: 362

Answers (1)

cejast
cejast

Reputation: 1007

You can consider a String to essentially be an array of characters. They have certain properties and functions that you'd find on an Array, such as .length and .indexOf().

Based on the lodash source for .last and .indexOf, they use the .length property to determine the last character, or index of a character within an array.

These implementations, while could work with Strings in most scenarios because of their Array-like nature, will not work in all, since lodash uses bracket notation (str[0]) to find the last character/index of an item with an array. This is not universally supported e.g. for IE7, which is why the charAt method exists for accessing a character at a given index for a string.

You can do both of these things natively:

var str = 'mystring';
str.charAt(str.length - 1); // 'g'

var str = 'mystring';
str.indexOf('y') // 1`

Upvotes: 3

Related Questions