This content originally appeared on DEV Community and was authored by ahmedgaafer
JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm. It has curly-bracket syntax, dynamic typing, prototype-based object orientation, and first-class functions.
Some confusing parts
(([]+{})[1]+'mg').toUpperCase() // outputs OMG
But how is this happening
We will go into a little depth on how JS interprets stuff
I am using chrome console to test all of this
Let's Explain how the line above first
the '+' sign converts the parameters to strings by using the 'toPrimitive' method
so, toString([]) returns an empty string ''
and toString({}) returns to this '[object Object]'
then the result is '' + '[object Object]' = '[object Object]'
the rest is simple, I am picking the character at index 1 'o' and just adding the 'mg' and converting all to upper case
Drum roll ........
We get "OMG"
ToPrimitive:
ToPrimitive(input, PreferredType?)
The optional parameter PreferredType is either Number or String. It only expresses a preference, the result can always be any primitive value. If PreferredType is Number, the following steps are performed to convert a value input (§9.1):
- If the input is primitive, return it as is.
- Otherwise, input is an object. Call obj.valueOf(). If the result is primitive, return it.
- Otherwise, call obj.toString(). If the result is primitive, return it.
- Otherwise, throw a TypeError.
If PreferredType is String, steps 2 and 3 are swapped. If PreferredType is missing then it is set to Number for any numeric values and to string for all other values.
1 + 1 // 2 <= Number
1 + 1 + '1' // '21' <= String
1 + 1 + [] // '2' <= String
There are some unique examples that behave differently
{} + 1 // 1 <= Number
// JS treats the '{}' in this case as its own line
({});+1 = 1
({})+1 = '[object Object]1'
Now you can apply this principle to any addition in JS and always know the answer without being confused
references:
This content originally appeared on DEV Community and was authored by ahmedgaafer
ahmedgaafer | Sciencx (2021-04-07T01:29:21+00:00) Confusing JS Explained. Retrieved from https://www.scien.cx/2021/04/07/confusing-js-explained/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.