Reputation: 4934
Consider the following CoffeeScript:
$ ->
if localStorage["Flag1"] isnt "Done"
localStorage["Flag1"] = "Done" # Flagged on first page loading
$(".start").click ->
if localStorage["Flag2"] isnt "Done"
localStorage["Flag2"] = "Done" # Flagged on first click interaction
Which compiles into:
$(function() {
if (localStorage["Flag1"] !== "Done") {
localStorage["Flag1"] = "Done";
}
return $(".start").click(function() {
if (localStorage["Flag2"] !== "Done") {
return localStorage["Flag2"] = "Done";
}
});
});
There are two strange occurrence of "return" being planted into the rendered JavaScript. What do they do, and how will they affect the running of the script? Thanks!
Upvotes: 1
Views: 142
Reputation: 165951
They won't affect the running of your script. The first return
will return $(".start")
(since the jQuery click
method returns an instance of jQuery) from the DOM ready event handler. Since it's a callback that runs at a certain point, you can't really do anything with that return value.
The second return
will return "Done"
, after setting the localStorage
property, but again, since it's returning from a callback (a click event handler this time) you won't be able to do anything with the returned value.
I believe CoffeeScript will return
the value of the last expression in each function, which is why you see those return
statements in the output. From the docs:
Even though functions will always return their final value, it's both possible and encouraged to return early from a function body writing out the explicit return (
return value
), when you know that you're done.
Upvotes: 2