function Statements

By: Dusty Arlia
Published on Friday, April 19, 2013, 08:08 AM
Last Updated on Friday, July 10, 2015 at 12:05 AM
Total Updates: 3

Statements that start with the keyword function are used to define functions and are sometimes called function definitions or function declarations. Here is the basic syntax of a function definition:

function function_name(parameter1, parameter2) {
//statements
}

function_name is the name of the function, also called the function's identifier. Following the name of the function, in between parentheses, is a comma separated list of parameters. These parameters receive values from the function call. Wherever the parameter names appear in the function body, is where the passed values will be inserted.

The function body is the part of the function statement in between curly braces ({}). The curly braces are required. This differs from other statement blocks, because in other statements like loops and if statements, curly braces are optional when there is only a single statement in the body of the loop or branch of a if statement. Also, with function statements, there is no need for a semicolon at the end of the last curly brace.

Function definitions are not executed initially. They define functions that are later executed when called. Use a function call to invoke a function.

Function declarations may appear in top-level code or inside other functions. Function declarations are not allowed in loops, if statement, or any other statements. ECMAScript does not recognize function definitions as real statements because they are not allowed to be used just anywhere.

When being interpreted by the JavaScript interpreter, function definitions get hoisted to the top of the script they are in or to the top of the function they are nested in. With the function definition at the top of the script or function it is nested in, access to this definition is allowed whenever it is invoked.

Compariably, variable declarations get hoisted, but not their initializers. Function declaration statements have both the declaration and initialization code hoisted. All functions should be declared and initialized before any code in the script or function is run. Even though normal convention suggests that you keep you function declarations at the top of your script of function, you should still be able to call a function before that function is even declared (because these function definitions get hoisted).

Like variables that are created with the var keyword, any function objects created with the function keyword cannot be deleted. Their values can be overwritten, but not deleted.

Comments:

Ad: