Javascript Functions

JavaScript function is reusable piece of code that can be coded once and reused many times. For example, we can create a function that will either switch ON or OFF the lights and then reuse this function by switching the button to ON or OFF

Syntax of Creating a JavaScript Function

function SWITCH(INPUT)
Read the INPUT  and perform any action, for example SWITCH ON or SWITCH OFF

  • function is a JavaScript keyword

Example of JavaScript Function Creation

  • In above example we created a function and named it add. This function is expecting two value
  • function is a JavaScript keyword, so we must type it ‘as it is’
  • Function values also known as input parameters are always enclosed in parentheses ( ) and separated by comma
  • When creating a function we can specify as many input values as we like.
  • The action of a function is defined in curly braces { }
  • This function will add value of a to value of b and then save the result in c
  • This function will provide us the answer by using a keyword return

Syntax of Using a JavaScript Function


  • In order to use a function simply type the name of function and pass it the values it is expecting from us.
  • For switching lights function it’s expecting one value from us, either ON or OFF
  • Once a function is created, we can use it as many times as we like

Example of JavaScript Function Usage

  • In above example we are using (also known as calling) the function add
  • we are sending two input values (also known as parameters) of 4 and 5 to our function.
  • function parameter are enclosed in parentheses ( ) and separated by a comma ,
  • the above example will result in 9