Why is (string === array) false?
You are using strict comparison ( === ) , which also checks for data values. Obviously, a primitive string is not the same data type as an object , and objects are really equal to themselves. Evidence:
var foo = [1,2,3]; var bar = [1,2,3]; console.log(foo === bar); // false console.log(foo === foo); // true
Now, if you want to use the lose comparison ( == ) , the following comparison returns true :
console.log([1,2,3] == '1,2,3'); // true
Why? Since the array is first converted to a string, and this leads to the same string value. But this does not mean that the values ββare the same (one is still an array and the other is a string). That is why you should always use strict comparison.
What is the difference between a string and an array of characters in Javascript?
Strings are not arrays because they inherit from different prototypes (*) and therefore have different instance methods. For example, arrays have a join method , and strings have a method
*: Actually, there is even a difference between primitive strings and String objects, but I donβt want to go too deep here. Technically primitive strings do not have any methods because they are not objects, but in most cases you can consider primitive strings such as objects.