Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this JavaScript work?

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?

like image 216
knpwrs Avatar asked Oct 26 '12 16:10

knpwrs


People also ask

What does JavaScript work?

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.

Why my JavaScript is not working?

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.

Why is my JavaScript not working on Chrome?

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.


2 Answers

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.

like image 164
Wouter J Avatar answered Oct 13 '22 21:10

Wouter J


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.

like image 29
Quentin Avatar answered Oct 13 '22 20:10

Quentin