JavaScript join, Array.isArray, Array-Like Objects and Strings as Arrays
Converting arrays to strings with join and toString, checking for arrays reliably with Array.isArray, working with array-like objects (arguments, NodeList, { length }) via Array.from and borrowed methods, and treating strings as read-only arrays of characters, including the emoji trap.
kvi5hnuCode Sprout team member6 min readOn this page
This last article on arrays covers the edges: turning arrays into strings, telling arrays apart from other values, and the "almost arrays" (array-like objects and strings) you'll meet in the DOM, in old code and in interviews.
join: array to string
join(separator) converts every element to a string and glues them together with the separator, a comma by default:
const dateParts = ["2024", "06", "01"];
console.log(dateParts.join("-"));
console.log(dateParts.join()); // default separator ","
console.log(dateParts.join(""));
console.log([null, undefined, 1].join("-"));
console.log(new Array(4).join("ab")); // 3 separators between 4 empty slots
2024-06-01
2024,06,01
20240601
--1
ababab
null, undefined and holes become empty strings. Nested arrays are converted with their own toString, so they're flattened with commas whatever separator you pass: [1, [2, [3]]].join(";") is "1;2,3".
join is the inverse of the string method split (part 11): "a,b".split(",") gives ["a", "b"], and join(",") puts it back.
Common uses: building CSS class names (["btn", isActive && "active"].filter(Boolean).join(" ")), CSV lines, readable lists and paths.
toString and implicit conversion
An array's toString() is join() with no separator argument, so it happens whenever an array is converted to a string: in template literals, + with a string, and == comparisons (article 31):
const tags = ["js", "web"];
console.log(`Tags: ${tags}`);
console.log(["a"] + ["b"], [] + [], String([1, [2, 3]]));
console.log([1, 2] == "1,2");
Tags: js,web
ab 1,2,3
true
[] + [] is the empty string: both arrays convert to "". To show an array to a user, join(", ") is usually what you want; for saving or sending it, use JSON.stringify (article 50), which keeps types and nesting.
toLocaleString() calls toLocaleString on each element, so numbers and dates are formatted for a locale: [1.5, 1000].toLocaleString("en-US") gives "1.5,1,000", which shows why it's rarely useful with the comma separator.
Array.isArray: is this really an array?
typeof returns "object" for arrays, so it can't tell them apart from other objects. Use Array.isArray:
console.log(typeof [], Array.isArray([]));
console.log(Array.isArray({ length: 0 }), Array.isArray("ab"), Array.isArray(new Uint8Array(2)));
object true
false false false
Typed arrays (part 11) aren't arrays in this sense, and neither are array-like objects.
Why not value instanceof Array? It checks the prototype chain, which gives wrong answers in two cases: arrays created in another realm (an iframe or a Node vm context has its own Array constructor, so instanceof returns false), and objects that merely inherit from Array.prototype:
const impostor = Object.create(Array.prototype);
console.log(impostor instanceof Array, Array.isArray(impostor));
true false
Array.isArray checks what the object actually is, so it's the reliable test.
Array-like objects
An array-like object has a numeric length and elements at indexes 0, 1, 2..., but isn't a real array: it doesn't inherit from Array.prototype, so it has no map, filter or push, and its length doesn't update itself. You'll meet them in several places:
- the
argumentsobject inside regular functions (part 8); - DOM collections:
document.querySelectorAll(...)returns aNodeList,element.childrenanHTMLCollection(part 15); - strings, typed arrays, and plain objects like
{ 0: "a", length: 1 }.

Convert with Array.from
The simplest approach is to turn the array-like into a real array:
const record = { 0: "a", 1: "b", 2: "c", length: 3 };
try {
record.map((x) => x);
} catch (err) {
console.log(err.name); // no array methods
}
console.log(Array.from(record));
console.log(Array.from(record, (x) => x.toUpperCase()));
try {
console.log([...record]);
} catch (err) {
console.log("spread:", err.name); // not iterable
}
TypeError
[ 'a', 'b', 'c' ]
[ 'A', 'B', 'C' ]
spread: TypeError
Spread [...x] requires an iterable (part 12). arguments, NodeList, strings and typed arrays are iterable, so spread works for them; a plain object with length isn't. Array.from accepts both, which makes it the safe choice.
function collect() {
return [arguments.length, Array.isArray(arguments), [...arguments]];
}
console.log(collect("x", "y"));
[ 2, false, [ 'x', 'y' ] ]
In modern code, rest parameters (function collect(...items)) give you a real array directly (part 8).
Borrowing array methods
Most array methods are deliberately generic: they only use length and indexed access, so they work on any array-like when called with call (part 8):
const record = { 0: "a", 1: "b", 2: "c", length: 3 };
console.log(Array.prototype.join.call(record, "+"));
console.log(Array.prototype.map.call(record, (x) => x + x));
console.log(Array.prototype.includes.call(record, "b"));
a+b+c
[ 'aa', 'bb', 'cc' ]
true
You'll see Array.prototype.slice.call(arguments) in older code: it was the standard way to copy an array-like into an array before Array.from existed.
Strings as arrays
Strings behave like read-only arrays of UTF-16 code units: they have length, you can index them with brackets, and they're iterable.
const word = "café";
console.log(word[0], word.at(-1), word.length, word[10], word.charAt(10) === "");
c é 4 undefined true
Brackets are the modern replacement for charAt, with one difference: an out-of-range index gives undefined, while charAt gives "".
Strings are immutable
You can't change a character in place. In sloppy mode, the assignment is silently ignored; in strict mode, and with mutating array methods, it throws:
const word = "café";
(function () {
"use strict";
try {
word[0] = "C";
} catch (err) {
console.log(err.name);
}
})();
try {
Array.prototype.push.call(word, "!");
} catch (err) {
console.log("push:", err.name);
}
console.log(word, "C" + word.slice(1)); // build a new string instead
TypeError
push: TypeError
café Café
Non-mutating array methods do work on strings: Array.prototype.every.call("1234", (c) => c >= "0" && c <= "9") checks that every character is a digit. But usually it's clearer to convert to an array of characters, work on that, and join it back:
console.log([..."stressed"].reverse().join(""));
desserts
The emoji trap
length, indexing and split("") work in UTF-16 code units, and characters outside the Basic Multilingual Plane, such as most emoji, take two code units (article 13). Iteration (for...of, spread, Array.from) works in code points, so it keeps them intact:
const text = "a😀b";
console.log(text.length, text.split("").length, [...text].length);
console.log([...text].reverse().join(""));
4 4 3
b😀a
text.split("").reverse().join("") would separate the two halves of the emoji and produce garbage. Prefer [...str] over split(""). Even code points aren't the whole story: a flag or a family emoji is several code points combined, and only Intl.Segmenter (part 11) splits text into the characters a user sees.
Common questions
How do I check whether a value is array-like?
value != null && typeof value !== "function" && Number.isInteger(value.length) && value.length >= 0. Functions are excluded because they have a length (their parameter count). Usually you don't need the check: just call Array.from(value).
Why does [1, 2, 3] == "1,2,3" return true?
== converts the array to a primitive with toString, which gives "1,2,3". Use ===, which never converts.
Is a NodeList an array?
No. It has length, indexes, forEach and is iterable, but lacks map, filter and the rest. Convert with Array.from(list) or [...list]. Some DOM collections are also live (they change when the document changes), another reason to copy them.
What does Array.from({ length: 3 }) produce?
[ undefined, undefined, undefined ]: a real, dense array. Combined with a map function, Array.from({ length: n }, (_, i) => ...) is the standard way to generate arrays (article 54).
Summary
join(sep)turns an array into a string (comma by default);null,undefinedand holes become empty.toStringisjoin(), used automatically when arrays become strings.- Use
Array.isArrayto detect arrays;typeofsays"object", andinstanceoffails across realms. - Array-likes have
lengthand indexes but no array methods: convert them withArray.from(or spread, when they're iterable), or borrow methods withArray.prototype.method.call. - Strings are read-only, indexable and iterable; build new strings instead of modifying them.
length, indexing andsplit("")count UTF-16 code units; spread andfor...ofkeep emoji intact.
Practice Questions
What does this print?
console.log([1, [2, 3], null, "x"].join("|"));
Answer
1|2,3||x. The nested array becomes "2,3", and null becomes an empty string.
Why does snippet A throw while snippet B works?
[...{ 0: "a", length: 1 }]
Array.from({ 0: "a", length: 1 })
Answer
Spread needs an iterable, and a plain object isn't one. Array.from also accepts array-likes, reading length and the indexes.
Write isPalindrome(text) that ignores case and non-letters.
Answer
const isPalindrome = (t) => {
const s = t.toLowerCase().replace(/[^a-z]/g, "");
return s === [...s].reverse().join("");
};
isPalindrome("Never odd or even") is true.
"👍".length is 2. How many elements does "👍".split("") have, and how many does [..."👍"] have?
Answer
2 and 1. split("") splits into code units (the two halves of a surrogate pair), while spread iterates by code point.
Review quiz
You've finished Part 7. Check your understanding of arrays with the Part 7 review quiz: 25 questions on creating arrays, length and holes, iteration, searching, reduce, stacks and queues, slice and splice, the ES2023 copying methods and sorting.
Previous: Sorting JavaScript Arrays: sort, Comparators, localeCompare, Stable Sort, reverse and toSorted
Next: JavaScript Functions: Declarations, Expressions and Arrow Functions

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.