Mastering JavaScript Functions: A Comprehensive Guide for Web Developers

Mastering JavaScript Functions: A Comprehensive Guide for Web Developers

JavaScript functions are an integral part of the JavaScript language. They enable you to create dynamic and interactive web applications from handling users’ interactions to performing complex calculations. Functions are the building blocks for executing tasks in JavaScript thus, making them an essential tool for any developer. Whether you are new to JavaScript or you are looking to deepen your knowledge of functions, this comprehensive guide will deepen your understanding of JavaScript functions and its significance in modern web development and equip you with the knowledge to start writing reusable and efficient code.

Prerequisites

Before we dive into the world of JavaScript functions, it is essential to have a basic understanding of data types, and variables.

What Are Javascript Functions?

Functions are a block of code written to perform a specific task. They are simply workers sent to perform a specific duty. They can take in inputs, perform calculations and return values as outputs. Now you might be wondering why can't I just write all my code in a single long block? While you definitely can, there are tons of benefits to using functions: they allow you to organize your code in smaller and manageable chunks. With functions, you can create modular and concise reusable codes. In other words, you can use the same piece of code multiple times without having to rewrite it.

Consider the code below, they are all related and because of this, we can group them together in a function as we will see shortly.

/* without a function block*/
let a = 2;
let b = 3
let c = a+b;

Built-in Functions

Some JavaScript functions are accessible everywhere inside JavaScript, that is, they are global variables because they are not restricted to a particular scope neither are they tied to any object or datatype. They are provided by the JavaScript language itself. Some examples are typeof() which is used to indicate the data type of a variable, another of such is parseInt() which parses a string as an integer.

// how to use typeof method
const a = 2;
console.log(typeof(a)); //Output: ”number”

//how to use parseInt method
parseInt(‘77788799’); //Output: 7788799

Methods

Methods are functions that are called on objects. When you call a method, you are simply telling the object to perform. Methods are called using dot notation on an object. Examples are:

toUpperCase() - Converts a string to uppercase.
toLowerCase() - Converts a string to lowercase.

const sentence = 'The black lazy dog.';
console.log(sentence.toUpperCase()); //Output: THE BLACK LAZY DOG

However, the real power of JavaScript is on steroids when you define your own functions. This brings us to what is called Custom Functions.

Custom Functions

A function is created or defined after which they are called. A function takes in a parameter when they are defined and takes in an argument when they are called. A parameter can be described as a placeholder used to pass values in a function while an argument is an actual value or expression that is passed to a function when it is called.

Let's take a look at the basic syntax of a function:

function FunctionName(parameter(if any){
        Function body
}
FunctionName(argument);

To declare a function you use the “function” keyword then the name of the function (naming follows the same convention as that of a variable), then we have a parenthesis which takes in the parameter provided we have one or it is left empty, we then have the function body inside the curly braces. To run our function we include a parenthesis after our function name. When we have more than one parameter we separate them using commas.

// Example of a function with no parameter
function multiplyNumber(){
    return 2 * 4 
}
multiplyNumber() //Output: 8
greet(Alice) //Hello Alice

We can choose to dynamically change the values of “name” at any given time with the use of parameters just like the example below by passing the value as a parameter.


//Example of a function with a parameter

function  greet(name){
  console. log(`Hello ${name}!`);
}

greet(Alice) ;   // Hello Alice
greet(Grace); //Hello Grace

In this example, ”name” is the parameter and "Alice" is an argument passed to the greet function. The value "Alice" is provided as the actual input to the name parameter when the function is called.

Returning a function

The “Return” keyword is used to send a value as an output to a called function. If no value is returned explicitly, the called function returns undefined. This statement is usually followed by an expression that will be returned once a function is called. Once a ‘return’ statement is executed, the function is halted and the result is returned to the caller.

function addNumber(a, b){
   const  total = a + b
    return total;
}

addNumber(3, 4);  //Output: 7

If you type ‘total’ to the console, you will notice that we have an error:

“total”  is not defined

This is because the variable ‘total’ is only accessible within the addNumber scope, so to access this variable outside the said scope we need to redeclare it inside a variable outside the addNumber scope. So now we can always re-use the ‘add’ variable anywhere in our code.

function addNumber(a, b){
   const  total = a + b
    return total;
}

const add  = addNumber(5, 6); //11

Anonymous Functions

Another way to declare a function is by following the syntax we have seen but without a function name. The idea around anonymous functions is that they have no name, they are valid in some use cases such as callback functions.

 //basic syntax 
function(){
      function body
}

//Anonymous function example
function () {
       console.log("This is an anonymous function!");
 }

Function Expressions

These functions are written by assigning a variable to our function. We can also use anonymous functions when writing our function expressions.

const add = function (a, b){
    return a + b;
};

const result = add(3,4);
console.log(result); //7

We can also create a named function expression if we want to reference the current function within the function body; the given name is then only accessible within the function.

// A named function expression

const greet = function sayHello(name) { 
     console.log("Hello, " + name); 
}; 

greet("Alice"); // Output: Hello Alice

I know you might be wondering what is the difference between function declaration and function expression. The major difference is that with function declaration, you can call the function even before it has been declared.

//function declaration
greetDeclaration("Alice"); // Output: Hello, Alice

function greetDeclaration(name) {
  console.log("Hello, " + name);
}


// Calling a function expression before it has been declared will result in an error 

greetExpression("Charlie"); // output: // ReferenceError: Cannot access ' greetExpression' before initialization


const greetExpression = function (name) { 
          console.log("Hello, " + name);
 };

Arrow Functions

This function syntax is a little bit different from the usual function declaration. They are a shorter alternative to function expression. They allow for a single line of code and are concise although they do not allow reference with the 'this' keyword.

They are written as follows:

// Regular function 
function addRegular(a, b) { 
   return a + b; 
} 

// Arrow function 
const addArrow = (a, b) => a + b;

 console.log(addRegular(3, 4)); // Output: 7 
console.log(addArrow(3, 4)); // Output: 7

We can omit the curly braces and the return statement if the function directly returns an expression, but if we have additional lines of statements then the braces and return must be included.

const calculateArea = (width, height) => { 
        const area = width * height;
            if (area > 10) { 
         return "This is a large area.";
 } else { 
             return "This is a small area."; 
   } 
};

console.log(calculateArea(4, 3)); // Output: This is a small area. 
console.log(calculateArea(5, 6)); // Output: This is a large area.

Conclusion

In this article we have covered the basics of JavaScript functions, how to declare them, and how to call them in our codes.

With a strong understanding of functions we can write clean and efficient codes.

You can check out the MDN Docs to read more on JavaScript functions.

Happy coding!