alert JavaScript

alert JavaScript

In this lesson we will talk about alert in JavaScript, i.e. window.alert(), used to communicate a message to the user.

Alert () is therefore a method of the window object, which serves to show an alert window. The window object is therefore the main JavaScript object and represents the entire browser window. This object also has many methods and properties that we will gradually see throughout this JavaScript tutorial.

We emphasize that using the JavaScript alert method, the dialogue is one-sided, that is, from the site to the user, we will see later other communications that are not.

alert JavaScript – first example

Let’s make an example of using this method right away.

Click a button to display a dialog box with a message.

So try clicking on the send button you see below:

A few lines of code are enough to create the example. First of all, our button where we insert the event when the message is clicked.

<div>
   <input name="invia" type="submit" onclick="messagge()">
</div>

N.B. For simplicity, we add the onclick () event to the button for sending data, where we call up our message function, then we will use other methods for managing the events.

Then we develop our very simple JavaScript function which we call message which will simply contain an alert with a message for the user.



function messagge() { 
     alert("stai per inviare i dati"); 
}

N.B. You can write window.alert () or even alert () indiscriminately.

alert JavaScript – second example

The alert () method can also be included in an element, i.e. in an html tag. Nowadays it is not a very common practice, but let’s study its functioning anyway.

So let’s take another example of using JavaScript alert in a tag.

Let’s say we want to display a dialog with a welcome message when we load our web page.

Just enter the onload event and a simple alert message in the body.

When we load the page, the dialog box will immediately appear, as shown in the figure:

avviso

alert JavaScript – third example

Let’s take yet another example of using alert in an html tag.

Let’s imagine that you have inserted images on our website and we want to inform the author that they are protected by copyright, when, for example, he clicks on them to save them.

Then just insert the onmouseup event with the related alert inside the img tag.

<figure>
   <img src="images/logo_coding_creativo.png" alt="coding creativo" onmouseup="alert('The images are protected by copyright')"> 
</figure>

alert JavaScript – fourth example

You can also place multiple alerts () one under the other.

So here’s an example that uses multiple JavaScript alerts:



function messaggio() { 
   alert("Welcome on Coding Creativo");
   alert("You learn to make coding funny");
}

In this way, the messages will appear one after the other.

Conclusion

In this lesson we have studied some examples of using JavaScript alert, in the next lesson we will deal with the confirm method.

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 functions

JavaScript functions

JavaScript functions are fundamental blocks of code, consisting of one or more instructions, which perform one or more actions.

A function in JavaScript is defined by the keyword function followed by the name of the function and by the arguments, however optional, enclosed in round brackets and separated by commas. The instructions are then placed between the curly brackets.

To call a function then simply indicate the name of the function and the arguments in parentheses, if any.

JavaScript functions – first example

Let’s first take an example by creating a simple welcome function that starts an alert with a welcome message.

So we don’t insert any parameters in round brackets.



function welcome(){
  alert('Welcome in coding creativo');
}

A function in this way is only defined, that is, it does nothing until it is called.

To recall it (invoke it), the name of the function followed by the round brackets is sufficient.

So here’s an example:



welcome();

JavaScript functions – return instruction

In the body of the functions there may be a return statement that is used to return a value or data.

Let’s take another example where we use parameters. We define a sum function with two placeholder values ​​a and b.

Inside the curly brackets we insert the calculation of the sum of the two numbers and return the result to the function.



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

So we invoke the sum function indicating the real values ​​in brackets and store the value it returns in a variable sumNumbers.

We then display the value obtained in the browser console.



var sumNumbers = somma(5,6);
console.log(sumNumbers);

In this lesson we have introduced functions in JavaScript, in the next lessons we will deepen the subject with other 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

JavaScript for loop

JavaScript for loop

In this lesson we will talk about JavaScript for loop and we do some usage examples to better understand how it works.

The for loop is an iterative structure that serves to repeat statements a certain number of times.

JavaScript for loop – syntax

The syntax of the for loop is as follows:



for(expression1; expression2; expression3){
   instructions;
}

Where:

  • expression1 is generally an initialization such as: i = 0.
  • expression2 is a condition, a test that returns a boolean value.
  • while expression3 usually represents an increase or decrease.
  • the instructions inside the curly brackets are executed only if expression2 gives a boolean value true. Otherwise the cycle will not run even once. Furthermore, if expression2 is always true then the instructions inside the curly brackets will be executed indefinitely. It is therefore said that the cycle is infinite.

JavaScript for loop – first example

Display the numbers 1 to 9 using the for loop.

First we start from the first expression which is an initialization. In our case we can use a variable i that starts from 0.

Then, the second expression is our test, that is in our case i <10 as the cycle will have to continue until we arrive at number 9.

The third expression is an increase, in our specific case it is the increase of variable i by 1.

Within the for loop we simply insert a print of the variable i.

Here is the complete code:


for(var i = 0; i < 10; i++){
     console.log(i);
}

The output produced by this very simple script are the numbers from 0 to 9.

JavaScript for loop - second example

Display even numbers from 0 to 100.

Even numbers are obtained simply by increasing the initial value 0 by 2, then the increase becomes: i + = 2.

We then always print our variable i.

So here is the easy solution to the proposed algorithm:


for(var i = 0; i <= 100; i += 2){
   console.log(i);
}

JavaScript for loop - third example

Display the odd numbers from 1 to 99.

The exercise is similar to the previous one, we just need to change the initialization of variable i.

Here is a possible solution:


for(var i = 1; i < 100; i += 2){
    console.log(i);
}

Conclusion

These are just some examples of exercises with the JavaScript for loop, in the next lessons I will propose many other 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

JavaScript variables and costants

JavaScript do while

JavaScript do while

In JavaScript the do while loop, as well as in other languages ​​where this construct exists, allows you to execute instructions at least once. If the condition is true then the cycle is repeated again, otherwise it goes to the next instruction.

The do-while loop is in fact a post-conditional construct.

JavaScript do while – syntax

The syntax of the do while is therefore this:



do {
   instructions;
} while (condition);

You can clearly have a single instruction to execute as well.

The semantics of the do-while construct are therefore this:

  1. The instruction (or more than one) is carried out;
  2. Then the condition is evaluated, which can be true or false.
  3. So if the condition is true you go back to point 1; otherwise you go to the next instruction.

JavaScript do while – example 1

As a first example I propose an exercise already developed with the while loop in the previous lesson.

We display the numbers from 0 to 9 in ascending order.

For this example we always initialize a counter variable: c = 0.

Then, with the do while loop, we print the first statement, increment c by 1 and only then evaluate the condition. If the condition is true then the cycle will start again by executing the same instructions.

Note that if I had mistakenly entered the condition c> 10, however, the instructions within the do-while would have been executed at least once.

Here is the complete code:


var c = 0;
do {
   document.write(c + '');
   c++;
} while (c < 10);

JavaScript do while - example 2

In this second example we will use the do while loop to check the input. This is in fact one of the major cases in which the do while loop is used.

Check that a number entered is positive and request it if not.

Inside the loop we insert the instruction that is used to take an input data. Only then do we check if this value is negative. If this condition is true the cycle will be repeated.

So here is the complete code.


do {
  var a = prompt("Insert a number:");
} while (a<0);        
document.write(a);

JavaScript do while - input control on two input data

In this third example on the do while loop in JavaScript we take two numbers as input and check if both are positive, otherwise we require them.

The resolution of the exercise is similar to the previous one, but attention must be paid to the condition. In fact, it is necessary to test whether a or b are less than zero. One can mistakenly lead to use the logical operator and (&&), but in this case the program does not repeat the loop if one of the two numbers is negative.

Try to reflect on this!

Here is the complete code:


do {
   var a = prompt("Insert number a:");
   var b = prompt("Insert number b:");
} while ((a<0) || (b<0));
	   
document.write(a + '');
document.write(b);

Conclusion

In this lesson we have introduced the do while loop in JavaScript, in the next lessons I will propose many other 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

JavaScript variables and costants

JavaScript while loop

JavaScript while loop

In this lesson we will talk about the JavaScript while loop and we will also do some very simple examples to understand how it works.

The while is a pre-conditional construct, that is, the condition check occurs before the execution of the instructions indicated in curly brackets.

The syntax of the while loop is as follows:

while (condition) {
   istructions;
}

Where condition represents a Boolean value, that is, a true or false value. The condition determines the length of the cycle that will then run as long as the condition is true.

So as long as the condition is true, the instructions indicated in braces will be executed.

So be careful to set the condition correctly.

The cycle will be infinite if the condition is always true.

While the cycle will never run if the condition is false from the start.

JavaScript while loop – first exercise

Display the numbers 0 to 9 in ascending order.

First we initialize a counter variable to 0 to start from: c = 0.

Then we set the condition in the while, in this case c <10.

Then inside the curly brackets we insert our instructions: we write the variable c and then we increment it by 1.

You will then have these steps:

c = 0

step 1:

the condition: 0 <10 is true:

print 0

increases c by 1: c = 1

step 2:

the condition: 1 <10 is true:

print 1

increases c by 1: c = 2

it is so on until c = 9

So here is the complete code of the while loop in JavaScript.


var c = 0;
while (c < 10){
   document.write(c + '');
   c++;
}

JavaScript while loop - second exercise

Display even numbers from 0 to 100.

To carry out this simple exercise, just change the previous algorithm by increasing c by 2 instead of 1.

We change the condition to also include 100: c <= 100.

We also remember that 0 is an even number.

Here is the complete code:



var c = 0;
while (c <= 100){
   document.write(c + '');
   c += 2;
}

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 variables and costants

length of string JavaScript

length of string JavaScript

The length of a string in JavaScript is calculated with the length property, that count the amount of characters in that string.

The syntax is therefore the following: string.length, where string represents the string whose length is to be calculated.

length of string JavaScript – example

In this first example we will get the number of characters of any string taken as input.

So here is a possible example to calculate the length of a string:



var sentence = 'do coding creativo';
var sentenceString = sentence.length;
console.log(sentenceString );

In this case, in the browser console we will display the numerical value 20, which corresponds to the number of characters in the sentence.

length of string JavaScript – second example

Determine the length of a string, if it is empty, fill it with the creative coding value, otherwise print the result on the screen.

Suppose we start from an empty string:



var sentence = ' ';

Next, using JavaScript’s length property on strings, we calculate the length of the string and store this data in a variable:



var lengthSentence = sentence.length;

Since the string is empty, the value 0 will be stored in the variable lengthString.

Then, using the conditional statements, we check if the string is not empty and therefore if the length is different from 0 or not. If it is true we display the length of the string, otherwise we set the starting string equal to the example sentence: ‘creative coding’.

Here is a possible implementation:



if (lengthSentence != 0) {
   console.log(lengthSentence );
} else {
   sentence = 'coding creativo';
}

Conclusion

In this lesson we studied how calculate the length of string in JavaScript the JavaScript, similarly the following property can also be used on arrays. You can find the simple example tutorial at the following link: length properties on arrays.

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 variables and costants