Smal SEO Tool

JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task.

Function Syntax

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().

javascript
function name(parameter1, parameter2, parameter3) {
  // code to be executed
}

Function Invocation

The code inside the function will execute when "something" invokes (calls) the function:

  • When an event occurs (when a user clicks a button)
  • When it is invoked (called) from JavaScript code
  • Automatically (self-invoked)

Example

html
function myFunction(p1, p2) {
  return p1 * p2;   // The function returns the product of p1 and p2
}
let result = myFunction(4, 3); // result will be 12

Test Yourself with an Exercise

How do you call a function named 'myFunction'?