Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does [].$ mean in JavaScript?

Tags:

javascript

There is a function in JavaScript which calculates the sum of some digits, however I don't understand what this part ([].$) means:

const sum = d => d != [].$ ? `${d = [...`${d}`].join` + `} = ${eval(d)}` : ``

[].$

[].$ - what is it?

like image 245
mvn.2047 Avatar asked Jun 14 '20 18:06

mvn.2047


People also ask

What are [] for in JavaScript?

The [] operator converts the expression inside the square brackets to a string. For instance, if it is a numeric value, JavaScript converts it to a string and then uses that string as the property name, similar to the square bracket notation of objects to access their properties.

What is [] vs {} in JS?

[] is declaring an array. {} is declaring an object. An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class.

Why [] == [] is false in JavaScript?

Because [] creates a new array, so you are comparing one array object with another array object. It's not the contents of the arrays that is compared, the object references are compared. They are not equal because it's not the same object instance.


2 Answers

[].$ - what is it?

It's an empty array literal ([]) followed by a property accessor expression (.$) looking up the property called $.

Since arrays don't normally have a property with that name, presumably it's been set there (or potentially set there, given the check) by some previous code. If no code sets it, then it's a short way to write undefined (since [].$ is undefined when $ isn't a property of arrays).

like image 185
T.J. Crowder Avatar answered Oct 11 '22 18:10

T.J. Crowder


For this particular code, it doesn't have any significant meaning. It's there just to represent the value undefined with the least amount of characters. It could equally be []._ or just undefined.

For how it's interpreted. @T.J.Crowder answer summarised it pretty well

like image 33
thammada.ts Avatar answered Oct 11 '22 19:10

thammada.ts