0

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(" ");
    console.log(ani[0]);

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

var str = "This is text 1";
    str.split(" ");
    console.log(str[0]);

It gives result as the first character of the string.

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

3
  • 1
    split does not modify the string being split. Commented Mar 13, 2018 at 21:50
  • The first return the modified text, the second return the first character in the character array Commented Mar 13, 2018 at 21:51
  • In the second case you are not assigning str.split(" "); to anything. You should save ti like let anyother = str.split(" "); Commented Mar 13, 2018 at 21:52

3 Answers 3

2

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.

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

1 Comment

split is not even just mutating, if so, it changes the type as well.
0

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]);

Comments

0

.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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.