0

Javascript array lengh giving 1 if null.I am using Split function.

var str = '';
var arr = str.split(',');
alert(arr.length);
**Output:1**

When there is any value in string counting correctly

  var str = 'a,b,c';
  var arr = str.split(',');
  alert(arr.length);
  ****Output:3****
2
  • You can wrap it into an if statement: var str = ''; if (str) { var arr = str.split(','); } else { var arr = []; } alert(arr.length); This way you will have an evaluation of your string and since empty string evaluates to falsy in JS, you will run the else statement when the string is empty returning an empty array. Commented Feb 10, 2017 at 1:15
  • Better duplicate: stackoverflow.com/questions/33516370/… Other one was for Scala. Not sure how that happened. Commented Feb 10, 2017 at 2:04

2 Answers 2

1

An empty string isn't a null value. And String.prototype.split splits a string into array indexes when it finds the separator character. In your empty string, there's a single string. Therefore, you get an array length of 1.

Sign up to request clarification or add additional context in comments.

3 Comments

ok.then how i can calculate string length in array?
@Raju Elaborate more on this please, I don't understand your question at all...
@Raju Do you mean this? var totalLength = array.reduce(function(result, str) { result += str.length; return result; }, 0);
1

when you do var arr = str.split(','); the returned array is not null. It has one element and that value has space in it. So when you do arr.length - it will return 1 as it has one element and that element is space " ".

Hope it helps. Happy Learning :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.