Proprietà length di 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

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *