Introduction to Functions in JavaScript (JS)

How to create a JS function?

A JavaScript function is a block of code designed to perform a specific task. It will be executed only if it is called. 

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Inside parentheses (), it may also contain function arguments separated by comma.

Function names can contain letters, numbers, dollar signs and underscores. 

				
					// defining a function without function arguments
function displayMessage() {
  alert('Hello world!');
}

// defining a function with function arguments
function displayAddition(a,b) {
  let result = a+b;
  alert('Addition is:'+result);
}
				
			

How does a JS function return value?

A return keyword is used to return a value from JavaScript function.

Syntax: return value;

				
					function addition(a, b) {
  return a + b;
}

let result = addition(10, 5);
alert(result); // 15
				
			

Flexibility of arguments in a JS function

A function in JavaScript can be called with missing argument. These missing arguments are set to undefined by default. 

				
					function showMessage(message) {
  // if message is undefined or null, show "No message"
  alert(message ?? "No message");  // ?? is known as Nullish coalescing operator in JavaScript
}

// Calling a function with function argument
showMessage("Welcome"); // Welcome

// Calling a function with 'null' function argument
showMessage(null); // No message

// Calling a function without function argument
showMessage(); // No message
				
			

How to set default value for a JS function argument?

If a function in JavaScript is called with missing arguments (less than what is declared), the missing arguments are set to undefined. A default value can be assigned to such missing arguments.

				
					function addition (x, y) {
    if (y === undefined) {
    y = 0;
  }
  return x+y;
}

// Above function can also be written in following way:
function addition (x, y = 0) {
  return x+y;
}

// Calling a function with only one argument, second argument is missing here. Default value for second argument is set to 0.
addition(5); // 5

//How to use default value for first argument?
function abc(num1=30, num2=60){
    console.log(num1)
    console.log(num2)
}

abc(undefined, 20)
//Note: We can provide 'undefined' in function call to use default value
//for any of the argumemnts before the last argument.



				
			

JS Function Expressions

JavaScript function can also be defined using an expression. There is another syntax for creating a function that is called a Function Expression. A variable can be used to store a function expression.

In function expression, we can skip providing a function name after function keyword.  Omitting a name is allowed for Function Expressions. Such function expression is called as anonymous function expression.

				
					// Creating a function and put it into the variable 'mesg'
let mesg = function() {
  alert( "Hello" );
};

alert(mesg); // Hello

				
			

Arguments Object in JS Functions

In JavaScript, the arguments object is a special array-like object that is available within regular (non-arrow) functions. It provides a way to access the arguments passed to a function, even if those arguments were not explicitly defined as parameters in the function’s parameter list.

Here’s an example of how the arguments object works in a regular function:

				
					function calculateSum(){
    let sum = 0
    for(let i = 0; i < arguments.length; i++){
        sum += arguments[i]
    }
    return sum
}

console.log(calculateSum(10,203,20,300))
console.log(calculateSum(20,300,236,258,45,56))
				
			

What is Immediately Invoked Function Expression (IIFE) in JavaScript?

				
					(function() {
    // code goes here
})();

				
			

An Immediately Invoked Function Expression (IIFE) is a JavaScript design pattern that involves defining and executing a function immediately after its creation. This pattern is commonly used to create a private scope for variables and functions within the function, preventing them from polluting the global scope.

Here’s the basic syntax of an IIFE:

Let’s break down how an IIFE works:

  1. It starts with an anonymous function defined within parentheses (function() { ... }). This function can also take parameters if needed, such as (function(param1, param2) { ... })(value1, value2).

  2. The entire function is enclosed in parentheses (function() { ... }). The outer parentheses are used to indicate a function expression.

  3. After defining the function, you immediately invoke it by adding another pair of parentheses at the end ();. This causes the function to execute right away.

Here’s an example of an IIFE:

				
					(function() {
    var localVar = "This is a local variable";
    console.log(localVar);
})();

				
			

In this example, localVar is scoped within the IIFE and cannot be accessed outside of it. This helps avoid naming conflicts with variables in the global scope.

IIFEs are often used to encapsulate code, create modules, or simply to avoid polluting the global scope with temporary variables and functions. They are especially useful when you need to execute code immediately without waiting for an external event or function call.

Rest Parameter

Rest parameters in JavaScript allow you to represent an indefinite number of arguments as an array. They are useful when you want to work with a variable number of arguments in a function. Here’s a small example of how to use rest parameters:

				
					function sum(...numbers) {
  let result = 0;
  for (let number of numbers) {
    result += number;
  }
  return result;
}

console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(10, 20, 30, 40, 50)); // Output: 150

				
			

In this example, the sum function takes any number of arguments, and the ...numbers syntax collects all the arguments into an array called numbers. The function then iterates through the array and calculates the sum of all the numbers passed to it. This allows you to work with a variable number of arguments without explicitly specifying them in the function definition.

Assignment

  1. Write a JavaScript function expression that accepts a number as an argument and return its cube.
  2. Write a JavaScript function to calculate average of 3 numbers. If any of the numbers is not passed then use default value as ‘1’.
  3. Write a JavaScript function that accepts a date and print the day of a week for this date. If date is not passed then print output as ‘Invalid date’.