Function Declarations

Overview


Declaring a function is a block of code which defines what a function does and (typically) assigns it a name so that it can be referenced later.

Using Function Keyword




function add(a, b){
  let answer = a+b;			
  return answer;	
}
            	
Try it!

There are other ways to declare a function. A function can be declared in a similar way to the variable declarations given above.


let sum = function(a, b){
  let answer = a+b;			
  return answer;	
}
            	
Try it!



Arrow Functions

Javascript also gives you a shortened method of declaring the function by getting rid of the key word "function". In this case, it is replaced by an "arrow". You enter the parameters of the functon, followed by the arrow, followed by the function block.


let sum = (a, b) => {
  let answer = a+b;			
  return answer;						
						
}
            
Try it!



When there is only one argument, the function can be shortened further. You dont need the parentheses. If the function block can be written as a single line, you can remove the curly braces and the return keyword.


let double = a => {
  return 2*a;										
}

let double2 = a=>2*a;
            

Contents