What is and how to declare a function in JavaScript

What is a function in JavaScript?

A function is a piece of script within another larger script. A function is use to perform one or multiple tasks according to what code is placed inside it.

Functions can be use to organize a script into parts that accomplish different things. Functions can be reused as many times as you wish by simply calling the function again.

A function needs to be declared with its name and its code. You can also import one or more variables into the function, which are called parameters. In addition you can use return statement to return a value to the main script.

Declaring functions in JavaScript

To declare a function, you use the reserved JavaScript word function, followed by the function name, and a set of parenthesis (indicate whether the function accepts any parameters).

function thefunctionname()

Notes:

  • The reserved word function tells browser that a function is declared.
  • There are some special consideration when naming functions (as in the case of variables).
  • Parenthesis are left empty if the function doesn’t accept any parameters.
  • There is no semicolon to show where the function’s code ends but each line of code within the function ends with a semicolon.
  • The code inside the function is surrounded by curly brackets (see below).
function thefunctionname() {
JavaScript code within the brackets.
}

Naming functions in JavaScript

As in the case of variables, naming functions follows the same rules.

Leave a Reply