Back to: JavaScript
A function declaration is one way of creating a function in JavaScript.
A function declaration is defined by using the function keyword, followed by a name, followed by parenthesis and then curly braces:
function name() {
statement(s);
}
Between the curly braces is where you write your statement(s). Between the parenthesis you can specify parameter(s):
function calSqrArea(length, width) {
return length * width;
}
To be used, it must be invoked, by using its name:
name();
You can add any required parameter(s);
console.log(calcSqrArea(5, 3));
A function declaration must start with the function keyword and be given a name.
You can call a function declaration before you define it! This works because of a process called hoisting. In JavaScript, hoisting is a behaviour which moves all declarations to the top of the code, before execution.
A function that is created with a function declaration is a function object that has all of the properties, methods and behaviour of function objects.
By default, functions return undefined. To return any other value, the function must have a return statement that specifies the value to return.
conclusion
In JavaScript there’s more than one way to create a function. You should choose a function declaration when you want to create a function with global scope, so it’s available throughout your code.