Ad

Functions in JavaScript

In a program, we offen need to use same block of code in many different places, in that suitations functions play an important role. In function, we can define code once, and use it as many times as required.

Advantage of functions
  1. Remove redundancy
  2. Make program size compact
  3. It helps in increasing speed of page
  4. Reduce Programmer's effort
Types of functions: Functions is of 2 types:
  1. Built-in functions like alert(), confirm(), string functions, math functions date functions etc.
  2. User-defined functions: created by user to perform some action.

In this section we will discuss User-defined functions.

JavaScript - User-defined functions

Below figure contains function keyword, function name, curly brackets, function body including statements and function calling.

Function name should be brief, meaningful, easy to read and in camel case eg: showMessage(), calcPower(), createResult(), etc.

Example 1: function without parameter, without return type.

javascript function defination

Example 2: function with parameter, without return type.

javascript function with parameter, without return type

Example 3: function without parameter, with return type.

javascript function without parameter, with return type

Example 4: function with parameter, with return type.

javascript function with parameter, with return type

Variable scope

A variable can be declared inside or outside function. A variable declared inside a function is known as local variable, A variable declared outside a function is known as global variable.

Local variable scope is limited within a function

Global variable scope can be used outside function and can be used inside whole web page.

Example 5: Local variable

function square(){
    let n=10;
    let s=n*n;
    alert('Square = '+s); // display 100
}
square(); //function call
alert('Square = '+s); // Error, cannot access outside function

Example 6: Global variable

let s; //global variable
function square(){
    let n=10;
    s=n*n;
    alert('Square = '+s); // display 100
}
square(); //function call
alert('Square = '+s); // display 100

Function with default value

If we declare a parameterized function and does not pass the argument then error will prompt, but if we declare a function with default value and does not pass any argument then default value will be assigned.

Example 7: Default argument

function power(n, p=2){
    let s=Math.pow(n,p);
    alert('Power = '+s);
}
power(10,3); //function call with 2 arguments, Output: Power = 1000
power(10); //function call with only 1 argument, Output: Power = 100

JavaScript function with beautify

There are some points mentioned to write your code that looks good, easy to read and understand. Lets understand coding style which is more prefered.

javascript syntax

JavaScript Feedback, Questions, Suggestions, Discussion.

Ad: