Functions in JavaScript in Depth

Functions in JavaScript in Depth

What are functions in JavaScript?

In JavaScript, a function is a reusable block of code that performs a specific task or set of tasks. Functions are a fundamental building block of JavaScript programming and are used to organize code. They are crucial for organizing and structuring JavaScript programs. They promote code modularity, readability, and maintainability. Functions are treated as first-class citizens. There are some types of functions. Functions reduce the redundancy (repitition) of code.

Type-1: Function without Parameter

Function Declaration or Definition

Functions can be declared using thefunction keyword, followed by a name, parentheses() . These parentheses may include parameter names separated by commas like (parameter1, parameter2, ...) , and the code to be executed enclosed in curly braces{}. This is the function without parameters.

For Example:

// Function without parameters
function hello() {
    console.log("Hello, This is our first function");
}

Function Calling or Invoking

You can call or invoke a function by using its name followed by parentheses(). If the function takes parameters, you provide those values inside the parentheses.

For Example:

// Function without parameters that we declare or define above
function hello() {
    console.log("Hello, This is our first function");
}
// Calling the function by using its name followed by parentheses ()
hello();
Output: Hello, This is our first function

Type-2: Function with Parameter

Here are two types of parameters:

1. Function with default parameters.

They allow you to assign default values to function parameters. The function uses the default value if a caller does not provide a value as a parameter while calling the function. If the caller provides the value as an argument while calling, then it will override the default parameter.

For Example:

// Function with default parameter
function welcomeFunc(name = "Muhammad Bilal") {
    console.log(`Hello, ${name} Welcome to the JS Blog.`);
}
welcomeFunc();
Output: Hello, Muhammad Bilal Welcome to the JS Blog.

welcomeFunc("User"); // Here this argument overrides the default value.
Output: Hello, User Welcome to the JS Blog.

2. Function without default parameters.

These parameters don't have default values assigned in the function declaration. You must provide values for all parameters when you call the function.

For Example:

// Function with parameters value as argument while calling
function welcomeFunc1(name) {
    console.log(`Hello, ${name} Welcome to the JS Blog.`);
}
welcomeFunc1("Muhammad Bilal"); // Giving argument here is necessary.
Output: Hello, Muhammad Bilal Welcome to the JS Blog.

Type-3: Function with return value

In JavaScript, you can create functions that return a value using the return statement. Then you can use the returned value in various ways, such as assigning it to a variable, using it in further calculations, or displaying it in the console. Functions also have their scope; you can capture variables from another function's scope by usingreturn.

For Example:

// Function with return keyword
function addTwoNumbers(number1, number2) { 
    return number1 + number2; // Here it return addition operation
// After this return value nothing gonna work.
}
// Function call and assigning the value in variable
let result = addTwoNumbers(3, 4); // These values are known as arguments
console.log(result); // If we console that variable then output is 7
Output: 7 // This is the value of assigning variable result

Why is there a need to use the return function?

If we console the parameters within a function and then assign them to a variable for printing, it will print undefined as output. For returning that value, we use return keyword.

// Simple Function 
function addTwoNumbers(number1, number2) { // These values are parameters
    console.log(number1 + number2); // perform the arithmetic operation
}
// Function call and assigning the value in variable
let sumResult = addTwoNumbers(3, 4); // These values are known as arguments
console.log(sumResult); // If we console that variable then output is undefined   
Output: 7 // This is the value where we call the function
Output: undefined // This is the value of assigning variable sumResult.

Here the concept came that what we have returned from the function

Let's see a practical example of the return function.

function loginUserMessage(username) {
    if (!username) {
        console.log("Please enter a username");
        return // This is written here because after this nothing gonna work
    }
    return `${username} Just logged in`;
}
console.log(loginUserMessage("Muhammad Bilal")); // If there is no argument then output is undefined   
Output: Muhammad Bilal Just logged in

Note:

If you want to avoid an undefined value then you can use the default parameter that we discussed above.

function loginUserMessage(username = "Pass name to") {
    if (!username) { // Here ! denotes the not 
        console.log("Please enter a username");
        return // This is written here because after this nothing gonna work
    }
    return `${username} Just logged in`;
}
console.log(loginUserMessage()); // If you pass argument so it overrides the default value.  
Output: Pass name to Just logged in

console.log(loginUserMessage("Muhammad Bilal"));
Output: Muhammad Bilal Just logged in

Type-4: Anonymous Functions

In JavaScript, anonymous functions refer to functions that are defined without a specified name. They are often used for short, one-time operations or as arguments to other functions.

For Example:

function(num1, num2) {
    return num1 * num2;
}

To identify this function we have to store it in a variable.

const myFunc = function(num1, num2) {
    return num1 * num2;
}
console.log(myFunc(2,5));
Output: 10

// You can again store it into variable before consoling.
const myFunc = function(num1, num2) {
    return num1 * num2;
}
const output = myFunc(3,6);
console.log(output);
Output: 18
// Both ways are Ok, you can do it in both ways.

Type-5: Arrow Functions

Arrow functions are a concise or compact way to write anonymous function expressions in JavaScript. They were introduced in ECMAScript 6 (ES6) and provide a shorter syntax compared to traditional function expressions. Arrow functions are particularly useful for short, one-line functions. These are also known as fat arrow functions.

For Example:

// Traditional function expression
const myFunc = function (num1, num2) {
    return num1 * num2;
};
console.log(myFunc(2,5));
Output: 10

  // Fat Arrow function
const arrowFunc = (num1, num2) => {
    return num1 * num2;
}
console.log(arrowFunc(2,5));
Output: 10

This can be written more shortly. While returning you don't need to write curly braces {}. While not applying curly braces {}, you don't need to write return keywords. This is a implicit return way of returning a value from a function without explicitly using the return keyword.

// Arrow function without curly braces {} and return keyword
const arrowFunc = (num1, num2) => num1 * num2;
console.log(arrowFunc(2,5));
Output: 10
// Arrow function with implicit return 
const arrowFunc = (num1, num2) => (num1 * num2); 
// Here you can use parentheses () This is used when you need to return
// an object. like ->  ({blog: 'JavaScript'})
console.log(arrowFunc(2,5));
Output: 10

If there is one parameter in the parenthesis,() then you don't need to write parenthesis() .

// Arrow function without curly braces {} and return keyword and parenthesis ()
const arrowFunc = str => str; // 
console.log(arrowFunc("Muhammad Bilal"));
Output: Muhammad Bilal

Note: this Keyword

We will discuss this keyword separately in-depth and also in terms of objects.

Type-6: Callback Functions

In JavaScript, a callback function is a function that is passed as an argument to another function and is executed after the completion of a specific task. Callback functions are often used in asynchronous programming, where certain operations take time to complete, such as reading a file, making a network request, or handling user input.

For Example:

let arr = [1, 2, 3, 4, 5, 6];
arr.forEach( (value) => {
    console.log(value);
});
Output: 
1
2
3
4
5
6

We will discuss foreach in an upcoming blog.