8

Strings in JavaScript have a length property like arrays, but they don't have methods such as forEach or reduce.

Does this mean that strings are array-like objects?

2
  • 6
    No, in JS strings are primitives. In order to use the string methods, a temporary object is created. Commented Aug 13, 2018 at 12:04
  • 1
    Notice, that there are some methods in String.prototype too ... Commented Aug 13, 2018 at 12:13

3 Answers 3

13

The term "array-like" usually refers to an object having an integer-valued .length property and correspondingly many elements stored in integer-keyed properties, so that we can access them by index like an array. Strings certainly fulfill that requirement.

No, strings do not have all the methods that arrays have. They don't inherit from Array.prototype, they are not real arrays - they're just array-like. You can however trivially convert a string to an array, either by ….split('') or by Array.from(…).

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

2 Comments

Hmmm, now I'm confused. You are saying that strings are array-like but @Teemu is saying that they aren't (please see the very first comment).
@user1941537 Normal strings are no objects (that's what Teemu said), but they still are array-like. When you access a property on a primitive value, it does get implicitly coerced to a temporary object though
2

According to the documentation these functions does not exist (Documentation).

But you can add functions to the String prototype

// forEach function
String.prototype.forEach = function (f) {
  for (i=0; i < this.length; ++i) {
    f(this[i]);
  }
}


// reduce function
String.prototype.reduce = function (f, start) {
  result = (start == undefined) ? null : start
  for(i = 0; i < this.length; ++i) {
    result += f(this[i])
  }
  return result
}

Comments

1

In javaScript the string letters are get stored in the indexed manner,both primitive as well as the object type string get stored in the indexed value of the string reference name. Then a question come to mind that why we convert string to array in javaScript,well if we want to sort the letters we need sort method which javaScript array consist.String contain no sort method.Sting contain some property like length,but srting does not contain all the methods an Array contain. If we apply sort method in string it give an error that "stringName.sort is not a function".

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.