What is the difference between a string and an array of characters in Javascript?

When I checked if the two were equal, they obviously were not. Can someone explain why?

var string = "Hello"; var array = ['H', 'e', 'l', 'l', 'o']; 

Why is (string === array) false?

EDIT: This site is fantastic. Such a quick help. Thanks guys.

+6
source share
4 answers

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.

+11
source

You are confused with c / C ++. In java-script, an array is another object, and a string variable is different. Try to read this

+2
source

In JavaScript === there is strict equality that compares two values ​​for equality. Before matching, no value is converted to any other value. So why do you have different objects (String and Array) that cannot be equal, and so your comparison returns false .

More on what you can find on Strict Equality using ===

+2
source

In Javascript, the String and Array data types are not equal.

+1
source

All Articles