0

I was playing with a constant string in a loop from another question…
Here it is:

str = "abcd";
for (i = 0; i < 4; i++) {
  console.log(str[i]);
}

… and I ended up doing that:

for (i = 0; i < 4; i++) {
  console.log("abcd"[i]);
}

I didn't know this kind of coding was working before I tried!
How is this way of doing called?
Should it be avoided for any technical reason?

Thanks for any answer.

Takit Isy
  • 9,688
  • 3
  • 23
  • 47
  • 1
    Possible duplicate of [JavaScript access string chars as array](https://stackoverflow.com/questions/4051385/javascript-access-string-chars-as-array) – PM 77-1 Apr 19 '18 at 17:11
  • 3
    @PM77-1: No, the question isn't about that. – T.J. Crowder Apr 19 '18 at 17:12
  • @T.J.Crowder- **answers** to the linked question are fully applicable here. Especially, [this one](https://stackoverflow.com/a/4051431/2055998). – PM 77-1 Apr 19 '18 at 17:15
  • @PM77-1: I think we're reading the question quite differently (since I am familiar with SO's definition of "duplicate"). – T.J. Crowder Apr 19 '18 at 17:17
  • @PM77-1 It is applicable, and I know it. I know how to deal with a string, but that was never my question. – Takit Isy Apr 19 '18 at 17:17
  • You asked about "technical reasons" and the linked answer provides it. – PM 77-1 Apr 19 '18 at 17:19
  • If you are referring to **BEST PRACTICE**, you should avoid using a technique/mechanism that _just happens to appear working_ in a specific language. You would be using much the same resources as if would declare a variable that holds a reference to the string. In short, I would NOT accept that anyone in my team codes this way. – FDavidov Apr 19 '18 at 17:20

4 Answers4

3

How is this way of doing called?

I'm not aware of it having any specific name. You're just using a string literal inside the loop.

Should it be avoided for any technical reason?

With a string literal it probably doesn't matter, because string literals define primitive strings (and are likely reused by the JavaScript engine, as they're immutable). But if you were creating an object every time, that would be unnecessary overhead compared with just creating it once and reusing it.

For instance, if you were doing this:

for (var i = 0; i < 4; i++) {
  console.log([1, 2, 3, 4][i]);
}

That code tells the JavaScript engine to create that array each time the loop body runs, which is fast, but not instantaneous. (The JavaScript engine might be able to analyze the code and optimize it if the code were used enough that it seemed worth bothering, but that's a different topic.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • So, `[1, 2, 3, 4][i]` creates the object everytime but `"abcd"[i]` doesn't? What's the difference? – Takit Isy Apr 19 '18 at 17:22
  • @TakitIsy: As I said in the answer: `"abcd"` is a string literal, defining a string primitive (not an object), and the JavaScript engine can probably reuse that primitive. But that's a side point: You wouldn't want to use your alternate version anyway, there's no particularly good reason to vs. just using a variable. – T.J. Crowder Apr 19 '18 at 17:28
  • i would call it *inline constant*. – Nina Scholz Apr 19 '18 at 17:30
  • @NinaScholz: Literals are always constants. :-) (Though you'll find people getting misled on that point, because of the common but incorrect use of "object literal" and "array literal" for the syntaxes that are properly called "object initializer" and "array initializer".) – T.J. Crowder Apr 19 '18 at 17:33
  • Is there any method to ''see'' that the object is or isn't created at each iteration? Just for fun... :) – Takit Isy Apr 19 '18 at 18:45
  • @TakitIsy: Again: It isn't an object. (If it were, then it *would* be created each time, modulo optimization.) I'm not aware of a runtime way to know for sure. You could go digging through the source code of any of the open-source JavaScript engines (V8's is [here](https://chromium.googlesource.com/v8/v8.git), mirrored [here](https://github.com/v8/v8)). – T.J. Crowder Apr 20 '18 at 06:17
0

The way to tried is okay but not very useful as if you specify the string in the loop it becomes static to the loop.

It is advised to use Variable insteads of "HARDCODED" values.

krishnashu
  • 42
  • 5
-1

All your code really does is do away with the variable and index the "array-like" object directly.

Strings are "array-like" objects. They have .length property and can be indexed just as Arrays can be. They are not however, actual arrays and don't support the full Array API. JavaScript is full of "array-like" objects and they are certainly not anything to be avoided. To the contrary, it is a great feature of the language to be able to leverage this. It's just important to know when you have an actual Array and when you have an "array-like" object, so you don't use the latter incorrectly.

So, because "abcd" is array-like, there is no reason you can't place an index right after it:

"abcd"[2]
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
-1

Scott Marcus explains what's happening here well. As far as whether this should be avoided, many believe it is better to access chars in a string using chatAt() instead of bracket notation. Namely because:

  1. Bracket notation is part of ECMAScript 5 and therefore not universally supported

  2. The similarity to bracket notation of an array or hash object can be confusing. For instance, strings are immutable so you cannot set the value of a string at a certain index as you can with an array or hash. Using chatAt() can therefore elucidate that one should not expect this to be possible.

Source: string.charAt(x) or string[x]?

ztech
  • 560
  • 5
  • 13
  • 1
    I don't think there is anyone out there still concerned with IE 7 and you can't set a character in a string at all - - ever. Strings are immutable. – Scott Marcus Apr 19 '18 at 17:18
  • @ScottMarcus a little harsh there but I understand where you are coming from. I do strongly prefer the use of charAt() instead of bracket notation and did my best further clarify why in a revision. – ztech Apr 19 '18 at 17:27
  • The "source" you link to is 7 years old and that source gets its information from another source that is 10 years old. Also, since string immutability is a basic premise in almost all languages, the argument that `charAt()` somehow protects you from attempting to change a string really masks the larger issue. – Scott Marcus Apr 19 '18 at 17:28