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:
1 | var str = "123"; |
Result:
1 | 123 |
By the way, strings are marked with ""
, ''
or
(multiline code definition), and arrays are
[]
.
More examples:
1 | var str = "123"; |
Results:
1 | 123 |
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:
1 | alert("\""); |
Result:
1 | " |
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:
1 | var js = "JavaScript"; |
Result:
1 | I like JavaScript |
Please note that grave accent (`) should be used for string template, not apostrophe (‘).
For array, use concat()
1 | var arr = ['a', 'b', 'c']; |
Result:
1 | a,b,c,d,e,f |
Access elements
Use []
for both:
1 | var arr = ['a', 'b', 'c']; |
Result:
1 | a |
Search
Use indexOf()
for both.
1 | var arr = ['abc', 'xyz', 123, 789]; |
Result:
1 | 2 |
No explanation…
Substring and subarray
Use substring()
for string and slice()
for array.
Example:
1 | var str = "abcxyz";//a=>0 b=>1 c=>2 x=>3 y=>4 z=>5 |
Result:
1 | abcxy |
I hope this post gives you enough confidence to use these two everyday life data structures (types).