Understand and write JavaScript functions like a Pro

Understand and write JavaScript functions like a Pro

As a beginner who just started writing JavaScript, have you ever found yourself writing the same code same repeatedly to achieve the same result or declare so many variables in your global scope to help you achieve a task procedurally (I will elaborate more on scoping so don't think about it too much for now)?

Then you need to read this article meticulously because this is definitely the game-changer you need to make you a better developer who writes clean and well structured readable code using functions.

At the end of this article, you should already understand

  1. What is a function and how essential it is to programming
  2. How to define a function using a variable and built-in function keyword
  3. Types of function in JavaScript and what are the differences between them
  4. Scoping and how they relate to function

What is a function and how essential is it to programming

The function is the holy grail of programming, the way it helps us abstract away lots of code and saves it in a value is simply amazing.

Let me use a real-life picture to give you a better understanding of what a function is before I go forward to give you a more in-depth explanation of a function programmatically.

Let us take our analogy using a car, imagine the car functions and how each function is abstracted away from the other and yet works simultaneously.

The driver doesn't have to worry about what happens when he matches the break, he knows within himself that measures have been put in place to ensure that the break does its job.

I can go on and start explaining what happens under the hood when a car break is matched, but that would be me flexing my muscles in mechanical engineering. Though by now I think you already got the gist.

Segregating our codes into functions gives us a way to structure our larger program into smaller chunks and make sure that the variables defined within remains local to the function and doesn't interfere with other parts of our programs.

Functions also help also avoid code repetition and flooding our namespace with so many variables.

How to define a function

You now understand what a function is and how useful it is to developers, so let us now look at ways we can define one.

one of the ways we can define our function is by declaring a variable where the value is written as a function.

let's look at an example

let square = function (x) {
  return x * x;
};
console.log(square(2));
// prints 4 to the console

Let me explain what happened in the code above. We declared a function and saved it in a variable name we defined as a square. What it means is that whatever the function returns will be the value saved in our square variable. Our function also takes in an input which is referred to as a function parameter and multiplies that input by itself.

In JavaScript, a function is declared starting with the function keyword. The function body must be wrapped in curly braces and that is where the main action happens. Functions can have multiple parameters or no parameter at all.

Let us look at another way we can define our function with another code example

function greet() {
  console.log("Hello, World");
}

greet();// prints Hello, World

If you understood the first example, this wouldn't be hard to comprehend either. What I did differently here is to start my function declaration with the JavaScript function keyword before its name.

The greet function has no parameter and a return keyword, which brings me to another point. In fact, it was one of the things I struggled with when I was learning JavaScript functions.

I always found myself asking how a return keyword differs from console.log in a function and since I don't want you to pass through the same vicious circle let me elaborate.

Return keyword returns a value that can be saved separately in a variable and used afterward while console.log just prints out stuff and can't hold a reusable value within the function.

Let us look at an example with our square function

let square = function (x) {
  return x * x;
};


let squareValue = square(2)
console.log(squareValue)

// prints out 4 to the console

function greet() {
  console.log("Hello, World");
}

let greetValue = greet();
console.log(greetValue);
// return undefined

I said earlier that functions can be declared with multiple parameters right so let us look at an example with an add function

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

add(2, 5);
// 7

If you declare a function with two-parameter and finally give it one, it will return the second parameter as undefined, alternative if you declare a function with one parameter and gives it more than one argument, it will use the first argument and ignore the rest

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

add(2, 5, 7, 7);// 7

Types of functions in JavaScript

Apparently, we have been looking at different types of ways we can write a function above and we have been using one type which is defining a function with the function keywords but let us look at another way we can achieve the same result without the function keyword.

Arrow function

Arrow function was recently introduced in ES6, honestly, I don't see any major advantage of one over the other except for the fact that it deals with this problem when working with JavaScript classes (Classes will be discussed in a future article) but since it's at our disposal, we should also know how it is defined in case we want to use it anytime.

const add = (a, b) => a + b;
add(1, 2);

//prints 3

First, we define our variable which will be the function name, and then the brackets that take in our parameters just like our normal function, and then the arrow before the return body. Don't confuse the arrow with the > sign which means greater than. One good reason I prefer to use this function is that when my argument is one, I can omit the brackets for the parameter and also I don't have to include the return keyword.

const addSelf = (a) => a + a;
addSelf(1);

//prints 2

IIFEs

Immediately invoked functions as they are known is just a convenient way for us to define anonymous functions on the go.

Let me elucidate so you can understand what I mean. There are times you don't want to reuse a function and instead of declaring a function and keeping it in the namespace, you can just declare it and use it on the go. IIFEs gets called after it is declared.

let's see some example

const person = (age) => {
  if (age < 21) {
    (function () {
      console.log("young");
    })();
  } else {
    (function () {
      console.log("old");
    })();
  }
  return age;
};

person(30);


// old
//30

Scoping and how they relate to functions

Now to be able to define useful functions that run without errors, you need to understand scoping and how they can affect the variables in your functions

They are two types of scoping in JavaScript and programming in general.

  • Global scope
  • Local Scope

All variables in the Global scope can be accessed in all parts of your program while those in your local scope can only be accessed in the scope in which they are defined.

let a = 10;

function scopeSample() {
  let b = 20;
  console.log(a);
}

console.log(b);
scopeSample();

// b not visble in the global scope
// 10

but when there is the same variable name in a different scope, the code will take the one in its innermost scope

let a = 10;

function scopeSample() {
  let b = 20;
  let a = 5;
  console.log(a);
}

console.log(b);
scopeSample();
console.log(a);

// b not visble in the global scope
// 5
//10

Conclusion

By now you should understand what a function means, how useful they are, the different ways you can define them, and how you can prevent running into errors by scoping your variables the right way.

I can tell you that if you understood everything above, then you are on your way to becoming a better JavaScript developer and I am glad to be one of your guides through this journey.

Please I will appreciate your feedback and also topics you would like to write about. Also, share this article if you found it useful. See you soon.