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

JavaScript charCodeAt

JavaScript charCodeAt

JavaScript charCodeAt method, to be used on strings, takes an index as an optional parameter. This method returns the Unicode character of the corresponding character specified by the index.

So the syntax is as follows: string.charCodeAt(index).

If the index is not specified, it will have a default value of 0.

Recall that Unicode is an encoding that assigns a unique number to each alphanumeric character. This encoding is independent of the language used.

For more information, see the following link: unicode encoding.

JavaScript charCodeAt

In this first example we will get the Unicode of the first character of a string.

So here’s a possible implementation of the JavaScript charCodeAt method:



var sentence = 'do coding creativo';
var character = sentence.charCodeAt(0);
console.log(character);

So, in the browser console, we get the value 102, which is the corresponding Unicode character of the letter f.

Using the JavaScript charCodeAt method in the last character of a string

In this example we get the Unicode encoding of the last character of a string taken as input.

To do this, it is necessary to use the length property on the string which, remember, returns the number of characters of a given string.

Here is the complete example:



var sentence = 'do coding creativo';
var character = sentence.charCodeAt(sentence.length-1);
console.log(character);

In this case, the value 101 is obtained, which corresponds to the Unicode encoding of the letter o.

If we try to obtain the Unicode encoding of an index that does not exist then we will have the value NaN (Not a Number).

Conclusion

In this lesson we have seen some practical examples on using the JavaScript charCodeAt method, in the next lessons we will see many other examples with other methods on strings and 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

JavaScript charAt

JavaScript charAt

The JavaScript charAt method used on strings returns one character from a string. The position of the character is indicated in the index between round brackets.

So for example charAt (0) returns the first character, while charAt (1) returns the second and so on.

The syntax is therefore the following: string.charAt(index)

Therefore the method accepts a mandatory parameter, index, which represents the position of the character to search for in a string.

JavaScript charAt – examples

In this first example we will search for the first character of a string in a simple sentence.

Here is a possible implementation:



var sentence = 'do coding creativo';
var character = sentence.charAt(0);
console.log(character);

In this case, the result is the letter f (the first letter of the sentence).

If, on the other hand, we look for a position in the sentence that does not exist, we will not get any value, as in the example below:



var sentence = 'do coding creativo';
var character = sentence.charAt(200);
console.log(character);

Last character of a string using the JavaScript charAt method

If we want to determine the last character of a string, then we can use the length property on the string. In fact, remember that str.length returns the amount of characters in a string, so to get the last character, since the index starts from 0, we must subtract 1.

Here is the complete example:



var sentence = 'do coding creativo';
var character = sentence.charAt(sentence.length-1);
console.log(character);

Capitalize the first character with the JavaScript charAt and uppercase method

In this exercise we extract the first character, convert it to uppercase with the toUpperCase method and then concatenate everything else using the substr method.

Here is the complete example:



var sentence = 'do coding creativo';
var sentenceUpper = sentence.charAt(0).toUpperCase() + sentence.substr(1);
console.log(sentenceUpper);

In this short lesson we have implemented some very simple exercises using the JavaScript charAt method, continuing in the tutorial you will find many other application 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