Javascript Functions

A function is a block of code designed to perform a certain task. A function is run when it’s invoked or called by an action. functions are very important because they are written once and can be executed multiple times. They save you a lot of development time in that you don’t have to repeat writing the code in the function in multiple places where you need it.

Syntax

function add(num1, num2){
 let sum = num1 + num2;
 return sum;
}

Parameters

Function definitions do not specify data types for parameters. Functions do not perform type checking on the passed arguments. Functions do not check the number of arguments received. Parameters that are not objects are passed by value. Parameters that are objects are passed by reference which means, changes to them will reflect every where.

let user = {
    "name":"Folau"
}

function changeToRandomName(user){
    user.name = "Lisa";
    console.log("user:",user);
}
console.log("user:",user);//{name: "Folau"}
changeToRandomName(user);//{name: "Lisa"}
console.log("user:",user);//{name: "Lisa"}

 

 

Default Values

If a parameter is not provided, then its value becomes undefined. You can set a default value to be used in case a parament is not passed.

/*
* Function Default values
*/
function hello(name, greeting = "Hello there! "){
    return greeting+name;
}

/*
* Note that functions can take 0 or more parameters. 
*/
let greetingFolau = hello("Folau");
console.log(greetingFolau);

// pass undefined instead null when intended to use default values.
let greetingLisa = hello("Lisa", undefined);
console.log(greetingLisa);

let greetingKinga = hello("Kinga", "Hi ");
console.log(greetingKinga);

Output

Hello there! Folau
Hello there! Lisa
Hi Kinga

Of course you can also check if parameters are undefined and set them to desired values

function sayHi(name, greeting){
    // if(greeting==undefined){
    //     greeting = "Hello there! ";
    // }
    
    // undefined check with ??
    greeting = greeting ?? "Hi there! ";
    return greeting+name;
}

Function as a parameter

The function as a parameter will be executed every time the main function is called.

function sayHi(name, greeting){
    // if(greeting==undefined){
    //     greeting = "Hello there! ";
    // }
    
    // undefined check with ??
    greeting = greeting ?? "Hi there! ";
    return greeting+name;
}

let greetingLau = sayHi("Folau");
console.log(greetingLau);

let greetingFusi = sayHi("Fusi", hello("Fusi "));
console.log(greetingFusi); //Hello there! Fusi Fusi

The arguments object

The arguments object contains an array of the arguments passed into the function. The arguments object behaves like an array though it is not an instance of the Array type.

let maxNum = findMax(1, 123, 500, 115, 44, 88);
console.log("maxNum: ",maxNum);//500
function findMax() {
    var i;
    var max = -Infinity;
    for (i = 0; i < arguments.length; i++) {
        if (arguments[i] > max) {
        max = arguments[i];
        }
    }
    return max;
}

Anonymous functions

An Anonymous function is a function without a name. An Anonymous function cannot be called before its declaration.

//saveData();//Uncaught ReferenceError: Cannot access 'saveData' before initialization

let saveData = function(){
    console.log("saving data to database");
}

saveData();

/*
* Functions that run immediately
*/
let name = "Lisa";
let age = 30;
(function() {
    console.log("name: "+name+",age: "+age);
})(name);// parameters are passed from outside variables.

let multiply = (function(a,b){
    return a * b;
})(10, 2);
// multiply here holds the result of the multiplication not an instance of the function
console.log(multiply);//20

 

Functions that run immediately(without being invoked)

let name = "Lisa";
let age = 30;
(function() {
    console.log("name: "+name+",age: "+age);
})(name, age);// parameters are passed from outside variables.

Arrow functions

An arrow function is a shorter way of declaring an anonymous function.

let updateData = (name) => {
    console.log("updating name in database.");
}

updateData();//updating name in database.

 

Source code on Github




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *