JavaScript >> Web Applications
string length in javascript
As with any other programming language, string length is also required in javascript. Though the primary purpose of string length in a javascript is to use in for loop control or if but it can be used to initialize other variables.
If you are using string length for checking if the string is empty or not then you should be aware of the fact that there are other multiple ways to check for empty strings in Javascript.
<script> var str="abc"; alert(str.length); </script>
The above code will result in an alert box with output as 3.
Similarly to check if a string is empty or not then use the following code example:
<script>
var str1="abc";
var str2="";
if(str1){alert('string str not empty');}
if(str2){alert('string str empty');}
</script>
As we can see that the string variables when used in if condition automatically acts as a boolean variable to tell if the string variable is empty or not. But the above code could break if the string used in the if condition has a value of “0″.


