Functions

A function is a block of code or a set of statements which has a name and performs some task. A simple example is a function that displays a message at the console or a function that performs addition of two numbers.
A function can be called as many times as required. It may or may not return a value.
[the_ad id=”89″] Benefits of Function
Following are the important advantages of using functions.
Promotes code reusability. When the same set of statements is required at many different places, then instead of repeating those lines, they are placed in a function, thus promoting code reusability.
Enhances modularity. Separating large code into function blocks makes the code modular.
Makes maintenance easier. Placing statements in a function also makes code maintenance easier since if there is a change, it needs to be done at a single place only. If the same code was repeated at multiple places, the change would be required at every place.
Enhances code readability. Functions make the code cleaner, organized and easier to understand since writing all the code at one place makes makes it very difficult to understand and modify.
Function Syntax
A function is declared using function keyword followed by a user defined function name. This name is followed by parenthesis with optional arguments(discussed later) as shown below.

function functionName() {
   // function code
}

A function written in above manner is called function definition.
Function Expression
A function defined in above manner using function keyword and a function name is also called Function Declaration. A function can also be defined using a Function Expression. A function defined using function expression has almost the same syntax as function declaration but a function expression assigns the function definition to a variable.
Thus, a function expression for the above function will be

const f = function functionName() {
   // function code
}

A function defined using a function expression has an advantage that its name can be omitted from the definition in which case it becomes an anonymous function. Example,

const f = function() {
   // function code
}
[the_ad id=”267″] Calling a function
Function definition can not execute on its own, it is just like a piece of code which is not used. In order to execute a function, it needs to be called. A function is called using its name followed by parenthesis. Parenthesis should contain arguments only if the function definition expects arguments. Thus, a function should be called using below syntax.

functionName();

Example
Below is a function which displays a welcome message on the console. The function is named displayMessage.

// defining a function
function displayMessage() {
   console.log('Welcome to javascript!!!');
}

// calling function
displayMessage();

Function with Arguments
A function can accept input values. These input values are called function arguments and make a function more dynamic and flexible. Consider the above function that displays a message.
[the_ad id=”94″] Now instead of writing this message inside the function, we can supply the message as an argument to this function and display it on the screen. This way the function can be used to display any text and not just the constant message.
 There is no limit to the number of arguments supplied to a function. 

Syntax

function functionName(argument1, argument 2) {
   // function code
}

Arguments supplied to a function are scoped to the function only and are not visible outside the function. A function that accepts arguments is called in the same way as a function without arguments supplying appropriate number of values as the number of arguments. Example,

// defining a one argument function
function displayMessage(message) {
   console.log(message);
}

// calling function with argument
displayMessage('This will be displayed');

Arguments are only required when the function should receive some values.
Returning values from Function
A function may or may not return a value. If it should return a value, then this is done using return keyword followed by the value to be returned. return keyword, if present, should be the last statement in function definition. You need not declare the type of value returned from a function as required in other languages such as java where a function needs to declare the type of value that it will return.
Value returned from a function can be assigned to a variable.
Example,

// function definition with 2 arguments
function add(numOne, numTwo) {
  let sum = numOne + numTwo;
  // return value from function
  return sum;
}

// assign value returned from function
let result = add(2, 3);
console.log(result);  // displays 5

[the_ad id=”95″]

Inbuilt javascript functions
Javascript has many builtin functions. Examples of such functions are
alert
setTimeout
setInterval
clearInterval and many more…

Functions

Suppose you have a set of few lines of code which is used and executed at multiple places. Instead of writing it again and again at multiple places, these lines are written at a single point and grouped into a function. Where ever they are required, this function is called. Thus, a function is a group of lines of code which can be used to perform a task and called from different places.
[the_ad id=”89″] Benefits of a function

  • A function promotes reusability as multiple repetitive lines are written only once and can be used where required.
  • It also promotes modularity as dividing the code into pieces converts it into smaller independent modules.
  • It makes the code cleaner, organized and easier to understand since writing all the code at one place makes makes it very difficult to understand and modify.
  • It makes maintenance easier. Think about it that when same logic is repeated at many places and there is a slight change in that logic, then that change needs to be done at all the places. While if that logic is grouped into a function, then that change only needs to be done at a single place.
  • It makes testing of code easier since you do not need to test multiple repeating lines again and again if they are grouped into a single function.

Creating a function
A function is created using def keyword followed by the name of function and arguments of function enclosed between parenthesis. These arguments are optional and are required only if you want to pass some values to the function though parenthesis after function name are mandatory. If there are no arguments to the function, parenthesis will be empty.
Syntax:

def <function_name> ():     # no-argument function
   # statement one
   # statement two
   # other statements

def <function_name>(arg1, arg2...): # function with arguments
   # statement one
   # statement two
   # other statements

There can be any number of arguments supplied to a function. Statements of a function should be indented at the same level to denote that they belong to that function.
A function may or may not return a value. If a function needs to send a value back to the calling code, it is done by using return statement with value to be returned written after return. Remember that when return is encountered, function execution is stopped and the function returns immediately. Any code written after return will not be executed.

return can also be used without a value. In that case, it is just used to terminate function execution.
[the_ad id=”94″]

Calling a function
A function is called by using its name followed by parenthesis. If the function expects any arguments, then those arguments should be provided between parenthesis separated by a comma. A function can be called only after it has been defined else you get an Unresolved reference error.
Below example defines a function which accepts two numbers as arguments and prints their sum.

# prints the sum of two numbers
def sum(first_number, second_number):
    sum = first_number + second_number
    print("Sum of numbers is " + str(sum))

# calling function
sum(2,3)

Remember that values of arguments when calling a function are passed in the same order in which they are given. In above example, first_number will be 2 and second_number will be 3.
Number of arguments which the function expects and which you pass while calling the function should match else you get an error. Example,

# prints the sum of two numbers
def sum(first_number, second_number):
    sum = first_number + second_number
    print("Sum of numbers is " + str(sum))

# calling function
sum(2)   # only one argument

The function is expecting two arguments but we are calling it with a single argument. When this code is executed, you get an error TypeError: sum() missing 1 required positional argument: ‘second_number’

Returning values from function
A function becomes more useful if it performs some task and produces a result and it is also capable of returning that result back to the calling code. A function can return a value using the return keyword followed by the value to return. Example,

def sum(first_number, second_number):
    sum = first_number + second_number
    return sum

# calling function
result = sum(2, 3)  # assigning the return value to a variable 
print("Sum of numbers is " + str(result))
[the_ad id=”95″] Value returned from a function should be assigned to a variable in the calling code or the returned value can also be used directly. That is, below line is also valid.
print("Sum of numbers is " + str(sum(2, 3)))

Also, return statement should be the last statement in the function body.
Default function arguments
As explained earlier, if a function is defined with arguments then an equal number of arguments need to be supplied while calling this function. However, python gives you a flexibility to this rule by the use of default arguments. By using default arguments, you can provide the value of an argument while defining it in the function.
If a function argument is provided a default value, then there is no need to supply its value at the time of calling the function. Example,

def defaultArg(a, b=5):
   print(b)

defaultArg(2)   # prints 5
defaultArg(2, 10)   # prints 10, overrides default value

Look in the above code, a function accepting two arguments is defined out of which one argument has a default value. When this function is called with a single argument, then the default value of second argument is considered.
Note that while calling a function, if you supply a value for the argument which also has a default value, then the value supplied while calling the function overrides the default value.

 

Exit mobile version