I was working another project this week and I wanted to talk about the .splice()
function in JavaScript...but then I started down a rabbit hole of having to write about other things, because there's some other things you should probably understand before using .splice()
.
For starters, let's talk about the relationship between Strings and Arrays in JavaScript. This will likely be a short series of articles. It might have been written before by someone else, but I'd like to give my own interpretation.
Strings and Arrays are like Yin and Yang. You use .split()
to split an string into an array. You use .join()
to join arrays into strings.
If you can exercise this dichotomy of two fundamental JavaScript types, you can understand the relationship between strings and array.
String split()
, Array join()
Whenever there is an array of strings requested, it is probably better to simply use .split()
rather than tediously adding every quotation mark and comma.
In these examples, there will be two comments. One showing the return value, and one showing the value of
arr
,str
, or other variables. This will be important to note throughout the examples
let arr;
// Returns 'undefined'
arr = "Whoever controls the splice controls the universe".split(" ");
// Returns: ["Whoever", "controls", "the", "splice", "controls the", "universe"]
// arr: ["Whoever", "controls", "the", "splice", "controls the", "universe"]
Conversely, what happens when we take that array and put it back together?
let str;
// Returns 'undefined'
str = ["Whoever", "controls", "the", "splice", "controls the", "universe"].join(" ");
// Returns: "Whoever controls the splice controls the universe"
// str = "Whoever controls the splice controls the universe"
You may have noticed that when we declare a variable. If we do our declarations on the same line as the assignment, the undefined
is returned, but arr
and str
have value.
let str = ["Whoever", "controls", "the", "splice", "controls the", "universe"].join(" ");
// Returns: undefined
// str = "Whoever controls the splice controls the universe"
For clarity, I will declare variables separate when we can in this sprint of short articles.
In the next article, I will talk about concatenation.
Top comments (0)