Defining JavaScript functions

In JavaScript, you can create a function in two ways. First way is to use a
function statement and it is similar to what is use in other programming
languages.

function hello() {
   alert("hello");
}
hello();

Here we define function hello and call the function after its definition. A
second way to create a function is by using a function expression. Here you
define a variable and assign a function to this variable.

var helloWorld = function() {
   alert("hello world");
}
helloWorld();

You can use function expressions when passing functions as function parameters.
For example like this.

var helloWorld = function() {
   alert("hello world");
}
function saySomething(f) {
   f();
}
saySomething(helloWorld);

Here we define a function with a function expression, then define a function
that takes a function as a parameter and pass the function we created as
parameter.

Read more about functions in the Mozilla JavaScript Guide.

Advertisements
Defining JavaScript functions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s