By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

JavaScript Functions

Tutorial on how to make custom functions in JavaScript.

Edited: 2013-07-18 12:50

Functions are "blocks" of code that can be executed, or called either from other functions, or whenever they are needed through the on event attributes.

A custom function can be written by typing the name of the function, preceded by the function keyword, followed by a set of parentheses, and curly brackets. I.e.

function MyUniqueFunctionName() {

The above script can be placed in a script element in the head section of the page, we then call our custom function with the onClick event attribute. I.e.

<!DOCTYPE html>
<html lang="en-US">

    <title>Using Custom Functions with JavaScript</title>
    <script type="text/javascript">
      function MyUniqueFunctionName() {

   <button onClick="MyUniqueFunctionName();">Click Me</button>


Passing Arguments to Functions

It can be very useful to pass arguments to functions, as this allows us to pass on values stored in variables earlier in the script. Arguments are placed between the parentheses of the function. You can include as many arguments as you want, just separate them with comma. I.e.

function myAlert(var1,var2) {
  alert(var1 + ' ' + var2);

Calling a Function with Arguments

To use arguments when calling a function, you would simply fill out the required arguments one by one. I.e.

<button onClick="myAlert('Hallo', 'Jacob');">Function Call</button>