I was looking at the output of some stuff from UglifyJS and happened across some code like the following:
var a = 0;
var b = function () {
return function () {
a++;
}(), 'Hello, World'
}();
After running that code a
is 1
and b
is the string Hello, World!
.
At first glance it appears that b
will be undefined
since it looks like the result of a function with no return value is being returned, but that is followed by a comma and a string literal.
Why does this work?
And why doesn't UglifyJS just execute the anonymous function and then return Hello, World!
as the next statement?
JavaScript works with HTML and CSS to build web apps or web pages. JavaScript is supported by most modern web browsers like Google Chrome, Firefox, Safari, Microsoft Edge, Opera, etc. Most mobile browsers for Android and iPhone now support JavaScript as well. JavaScript controls the dynamic elements of web pages.
On the web browser menu click on the "Edit" and select "Preferences". In the "Preferences" window select the "Security" tab. In the "Security" tab section "Web content" mark the "Enable JavaScript" checkbox. Click on the "Reload the current page" button of the web browser to refresh the page.
The main reason why Chrome is unable to load JavaScript is because it is disabled by you intentionally or unintentionally. There are more than five settings that need to be enabled all the time in order to allow Chrome to load JavaScript on any website.
It works due to the comma operator. From the MDN specs:
The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.
Both functions are IFFYs, they are inmediately executed.
The result of an expression using the comma operator is the right hand side of the comma operator.
You have:
return a_function_call(), a_string
… so you get a_string
assigned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With