Split function in Javascript and assigning it to variable gives different result

I am new to javaScript and is not able to understand why split function is behaving differently just by assigning it to a variable.

For example,

var str = "This is text 1";
    var ani = str.split(" ");

The above code gives the whole word "this" , whereas for the below code

var str = "This is text 1";
    str.split(" ");

It gives result as the first character of the string.

Why didn't the later code result was same to the first one?

3 answers

  • answered 2018-03-13 21:51 sklingler93

    String functions in javascript don't modify the string in place. So setting the result of str.split(" ") to a variable works, but the value of str is not changed.

  • answered 2018-03-13 21:52 Barmar

    str.split(" ") does not modify the str variable, it returns a new array containing the result. str still contains the original string, and str[0] is the first character of that string.

    If you want to do it without assigning to a variable, apply the subscript to the function call:

    console.log(str.split(" ")[0]);

  • answered 2018-03-13 21:52 theleebriggs

    .split() doesn't mutate / affect the variable it is called on, it instead returns a new value - which you have assigned to ani. The confusing thing for the example you have is that strings can be accessed like arrays. So str[index] will give the character at that position.