javascript – How is undefined converted to a string?

Question:

 var a = [undefined, undefined]; console.log(a.join()); // тут undefined преобразуются в пустую строку console.log(String(undefined)); // а тут в строку 'undefined' console.log('' + undefined); // и тут в 'undefined'

Where is the logic?

Answer:

You won't immediately grasp the logic until you read the standard, as is the case with many autocast languages. Building possible connections without knowing certain subtleties when managing types is useless in any weakly typed language, because developers do as it is convenient for them, and other developers do as it is convenient for them. Perhaps your interests will converge with them and then you will be in the language "like a fish in water" , but you may not converge ..

Let's do a little test .. What are the following operations?

console.log(NaN === NaN);
console.log([] + []);

There is a logical explanation for such operations, but for many people these operations associated with types in javascript have caused wild controversy throughout history, because it is a flexible language. And its flexibility is extraordinary, and it has two sides.

You can quickly write some kind of functionality, or you can write something with crooked hands that will make your eyes twitch . In general, this is the case with any language, know how to use it and you will not have any problems. Of course, not everyone likes dynamic typing, and recently the typed language TypeScript has appeared, which has its own syntax with automatic conversion to Javascript. Everyone thinks differently, maybe you are a strong typist and it suits you better?

There is an interesting video from a conference where people discussed such operations.

Let's go back to the question and open the Mozila website with a description of the standard :

var a = [undefined, undefined]; 
console.log(a.join());

Array.prototype.join () – Converts all elements of an array to strings and concatenates them into one large string. An array element of type undefined or null is converted to an empty string. A source

console.log(String(undefined));
console.log('' + undefined);

The first case is described in the official standard ( English ) in clause 9.8.

The second case is described on the official Mozila website:

undefined is a property of the global object, that is, it is a variable in the global scope. The initial value undefined is the primitive value undefined. A variable that has no assigned value is of type undefined. A method or statement is also returned undefined if the variable involved in the calculation does not have an assigned value. The function returns undefined if it does not return any value. A source

Scroll to Top