Introduction to JavaScript : Functions

Functions

Functions in a programming language is a group of statements for performing a specific task. This section of code may be reused anywhere in the whole program when needed. The use of functions eases the process of writing code for programmers as it assists in breaking down huge and complex programs into small and manageable parts. A function may have a name (named functions) and may accept a set on inputs called 'parameters'. 

To create a function, follow this syntax: 

function <function name> (parameter list) {
   <statements>
}

Example:

function write_my_name(my_name) {
   console.log('My name is ' + my_name)
}

var your_name = 'Teachsomebody'
write_my_name(your_name)

Output:

My name is Teachsomebody

A function may also return a value as shown in the example:

function get_sum(x, y) {
   var z
   z = x + y
   return z
}

var sum = get_sum(2, 5)
console.log(sum)

Output:

7


course logo
Introduction to JavaScript
Number of sections:
10
Content length:
Delivery formats: