1

Okay, so the only way to explain this is with an example. In javascript you can do something such as:

if(condition) {

}

The { and } are used to identify a code block. But in some cases such as this:

window.onload = function() {

}

You need the function() included. Why can't it just be:

window.onload {

}

Why the need for function() ? Also, I thought functions all have a name associated with them, and when that name is called the function runs, but why in this case is there a function with no associated name?

6
  • 1
    When doing window.onload = function() {}, you are setting onload to be an anonymous function that will be executed later. You are not defining a function named window.onload. Commented Oct 16, 2014 at 23:07
  • 2
    Learn the difference between expressions and statements, that will clear things up. Then look up "anonymous functions", and "first-class functions" Commented Oct 16, 2014 at 23:08
  • In JavaScript function are full blown objects. JS variables have function-level scope (there's no block-level scope). Commented Oct 16, 2014 at 23:15
  • @PM77-1—javascript has execution context scope, where functions are one type of execution context. It's possible to have multiple global execution contexts (e.g. frames in a document) and eval (but that's evil so just don't mention it…). ;-) Commented Oct 16, 2014 at 23:29
  • That's just how it was designed. It emphasizes on creating the function object and doing something, which would be obscured by syntactical sugar like yours. Commented Oct 16, 2014 at 23:30

3 Answers 3

1

if, for, while, try, catch, etc. are all statements that modify the following statement. For example, an if (condition) statement will only execute the following statement if the condition expression evaluates to true (or is truthy). A block statement is a special type of statement that is used to group multiple statements together, allowing an if statement to apply to a larger section of your code.

However, window.onload = function() { } is an expression—an entirely different construct. It's an assignment expression consisting of three parts, an assignment operator (=) an expression representing the value to assign (in this case a function expression) and a reference to a variable or property to assign that value to (window.onload).

Note also that there is a difference between a function expression as mentioned above and a function statement, as this can often lead to some confusion. In both constructs, the curly brackets are required around the body (unlike in an if statement).

Sign up to request clarification or add additional context in comments.

Comments

0

You think about Javascript (and maybe programming languages in general) the wrong way.

First of all, the if is a statement, a language struct that controlls the program flow. It is designed to look like if (condition) code. window.onload is a variable. window is an object here, which can "contain" other variables (onload in this case), accessable with that dot notation.

In JavaScript you can assign almost anything to a variable, since everything is basically the same. This is confusing and totally awesome at the same time imo.

You assigned a function, which works via the given syntax new function(params) {code}. You could habe also done window.onload = 5 or window.onload = {a: 5, b: "foo", c: ["bar", "baz"]}. (But that would cause runtime errors, because your browser fails to "run" that. Same error as if you'd try to run var a = 5; a();)

Comments

0

{ and } (also called "curly brackets") are punctuators, they are mostly used to denote a block of code, but have other uses.

Code blocks are statements that are conditionally executed and are used in various productions of the grammar, such as to enclose the statements related to an if statement:

if (condition) {
  // statements to execute if condition is true
}

function bodies in declarations:

function foo() {
  // statements in function body
} 

and expressions:

var foo = function () {
  // statements in function body
}

also in for, while and do loops, switch and with statements, and so on. Curly brackets are also used in object initialisers (aka object literals):

var obj = {name: 'foo', age: 42};

and probably lots of other parts of the grammar that don't come to mind right now.

Edit

So having said all that, time for the questions:

Why the need for function() ?

To indicate that the following code block is the body of a function, not some other production.

Also, I thought functions all have a name associated with them,

For a function expression, a name is optional. The name is only available inside the function (except for certain versions of IE which had a bug that made the name global) to allow for recursive calling:

// Function expression
var foo = function bar() {
            // In here, call as bar or foo
          };

// Everywhere else, call as foo    
foo();

and when that name is called the function runs, but why in this case is there a function with no associated name?

Function expressions are usually assigned to a variable and that name is used to call them. They are also passed in function calls, executed immediately or assigned to object properties where they can be called using normal property accessor syntax:

var obj = {};
obj.foo = function(){alert('My name is foo')};
obj.foo(); 

Function declarations create a variable in the scope of the declaration with the function name and the function object created from the body is assigned to that variable. Function declarations are processed before any code is executed.

There is quite a bit written about function expressions vs function declarations, see Named function expressions demystified and A closer look at expression closures.

4 Comments

While all this is correct, and the links to the spec are very useful, I think it misses the crux of the question. OP is not asking 'Why do we have to use {}?', but 'Why do we have to use function()?'.
Thanks! Very informative. It's not that I don't know the syntax, it's that I just like to understand why my syntax is how it is.
If you don't like the syntax, CoffeeScript provides an alternative, as does the ES6 draft arrow function synax.
No I love the JS syntax! Is my favorite actually. I just had some confusions I needed cleared up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.