Home » JavaScript » Javascript String Length Example

About Era Balliu

Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.

Javascript String Length Example

When writing code that has to do with strings and you need to know it’s length, or even find out if your variable is an empty one, you can get this information by finding out how long exactly this string is. Here’s how:

String length

One of the most important built-in properties for string variables in Javascript (and also other programming languages) is length. Have a look at the code snippet below:

var ourString = "The string whose length we're going to find";


We have firstly declared a non empty string, and then we’ve put out an alert that shows us it’s length, by using the property .length on it.

If what we want to know whether we have an empty string or not, we run the same code, except instead of the string we have an empty one. It would look like this:

var ourString1 = "";


However we can’t use this property to find out if the variable has been set or not, as instead of the length, we’d have an undefined Javascript error.

To avoid this error we can first run a check using the typeOf method and then find the length if the variable turns out to be a string, or we can use another method. This one would be by only running the code if the unknown variable we have in our hands is a string and if it is of a certain length. the code would go like this:

var unknownVariable;

if ((typeof unknownVariable == "string") && (unknownVariable.length > 0)) {
//code here

This way you can use the length property whatever way you might need.

Download the source code

This was an example of string length in Javascript.

Download the source code for this tutorial:

You can download the full source code of this example here: StringLength

Do you want to know how to develop your skillset to become a Web Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. Building web apps with Node.js

2. HTML5 Programming Cookbook

3. CSS Programming Cookbook

4. AngularJS Programming Cookbook

5. jQuery Programming Cookbook

6. Bootstrap Programming Cookbook


and many more ....


I have read and agree to the terms & conditions


Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments