Basic Javascript Guide

Functions

A function is an algorithm that takes a set of inputs, and returns a single output. As an example, we talk about the addition function, that is, an algorithm that takes two numbers as inputs, and returns a single number as the output. If we have a function, such as the add function, we get an expression that represents its output as the name of the function, with the list of its inputs within parentheses, separated by commas.

The following shows calling the add function, and then assigning its output the the variable named "sum".


let sum = add(2,3);
            


The javascript language comes with a number of predefined functions, however, in general it is up to the programmer to define the functions they need to use. To define a function, you write the word "function" followed by the name of the function, followed by parentheses with the list of inputs within the parentheses. Following the parentheses is an open curly braces followed by a closed curly brace.


function add(a, b){
						
						
}
            


This function does not do anything. The code for the algorithm that the function executes will be placed within the curly braces. The following puts an algorithm within the braces that executes the function.


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

Topics

Contents