JavaScript Tutorial for Programmers - String and Array

I still remember the days of debugging CORS problem when I put together some projects using JavaScript (& ajax), “a very particular programming language” in my first impression. Recently I got a great opportunity. The new role uses JS, the browser-side script that is now winning in all sides, as the major language. So I took it as a good chance to learn JS more systematically, and this series will be part of the outcome of my study. As the name implies, I will not cover primary level such as “if, else” (condition), “for” (or any kinds of loops), or basic OOP concepts. Instead, I will focus only on differences so you can learn this versatile language like reviewing a pull request, and use it the next day in your next awesome project.

First thing first, in JavaScript, strings are constant while arrays are mutable.

Example:

Result:

By the way, strings are marked with "" , '' or   (multiline code definition), and arrays are [].

More examples:

Results:

Interestingly, if you change the length of an array by force, the JavaScript runtime adds undefined into the array. But the string can not be modified this way because, as mentioned in the beginning, they are immutable.

Escape character \

JavaScript too uses \ to escape special characters (e.g., a " that is inside a string marked with ").

Example:

Result:

so \" represents a " literal; \n means a new line and \t, a tab. Search for “JavaScript special characters” in Google for the full list.

We can directly use ASCII and Unicode in strings with \ just like we did in C. But I will not elaborate further as I can not see an obvious use case of this feature in a high level language.

Concatenation

For strings, we use +, or string template:

Result:

Please note that grave accent () should be used for string template, not apostrophe (‘).

For array, use concat()

Result:

Access elements

Use [] for both:

Result:

Search

Use indexOf() for both.

Result:

No explanation…

Substring and subarray

Use substring() for string and slice() for array.

Example:

Result:

I hope this post gives you enough confidence to use these two everyday life data structures (types).

That's it. If you have any suggestions, or you just like the read, , and send me your comments. Thank you for your time and attention. I'll catch you later.