TIL how the documentation guides Javascript
POSTED ON:
TAGS: javascript
Today I learned about the ECMAScript specification.
Essentially, the ECMAScript team makes recommendations. And Javascript engines follow the spec to implement.
FOr example --
how exactly does Object.prototype.toString()
work?
Here's the specification!
Note: the page took me like 45 seconds to load, which is a miserable experience for anybody.
https://tc39.es/ecma262/#sec-object.prototype.tostring
Here's the documentation chunk:
20.1.3.6 Object.prototype.toString ( )
When the toString method is called, the following steps are taken:
- If the this value is undefined, return "[object Undefined]".
- If the this value is null, return "[object Null]".
- Let O be ! ToObject(this value).
- Let isArray be ? IsArray(O).
- If isArray is true, let builtinTag be "Array".
- Else if O has a [[ParameterMap]] internal slot, let builtinTag be "Arguments".
- Else if O has a [[Call]] internal method, let builtinTag be "Function".
- Else if O has an [[ErrorData]] internal slot, let builtinTag be "Error".
- Else if O has a [[BooleanData]] internal slot, let builtinTag be "Boolean".
- Else if O has a [[NumberData]] internal slot, let builtinTag be "Number".
- Else if O has a [[StringData]] internal slot, let builtinTag be "String".
- Else if O has a [[DateValue]] internal slot, let builtinTag be "Date".
- Else if O has a [[RegExpMatcher]] internal slot, let builtinTag be "RegExp".
- Else, let builtinTag be "Object".
- Let tag be ? Get(O, @@toStringTag).
- If Type(tag) is not String, set tag to builtinTag.
- Return the string-concatenation of "[object ", tag, and "]".
NOTE
Historically, this function was occasionally used to access the String value of the [[Class]] internal slot that was used in previous editions of this specification as a nominal type tag for various built-in objects. The above definition of toString preserves compatibility for legacy code that uses toString as a test for those specific kinds of built-in objects. It does not provide a reliable type testing mechanism for other kinds of built-in or program defined objects. In addition, programs can use @@toStringTag in ways that will invalidate the reliability of such legacy type tests.
Look at the process!
It's literally a bunch of If-Else statements.
If it's undefined, then return "[object Undefined]".
If it's null, then return "[object Null]".
There's no magic behind the scenes.
Heck, try it in your console.log now.
[image via Via https://medium.com/javascript-in-plain-english/you-must-understand-these-14-javasript-functions-1f4fa1c620e2](Via https://medium.com/javascript-in-plain-english/you-must-understand-these-14-javasript-functions-1f4fa1c620e2
)
And now you can go out and win JS arguments.
Related TILs
Tagged: javascript