Let's start what is function in javascript?

Function helps us to divide our code in small modules that are easy to understand and use through out our development.

Basic syntax of function.

ES5 syntax.

function function_name(args){
    // your code here
}

ES6 syntax.

const function_name = (args) => {
    // your code here
}

Developers mostly used ES6 syntax over ES5 and I will let you now why in upcoming blog.

Let's take an example of adding two numbers.

If I want to add two numbers in function I can write it like this

// ES5 version
function add(){
    let sum = 1 + 2
    console.log(sum)   // 3
}

// ES6 version
const add = () => {
    let sum = 1 + 2
    console.log(sum)   // 3
}

This is write but it will not print anything because a function has to be called after declaration

We can call a function by this syntax

function add(){
    let sum = 1 + 2
    console.log(sum)   // 3
}
add()   // calling the function

Whenever we call a function it always print 3, what if we want to add other numbers. In that case you have to use params provided to the function

function add(a,b){
    let sum = a + b; // a will store 10
                    // and b will store 30
                   // respectively
    console.log(sum)    // 30
}
add(10,20) // we pass two parameters 10 and 20

Function can also return values, say you want to return the sum of two numbers, there will be a small modification in the above code.

function add(a,b){
    let sum = a + b;
    return sum;    // use return keyword
}
let sum = add(sum);
console.log(sum)    // 3

If a function is returning a value it can be stored in variable.


There are various built in functions that we can use, here are some examples.

  • toUpperCase()
  • toLowerCase()
let name = 'tom'
let updatedName = name.toUpperCase()
console.log(updatedName)    // TOM
updatedName = updatedName.toLowerCase()
console.log(updatedName)    // tom