Why is (string === array)
is false ?
You are using strict comparison (===
), which also checks the data type of the values. Obviously a primitive string value is not the same data type as an object, and objects are only truly equal to themselves. Proof:
var foo = [1,2,3];
var bar = [1,2,3];
console.log(foo === bar); // false
console.log(foo === foo); // true
Now, if you were to use loose comparison (==
), the following comparison does return true
:
console.log([1,2,3] == '1,2,3'); // true
Why? Because the array is converted to a string first, and this happens to result in the same string value. But that doesn't mean that the values are the same (one is still an array and the other a string). That's why you should always use strict comparison.
What's the difference between a string and an array of characters in Javascript?
Strings are not arrays because they are inheriting from different prototypes (*) and hence have different instance methods. For example, arrays have a method join
and strings have a method match
.
From one point of view, arrays and strings are similar though, because they are both array-like objects.
What does array-like mean? It means that the object has a length
property and numeric properties. A string has a length
property which gives you the number of characters in the string, and you can access single characters of the string with str[i]
. Example:
var arr = ['a','b','c'];
var str = "abc";
console.log(arr.length); // 3
console.log(str.length); // 3
console.log(arr[0]); // a
console.log(str[0]); // a
console.log(arr === str); // false
console.log(typeof str); // string
console.log(typeof arr); // object
*: Actually, there even is a difference between primitive strings and String objects, but I don't want to go too deep here. Technically primitive strings don't have any methods because they are not objects, but in most cases, you can treat primitive strings like they were objects.