callback functions

callback functions

The callback functions are used in JavaScript to ensure that the code is asynchronous, i.e. executed after a certain event, such as when a button is clicked, or when you pass over an element of the html page, etc.

We have also seen in previous articles that callback functions can be passed as arguments to functions, as they are objects.

In this article we will give some more examples to better understand their use.

In fact, their use with other predefined methods is interesting, as in the first example below.

callback functions – first example

We remove the odd elements from a previously populated array.

First let’s create our array of numbers.

Next we create an anonymous function in JavaScript which we store in a variable number.

So in the variable number we are storing our callback function, which represents our object.

Then we filter the array using the filter method which invokes our callback function in Javascript, which was created to return true if an element is even.

The callback function takes a single parameter that represents each single element of the array that must be evaluated.

Then the function is called without round brackets within the filter method.



var array = [5,7,8,9,10];

var number = function(n) {
  if(n % 2 == 0){
    return true;
  }
};

//number becomes the function that I can call, therefore:
var num = array.filter(number);
console.log(num);

The console.log will print the array with only even numbers.

Therefore, the same function can also be written like this:



var array = [5,7,8,9,10];

var n = array.filter(function (n) {
  if(n% 2 == 0){
    return true;
  }
});

console.log(n);

callback functions – second example

We insert 5 numbers in an array at the click of the button and then display their sum.

Also in this case we use an anonymous callback function within which we call the functions askNumbers and sumNumbers.

The AskNumbers function takes an array and the quantity of numbers to insert as arguments, while the AddNumbers function takes the array as an argument.



var numbers = [];

var calculation = document.getElementById('calculation');

calculation.addEventListener('click',function (){
  insertNumbers(numbers, 5);
  var sum = sumNumbers(numbers);
  alert('Sum is: ', sum);
});


function insertNumbers(arr, q){
  while (arr.length < q){
    var n = parseInt(prompt('Insert a number));
    arr.push(n);
  }
  return arr;
}

function sumNumbers(array){
  var sum = 0;
  for (var i = 0; i< array.length; i++){
    sum += array[i];
  }
  return sum;
}

Conclusion

We have done some exercises on callback functions in JavaScript, in the next lessons we will return to this topic.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

callbacks

callbacks

Callbacks in JavaScript, as seen in the previous lesson, can be passed as arguments to other functions.

In fact, functions in JavaScript are objects. We can also see this simply by doing the console.log of a function.

For example, if we have this JavaScript function:



var number = function(item) {
  return 10;
};

console.log(number);

If you do the console.log() of the variable number we will see that it is an object, as shown in the following figure:

funzione oggetto

Callback functions can be anonymous or have a name. The obvious advantage of having a name is that they can be called up in other portions of code, as well as making the code more readable.

Why are callbacks in JavaScript useful?

As we know JavaScript executes the code sequentially, and sometimes we need to execute the code after something else occurs. That is, we need to do something asynchronous!

Callback functions allow you to execute code only after completing certain actions. They are then recalled after completing an activity.

callbacks – examples

Let’s take another simple example of a callback function used to calculate the area of ​​the rectangle at the click of a button.

If we have a button with a calculation id on the HTML side:

<button id="calculation" class="btn">Calculation</button>

In JavaScript we program the areaRect callback function.

Here is the complete code with callbacks:



var calculation = document.getElementById('calculation');

calculation.addEventListener('click',areaRect);

function areaRect(a,b){
  a = parseInt(prompt('Enter the base value: '));
  b = parseInt(prompt('Enter the height value: '));
  alert(a*b);
}

So only after clicking on the button will the areaRect function start, which therefore waits for the click to finish.

Try not to release the mouse button right away.

Notice how, after the areaRect callback function, there are no round brackets.

Let’s make a small variation of the previous example, in order to create an additional function for printing the area of ​​the rectangle.

So the areaRect function will only return the calculation of the area. While the printArea function, which has as its argument only the areaRect function, will print the result.

Here is the complete code that shows the use of callbacks:



var calculation = document.getElementById('calculation');

calculation.addEventListener('click',printArea);

function areaRect(a,b){
  return a*b;
}

function printArea(){
  let base = parseInt(prompt('Enter the base value: '));
  let height = parseInt(prompt('Enter the height value: '));
  printResult = areaRect(base,altezza);
  alert(printResult);
}

The above code can also be written via an anonymous callback function in JavaScript:



var calculation = document.getElementById('calculation');

calculation.addEventListener('click',function (){
  let base = parseInt(prompt('Enter the base value: '));
  let height = parseInt(prompt('Enter the height value: '));
  printResult = areaRect(base,height);
  alert(printResult);
});

function areaRect(a,b){
  return a*b;
}

Conclusion

In this lesson we explored callbacks in JavaScript we will continue to talk about them in the next article.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

JavaScript callback

JavaScript callback

In this lesson we will talk about JavaScript callback functions, which are functions that are passed as parameters to other functions.

In the JavaScript version ES5 they are widely used, while in the ES6 they leave room for the promises that have become a native component of the language. A few years ago, in fact, the promises were used only thanks to external libraries.

Callback functions derive from a programming paradigm known as functional programming.

It is also good to remember that when we pass a callback function as an argument to another function, we are not executing the function, but we are only passing the definition of the function. So we don’t have to use round brackets, as we do when we execute a function instead.

JavaScript callback – first example

In this first example we will use a simple function for the sum of two numbers and then we will pass it as a parameter to another function.

So here is the code of our function which simply takes 2 numbers and returns their sum:



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

The function to which we will pass our function as an argument, therefore without brackets we will call it callsCallBack simply to make it clear that it calls a callback function.



function callsCallBack(callback){

  var number1 = parseInt(prompt('Insert a first number '));
  var number2 = parseInt(prompt('Insert a second number '));

  alert(callback(number1,number2));

}

Now let’s call the function:



callsCallBack(sum);

If you try the script you will notice that an alert will appear where the sum of the two numbers taken as input will be visible. If you prefer, use the console.log()!

JavaScript callback – second example

In this second example we will create an evenOdd function that returns true if a value passed as an argument is even, otherwise it returns false.

After our function callsCallBack we will pass a number and the function just created as arguments, without brackets. If the number passed is even we will print the string ‘even number’, otherwise we will print ‘odd number’.



function evenOdd(item) { 
  //function which will then be passed as an argument without brackets
  if (item % 2 == 0){
    return true;
  } else {
    return false;
  }
}

function callsCallBack(x,callback){ 
    //the parameters are a number and a function
    if (callback(x)) {
      console.log('even');
    } else {
      console.log('odd');
    }
    return x;
}


for (var i = 0; i < 10; i++){
  var n = parseInt(prompt('insert a positive number'));
  var y = callsCallBack(n,evenOdd);//I call the function without brackets
  console.log(y);
}

JavaScript callback – third example

In this third example we will populate an array of only numbers greater than or equal to zero (we discard only the negatives), again using the callback functions.

Then we create our positiveNegative function which returns a Boolean value.
Then we create the myArray function to which we pass a number, an array and a function as an argument (so I remind you without brackets), and we add the element to the array only if it is positive. This function returns our array.

Finally, through a for loop we ask for a number and call the popolaArray function with our parameters.

If we do the console.log() we can see our array populated with only numbers greater than or equal to zero.



function isPositive(item) { 
  if (item >= 0){
    return true;
  } else {
    return false;
  }
}

function myArray(x,array,callback){ 
    //where the parameters are a number, an array and a function
    if (callback(x)) {
      console.log('positive number - put it in the array');
      array.push(x);
    } else {
      console.log('negative number - don't put it in the array');
    }
    return array;
}

var numbers = [];

for (var i = 0; i< 10; i++){
  var n = parseInt(prompt('insert an integer number'));
  var y = myArray(n,numeri,isPositive);
  //I call the function without brackets
  console.log(y);
}
console.log('array: ' , numbers);

Conclusion

In this article we have seen some simple examples of using JavaScript callback functions, in the next lessons I will propose many other practical examples.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

format JSON

format JSON

format JSON – JSON is a format used for data exchange and is the acronym for JavaScript Object Notation.

It is based on the JavaScript language and is used a lot for asynchronous programming, therefore with ajax, as we will see in the next lessons.

JSON is a text format, so it is a string. It allows you to aggregate data and follows the syntax of JavaScript objects.

But it can be used independently of JavaScript, in fact many programming languages ​​use it and therefore also allow you to do the parse.

A JSON object is created using a pair of curly brackets that are used to contain the whole object. Then, inside these brackets, the various properties are inserted indicating key-value pairs and making sure to use double quotes for both the key and the value. Each property of the object is separated by a comma.

format JSON – example

Let’s take some examples of JSON objects.

This is an example of JSON format:



{
  "type":"Fiat",
  "model":"500",
  "color":"white",
  "powerSupply":"gas",
  "year":"2010"   
}

The json data is described as key-value pairs, in this example we have an auto object with some property, as for example: tyoe, model, color, ecc.

The JSON object can be even more complex, as for example this API:

format JSON e JavaScript

A JavaScript object is very similar to a JSON.

Let’s take an example of using JSON with JavaScript. So let’s take our usual auto object and write it as a JSON object, remembering that it’s a string.

Since it is a string we can use the simple superscript or the double superscript, without going to a new line. Or you can use the backtick (`) that is the back-to-back apex. To obtain the back-to-back apex, just hold down the ALT key and at the same time the numbers 0096 on the numeric keypad.

So let’s see a JSON object written using backticks:



var car = `{
  "type":"Fiat",
  "model":"500",
  "color":"white",
  "powerSupply":"gas",
  "year":"2010"   
}`;

and without:



var car = '{
   "type":"Fiat",
   "model":"500",
   "color":"bianco",
   "powerSupply":"gas",
   "year":"2010"
}';

Or alternatively, you can join the strings with the + operator, as shown in the example below:



var car = '{'
  + '"type":"Fiat",'
  + '"model":"500",'
  + '"color":"white",'
  + '"powerSupply":"gas",'
  + '"year":"2010"'+
'}';

If we try to do the console.log we will notice that what we have written is not an object but a string.



console.log(car);

In the next lesson we will see how to parse the following code in order to convert it into a JavaScript object.

For more information on the format JSON, you can consult the reference site: http://json.org/example.html.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

prompt JavaScript

prompt JavaScript

In this article we will talk about prompt in JavaScript, that is, windows that require a user to enter data.

The prompt () method therefore allows you to bring up windows to interact with the user.

prompt JavaScript – example 1

We want to make this example: when we click on the enter name button, the dialog box to enter the name will appear. After entering it and clicking ok, the greeting followed by the name just entered will appear in the level below.

Then try the example by clicking the button.

We then insert a button, anywhere on the page, which when clicked will bring up the dialog box for entering the name.

<button onclick=”myName()”>Insert the name</button>

In the div, which you can enter for example under button, I display the name that the user entered.

Let’s insert the JavaScript code now.

The JavaScript prompt () method has two arguments: the first that asks you to enter the name and the second that already appears in the field when the window opens (pre-filled value).

If the variable name is equal to the empty string then we display the message: ‘you have not entered the name’; otherwise we display the greeting followed by the name.

We are also using the getElementById () method which we will explore in the next articles.


function myName() {
   var messagge;
   var name = prompt("Insert your name:", "Coding Creativo");
   if (name == null || name == "")
      messagge = "You don't insert the name";
   else
     messagge = "Hi " + name;
   document.getElementById("view").innerHTML = messagge;
}

prompt JavaScript – example 2

Let’s take another simple example now, using the prompt () method. For example, we calculate the age of a person after requesting entry through the dialog box.

We insert the button anywhere on our page.

<button onclick="myAge()">Age Calculator</button>

Then we build our script, using the prompt () method to get the user's birth year to be entered.

We then get the date of the day with the Date () object and store it in the myData variable. Then we use the getFullYear () method to get the current year from the myData and store it in a variable named myYear.

So, to get the age we simply make a difference between the current year and the year the user entered.

Here is the complete script that uses JavaScript prompt:


function myAge() {
   var year = prompt("In what year were you born?", "1990");
   if (year !== null) {
         var myData = new Date();
         var myYear = myData.getFullYear();
         var age = (myYear - year);
         if (age < 18)
               alert("You are a minor, you have " + age + "years");
         else
             alert("You are of age, you have " + age + "years");
    }
}

Of course these are just simple examples of using the prompt () method in JavaScript.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

confirm JavaScript

confirm JavaScript

In this article we will talk about confirm in JavaScript, that is, how to create a window where the user can make a choice.

With the confirm () method, unlike the alert () method, communication is therefore not unilateral but bilateral.

confirm JavaScript – example 1

Let’s immediately take an example of use.

Try to enter some data in the fields below and then click on the Reset button. The window will appear that will tell you if you really want to reset the data.

Then, in any part of the web page, we insert the form with the labels, the text boxes and the reset button.

<form name="senda-data" onreset="return confirmation()">
  <label>Name</label>
  <input type="text" name="name">
  <label>Lastname</label>
  <input type="text" name="lastname">
  <input type="reset" value="Reset">
</form>

Note, in particular, that I have inserted the onreset event within the form tag.

After, as explained in the last lesson, we insert the following JavaScript code also in the same page for simplicity.

Inside the confirm method we then write if you want to reset the module.



function confirmation() {
  var reset = confirm("Do you want to reset the form?");
  return reset;
}

confirm JavaScript – example 2

Let’s take another very simple example of using the confirm () method, in which the window, after pressing the button, will display the choice we have made.

Try again to enter the data in the fields below and then press reset. The dialog box after pressing the button will tell you the choice you have made.

For the html we use the same form as before.

Ho modificato invece il codice JavaScript, per poter visualizzare, subito dopo, un alert che ci indica la scelta che abbiamo effettuato.

Usiamo un’istruzione condizionale, ovvero la funzione se … altrimenti, che controlla se il pulsante ok è stato premuto. Se è così useremo il metodo alert() per visualizzare che si è scelto di reimpostare i dati, altrimenti utilizzeremo sempre il metodo alert() per dire che si è scelto di premere annulla.

Ecco dunque l’esempio completo che utilizza JavaScript confirm:


function confirmation() {
  var reset = confirm("Do you want to reset the form?");
  if (reset === true){
       alert("You have chosen to reset your data!");
  }
  else {
      alert("You hit Cancel!");
  }
}

Conclusion

In order to develop this example, you can follow the lesson on conditional statements in JavaScript presented in this lesson: if else statement.

These are just simple examples of using the confirm method in JavaScript.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts