I am trying some simple javascript and what I discovered is quite amazing if you ask me, I was wondering why javascript behaves like this. So I have a simple inline function that defines two inner functions: task 1 and task2, and has a return object with two properties: job1 and job2, where job1 points to task1 and job2 points to task2. I get an error like:
Uncaught SyntaxError: Unexpected token :
and the amazing part is that if I move the curly brace immediately after the return statement (see comment in code), the script actually works and prompts an alert "1" as expected. Why does it matter if I put the curly brace immediately after return or on the next line?
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@*" data-semver="4.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/angular2.min.js"></script>
</head>
<body>
<h1>Hello!</h1>
</body>
</html>
<script type="text/javascript">
var x = function()
{
var task1 = function() { alert("1"); }
var task2 = function() { alert("2"); }
return
{ ///////////// move this on the previous line right after return
job1: task1,
job2: task2
};
}
x().job1();
</script>
I always thought that in javascript this:
var x = function() {
//content
}
is equivalent to this:
var x = function()
{
//content
}
but obviously not in the case I mentioned first. Why?