JS Functions Made Easy

JS Functions Made Easy

A Beginner's Guide to Javascript functions

Introduction

When you write a block of code to perform a task, most of the time, you may need to reuse that block of code somewhere else in your program. When this happens, there are two options.

  • Rewrite the same block of code over and over again whenever you need it somewhere else in your program. This approach flouts the DRY (Don't Repeat Yourself) principle. It also makes your code large and complex. Avoid using this approach.

  • Find a way to 'save' that block of code so you can reuse it whenever you need it somewhere else in your program. This is a better approach. The 'saved' block of code is a function and the act of 'saving' the block of code is a function declaration.

What is a function?

A function is a group of statements written to carry out a specific aim. Functions are the fundamental elements of Javascript programming. Think of a function as wrapping a block of code in a value. You can use this value in different parts of your program over and over again. Functions help to structure large programs by breaking them down into sub-programs. Functions also promote code organization and easy maintenance.

An example of a function in Javascript:

function talk() {
    console.log("I am talking");
// output: I am talking
};

Function Declaration in Javascript

To use a function you first need to create it. A function declaration is one way to do that.

To declare a function:

// Use the keyword "function" and the name of the function - talk
function talk() {
// The function body which contains the code the function will execute
    console.log("I am talking…");
}

// the code will print "I am talking" to the console.

Remember that functions store code that performs a specific task. You can call a function anywhere in your program.

Function Expression: Defining a function by using a function expression

A function expression is another way of creating a function in Javascript.

It means writing a function and assigning it to a variable.

const driveCar = function() {
    console.log("the car is moving");
};

In the example above, we first declared a variable called "driveCar" and assigned a function to it.

Note that, in a function expression, there is no name after the function keyword. You can omit a name in a function expression to create anonymous functions.

Function Parameters and Arguments

Oftentimes, a function will need extra information to perform its task. Parameters are the extra information needed for the function to perform its task.

Parameters

Parameters are variables inside the parentheses of a function. Like variables, parameters hold the information the function needs to operate.

// numberOne and numberTwo are placeholders
function addNumber(numberOne, numberTwo) {
    console.log(numberOne + numberTwo);
};

In the example above, the function adds two numbers and returns the result. To do this, the function needs two values (numberOne and numberTwo) passed into it. The numbers (numberOne and numberTwo) are the parameters. Note that these values can be different anytime this function is called.

Arguments

Arguments are the values you specify in the parenthesis when you call a function.

Let's declare a function that prints a salutation to the console. This function will have a name parameter that it will use.

function salutation(name) {
    console.log("Good day, " + name);
};
// Now let's call the function.
salutation("John Doe");
// output: Good day, John Doe

When the salutation function is called, "John Doe" is used as a name. In this case, "John Doe" is the argument passed into the salutation function.

Parameters and Arguments

Parameters and arguments are often used interchangeably, but there is a slight difference between them.

Parameters are the values inside the parentheses. They act as variables in the function for the information it needs when declared. Arguments are the actual values passed into the function when it is called.

In a nutshell, parameters are defined when the function is declared, arguments are passed when the function is called.

Return Values: how to return values from a function

In Javascript, functions can return values. To return a value from a function, use the return keyword followed by the statement. The return statement specifies the value that should be returned when the function is called.

function multiplyNumbers(a, b ) {
    return a * b;
}
// declare a variable to store the multiplyNumber function
let answer = multiplyNumbers(2,5);
console.log(result)
// output will be 10

The multiplyNumbers function above takes two parameters; a and b, multiplies them together, and returns the answer using the return statement. When we call the function with arguments 2 and 5, the return value 10 is assigned to the answer variable and then printed to the console.

A return statement terminates the execution of a function and sends the value back to the caller. Any code written after the return statement will not be executed.

Some functions do not explicitly return a value. In cases like this, the function returns undefined by default.

Variable Scope

Wherever you declare a variable will affect where it can be used within your code. This is called the variable's scope.

In Javascript, a variable has a scope that affects its visibility and where it can be used in a script. A declared variable within a function can only be used within that function.

Types of Variables

  1. Local Variables

  2. Global variables

Local Variables

Local variables are variables that are declared inside a function. They are also known as function-level variables. A local variable has a local scope or function-level scope. A local variable can only be assessed inside the function it was created.

function sayHello() {
// local variale declared inside a function
    let person = "John";
    console.log("Hello," + person);
}
// output will be "Hello, John"

Inside the function sayHello(), we declared a variable called person and assigned it the value of "John". When the function is called, it will print a message containing the declared variable to the console.

However, if we call the "person" variable outside of the function, the output will be an error because the variable has a local scope. It can only be accessed within the function that it was declared. An example.

function sayHello() {
// declare a local variable.
var person = "John";
console.log(person);
}

// attempt to print the local variable outside the function
console.log(person);

//output: error.

This will produce an error because the variable is only accessible within the sayHello() function. It cannot be used outside of the function.

Global Variable

A variable declared outside a function is called a global variable. A global variable has a global scope and can be used anywhere in the script.

//Create a global variable outside the function and assign a value.
var constant = 5;

function addConstant() {
    //Declare a local variable
localNumber = 2;
//add the localNumber(2) to the constant(the global variable outside of the function).
console.log(localNumber + constant);
}
addConstant();
//The output will be 7;

We were able to access the constant variable because it is a global variable with a global scope. It can be used anywhere in the script.

Global Variables and Local Variables

Global variables are stored for as long as the webpage is loaded into the web browser. Local variables are only stored for as long as the function they are declared in is running.

Global variables take up more memory because of how long they are stored. Local variables use less memory because they are not stored forever, the browser only remembers them when a function is being executed.

Because global variables are accessible everywhere in the script, there is a risk of naming conflicts, ( assigning the same name to more than one variable). For this reason, it is always advisable to use local variables wherever possible.

Using local variables where necessary also helps with memory management and faster execution of programs. The fewer variables a script has to remember, the less memory it requires to run which makes your web page respond faster to the user.

Closures

A closure is a function that can access variables from its surrounding local scope. Closures allow a function to maintain access to variables and functions declared in its parent scope even after the parent function has finished executing.

function outerFunction(outside) {
    let fromVariable = 'from';
    // function declared within the outer function
    function innerRoom(inner) {
    console.log(outside + ' ' + fromVariable + ' ' + inner );
    }
    return innerRoom;
}
// declare a variable - closure and assign the outerFunction() to it.
let closure = outerFunction("Hello");

closure("inside"); // Output: Hello from inside

In the example above: the outerFunction() is declared with an inner function called innerRoom. innerRoom() function has access to the 'outside' parameter and the 'fromVariable' variable is defined in its parent function outerFunction().

When outerFunction() is called with the argument 'Hello', it returns the innerRoom() function.

The returned innerRoom() function still remembers the 'outside' parameter and 'fromVariable' variable, forming a closure.

The 'closure' variable is assigned the returned innerRoom() function.

When 'closure' is invoked with the argument "inside", it logs "Hello from Inside'' to the console. The innerRoom() function can access the 'outside' parameter value of 'Hello' and the 'fromVariable' value of "from", even though "outerFunction" has finished executing.

The closure captures and retains the variables and parameters from its outer scope, allowing the inner function to access and use them even if the outer function has completed its execution.

Recursion

It is possible for a function to call itself. When a function calls itself, it is said to be recursive. In other words, recursion is the ability of a function to call itself.

countToTen(value) {
    if (value === 10) {
    console.log("Complete!");
    }
    return;
    console.log(value);
    countToTen(value + 1);
}

countToTen(10);

The countToTen() function takes a 'value' parameter. There is a conditional statement defined as 'value === 10', the function logs "Complete!" to the console and stops the function.

In the recursive case, the function logs the current value using console.log(value) and then calls itself again with a bigger value by calling "countToTen(value + 1)" with the number increased by 1.

Recursion helps to solve complex problems by breaking them into small bits and solving them one by one.

Note that recursion is not always the ultimate solution as there are simpler approaches available, but some problems are easier to solve with recursion. Balance is key.

Summary

In summary, functions in Javascript are blocks of code that can be reused to perform specific tasks. They help organize code, promo code reusability, and make programs easier to maintain.

Functions can be declared using the function keyword, followed by a name and a code block.

Functions can have parameters to receive input values and can return values using the return statement.

Variables have scope, with local variables limited to the function they are declared in, and global variables accessible throughout the script.

Closures allow functions to access variables from their parent scopes.

Recursion enables functions to call themselves, solving complex problems by breaking them into smaller parts.

Understanding these concepts is essential for effective programming and building robust applications.