JavaScript Functions for Muggles!!

JavaScript Functions for Muggles!!

What is a JavaScript function?

They are code lines that perform specific tasks within a program. It is also the algorithm in charge of giving life or functionality to any element with which a user interacts through the software interface. The functions are responsible for the internal execution of any command that we are developing and have the mission to fulfill only and exclusively the action assigned to it.

Creating a function. Function declarations and functions expressions in JavaScript

How to create a function in JavaScript?is one of the most important steps for the flow of an algorithm. There are many ways to define or write them but understanding the difference between a function declaration and an function expression can help us to develop in a better way.

Function declaration syntax

Function declarations begins with the keyword?function?and then the name of the function. This name MUST be the one that best suits the task to be performed by the function; the function name follows the same?rules for naming variables?and is then followed by its respective parenthesis () where the parameters will be placed (if required) and curly brackets {} where the logic or algorithm to be performed by the function will be placed.

//Function declaration example

let?point1?=?10;
let?point2?=?15;

function?pointSum?(?)?{
  console.log?(?point1?+?point2?);
  //Output = 25
}        

Later on we will see what the?parameters of a function?are.??

Function expression syntax

Function expression works exactly the same as a function declaration, the difference is in the way they are defined and hoisting. To create an function expression you must declare a variable that will contain that function, then write the function following the same rules as a function declaration.

//Function expression example

let?school?=?"Hogwarts";

let?greetings?=?greets?(?)?{
  console.log?(?"Welcome to "?+?school?);
  //Welcome to Hogwarts
}        

Now that we know the basics about?JavaScript functions?let's learn how to call these functions. The examples from now on can be declarative or expressive, whatever I feel like for the script of this article and its subject matter. ??

??Invoking or calling functions in JavaScript

To use a function we only have to write the name we have given to the function followed by its parenthesis.

//Invoking a function

function?spell?(?)?{
  console.log?(?"Lumos"?);
}
  
spell?(?);
  
//Function expression example
  
let?enchant?=?function?enchanting?(?)?{
  console.log?(?"Wingardium?leviosá?leviosa"?);
}
  
enchant?(?);        

Function parameters and function arguments in JavaScript

Parameters are data that are passed to a function to perform a process with the information that is being provided. This data can be of any type (variables, an?object?and even other functions) depending on the need of the algorithm.

To pass data to a function we must create it and then determine how many and which parameters it must take to perform its task.

function?functionWithParameters?(?parameter1,?variableAsParameter?)?{
  //Some random code
}        

An example. Suppose we want to cast a spell using a function, we can declare a function and pass it a parameter containing the spell we want to cast.

let?spell?=?"Accio";

function?spellCast?(?spell?)?{
  console.log?(?`Spell done:?${spell}`?);
}
  
spellCast?(?spell?);
  
//If we change the spell value the spellCast will have that new value        

Default parameters on a JavaScript function

One of the features that the language updates from ES6 is the ability to pass parameters with default values.

function?spellCast?(?spell?=?"Accio"?)?{
  console.log?(?`Spell done:?${spell}`?);
}
  
spellCast?(?);
  
//Now the default spell to be cast is Accio but if we write an argument the result of the spell cast is the one we stipulate        

Hey, and what are the?arguments of a function???

The arguments are data that we are going to provide to the function, if it has parameters, when this one is invoked. If it is not clear to you, let's see the difference between parameters and arguments. Let's take the same example as above:

function?spellCast?(?spell?)?{?//Parameters
  console.log?(?`Spell done:?${spell}`?);
}
  
spellCast?(?"Accio"?);?//Arguments
  
//Now if we change the value of the argument the spell cast changes        

Now your level of understanding of the functions has increased. 50 points for the house you belong to! ??. Let's look at other?types of functions.

Anonymous functions in JavaScript

What is an anonymous function?

As the title of this section describes, these are functions that do not have a name and are invoked through a variable as if they were an function expression.

const?conjure?=?function?(?conjureName?)?{
  console.log?(?conjureName?);
}
  
conjure?(?"Revelio"?);        

Callback functions in JavaScript

What is a callback function?

Callbacks are functions that are passed by parameter to another function and are executed once the function that executed it has finished its process. An example of this are the events (like a click or a mouseover) but we will make a simpler example.


function?unforgivableCurse?(?victim,?callbackCurse?)?{
  console.log?(?`Curse?${callbackCurse()}?to?${victim}`?)
}
  
unforgivableCurse?(?"Potter",?<--- 1st parameter
  function?callbackCurse?(?)?{?<--- 2nd parameter
    return?"Avada Kevadra";
}?);        

This is the first time in this article that we see the word?return??; until now we have only shown examples with messages in the console. If you notice the console object has a?log?method which is similar to executing a function but the differences between a method and a function, at a glance, are the following:

  • Methods are preceded by dots
  • That is why the?methods of an array?or an object are not called functions as such.
  • Functions act according to the logic or algorithm we design
  • Methods already have a predefined logic to accomplish their task.

Functions that return values

The functions almost always have to return a value that is the data that the function has processed to be used in another part of our program. That is why we use the word?return?at the end of the functions. Let's code a little more


function?transform?(?item,?transformation?)?{
  return?`${item}?transforms into?${transformation}`;
}
  
//When a return is used, a variable must be used to manipulate the data returned
  
const?transformationResult?=?transform?(?"Cat",?"Vase"?);
  
alert?(?transformationResult?);        

These values can be used in more complex ways, whether for mathematical operations, displaying information on screen by manipulating the DOM or passing a processed data to another function. It all depends on the complexity or requirements of the algorithm.

Arrow functions in JavaScript

How to do an arrow function?

This type of function performs the same task as a conventional function, its syntax is a little different because it does not use the keyword?function, instead it uses the equal and greater than signs forming an arrow (=>) to determine that it is a function.

Another difference of the?arrow functions?is that it is not affected by hoisting so it is determinant the use that you are going to give to this type of function inside your algorithm.

The third characteristic of an?arrow function?is that they can be summarized in a single line of code as long as its logic is to return a value. Let's see in code all these qualities.


//Arrow function syntax

let?patronus?=?(?happinessLevel?)?=>?{
  return?"Expecto Patronum";
}
console.log?(?patronus?(?9?)?);
  
//As this function only returns a text, it can be simplified to
  
let?patronus?=?happinessLevel?=>?"Expecto Patronum";
console.log?(?patronus?(?9?)?);
  
//If the function had a more complex algorithm, this simplification would not be possible
  
//Since there is an argument with the number 9 let's do that task with a?condition block
  
const?patronus?=?(?happinessLevel?)?=>?{
  
  let?run?=?( )?=>?""??RUUUUUUUUN!!;
    
  if?(?happinessLevel?>=?5?)?{
    return?"Expecto Patronum";
  } else {
    return?run();
  }
    
}
console.log?(?patronus?(?9?)?);        

If you liked this post or it helped you to better understand JavaScript functions let me know through my social networks, share it and let me know what you thought about it.??

There is a spanish version of this post here:

Check it out!

要查看或添加评论,请登录

Manuel De Leon ????的更多文章

社区洞察

其他会员也浏览了