Improving Function coding skills in JavaScript

Been a while since I wrote about JavaScript. Well, not really, it's been like 4 days but since I'm an obsessive person, I've spent a lot of time during the past days improving my JavaScript skills, in fact, most of my free time - yeah, the Missus has an issue with that but hey, a man's gotta learn and improve when a man's gotta learn and improve.

image.png

I'm pretty much up to date with my JS posts, meaning that the table below is up to date - remember, the little table that goes into detail about my little "Learning to code" project.

ConceptTime spent
Researching Howto8 hours
Downloading programs2 hours
HTML4 hours
Learning Javascript61 hours (so far)
Total (so far)75 hours

I've been reviewing Functions before getting on to the next level of Javascript, this level being the more advanced one. I already know the basics, about functions, loops, prototypes, methods and so on, so I'm some sort of an Adept in Skyrim terms, but I can't really call myself an expert and I can't really do much with my acquired knowledge right now, just brag about it on Hive, but there really isn't more to it, I can't do projects or develop little ideas I have, I can just write little pieces of code that work perfectly but I can't make them work out in the real world, the website developing world.

But hey, I can at least give you, dear developer-to-be or eager reader that will consume any piece of post such as this one, a thorough explanation of how Functions work on Javascript, so let's get to it.

Functions on JavaScript

"use strict";   

This way we write more secure code, it forbids us to make some things that are usually mistakes, and it makes errors more visible.

How to build a simple Function

A Function is a piece of code that we can use over and over again throughout our file

function  fruitProcessor(apples, oranges){ //1
    console.log(apples, oranges); // 2
    const juice = `Juice with ${apples} apples and ${oranges} oranges.`; // 3
    return juice;  // 4     
}
fruitProcessor(5, 0) // 5 

1.We specify parameters. Parameters are specific to this function.
2.These two functions will get defined once the function is called. They represent the input data of this function.
3.We are using these parameters as if they are normal variables inside the function.
We built a string using the input data that we get into the function.
4.We can return any value from the function. This value that we return can be used anywhere later in our code.
5.We run or call the function. The 5 and 0 are the inputs of the fruitprocessor function. The parameters are like empty spaces what we still need to fill out, when we call the function we fill in the spaces, and the values get assignes to the parameters. The 5 and 0 are called arguments.

But what about the juice? It was returned from the function, but we didn't store the function in a variable and we didn't call it.

So, for the final function we have:

function fruitProcessor(apples, oranges){
    const juice = `Juice with ${apples} apples and ${oranges} oranges.`;
    return juice;
}
const appleJuice = fruitProcessor(5, 0);
console.log(appleJuice);

Now we can create several juices with this function, we just have to define variables with different fruitProcessor arguments and call the variable.

function fruitProcessor(apples, oranges){
    const juice = `Juice with ${apples} apples and ${oranges} oranges.`;
    return juice;
}
const appleJuice = fruitProcessor(5, 0);
const orangeJuice = fruitProcessor(0, 5);
const mixedJuice = fruitProcessor(3, 3);
const orangeJuiceWithApple = fruitProcessor(1, 5);
const appleJuiceWithOrange = fruitProcessor(5, 1);

console.log(appleJuice,orangeJuice);
console.log(mixedJuice);
console.log(orangeJuiceWithApple);
console.log(appleJuiceWithOrange);

This was a function declaration, it is somewhat similar to declaring a variable but with more elements.

Now I will explain how to create a function expression

function calcAge1(birthYear){        // 1
    const currentYear = 2021;
    const age = currentYear - birthYear;
    return age;
}
const age = calcAge1(1988);  // 2
console.log(age);

1.We want the person's birthyear as an input (a parameter in this function)
2.We call the function and specify the argument of the function (1988) that will fill in the empty space in the function declared.

That was a function declaration, to write a function expression we store the whole function in a variable (and make an anonymous function).

const calcAge2 = function (birthYear){
    var currentYear = 2021;
    return currentYear - birthYear;
}
// We call the function in the exact same way.
const age2 = calcAge2(1992);
console.log(age2)

Both the declaration and the expression work the same way, but we might actually need to write them in one of these two ways depending on our code.

The main difference is that we can call function declarations before they are defined (ordering the calling before the definition), we cannot do that with expressions.

Arrow Functions

Apart from declarations and expressions, we have arrow functions. It is a shorter function and it is faster to write.

var calcAge3 = birthYear => 2021 - birthYear; // 1 
const age3 = calcAge3(1995);
console.log(age3); // 2

const yearsToRetire = birthYear => {
    const age = 2021 - birthYear;
    const retirement = 65 - age;
    return retirement;
}
console.log(yearsToRetire(2000));

1.We simply write what we want to return. We store it in a variable. The return happens explicitly, without us having to write "return" and we don't need curly braces, we can use it for one liner functions.
2.We use the arrow function when we only have one parameter and one line of code, but if we have more, then using this function becomes tricky.

Arrow functions do not get a ".this" keyword, so that's the only disadvantage to use them.

Calling a function from within a function. This is something that happens all the time while writing JS Code but it gets tricky, so let's explain the logic behind this.

function cutFruitPieces(fruit){
    return fruit * 4;
}

function fruitProcessor(apples, oranges){
    const applePieces = cutFruitPieces(apples);
    const orangePieces = cutFruitPieces(oranges);

    const juice = `Juice with ${applePieces} apple pieces and ${orangePieces} orange pieces.`;
    return juice;
}
console.log(fruitProcessor(2, 3));

This code will run as follows: We call the fruitProcessor function, which in turn while running will call the cutFruitPieces function, and it will do it twice, because we are giving it arguments for both parameters, apples and oranges.

image.png

By having two pieces of code this way, if one of the data pieces changes, we just change it in one function instead of doing several changes in separate parts of the code. Remember that most times we have thousands of lines of code, so changing one function is easier that to search and change all the data that we want to change.



That's it when it comes to Functions, you can actually start writing functions in JavaScript after reading this post, of course you won't be able to create them from nothing, but you can base your code on mine, if you really want to learn I recommend watching Youtube channels such as Whatsdev.


In the meantime, tell what do you make of all of this, maybe I can improve my code or maybe we can chat about code, I've been dying to become part of a coding community but to be honest I don't even know where to start (besides, I'm too much of a rookie to be an actual valuable part of any community yet, maybe in a couple of months once I can know what everyone is talking about :P).

By the way, I write all of my Coding related posts using @ecency, you should try out their interface, it is pretty cool!

H2
H3
H4
3 columns
2 columns
1 column
4 Comments
Ecency