0

I understand that javascript's split() method should take a string and split it into an array based on the parameter(s) passed in the method.

I have run the following in the console:

var sen = 'I love javascript';
sen.split(' ');
console.log(typeof(sen));

So split(' ') should split the string based on whitespace and return an array with 3 strings.

However the console returns the typeof as "string" rather than "object"

Does anyone know why?

asked Jul 24, 2014 at 23:48
3
  • Read some documentation. What is the result of split? Commented Jul 24, 2014 at 23:50
  • I have read documentation, or I wouldn't ask here. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… I see that split should result in an array of strings. running typeof on an array should return object shouldn't it. Commented Jul 24, 2014 at 23:54
  • Keyword: returns (the assumption in the question is wrong) Commented Jul 24, 2014 at 23:56

1 Answer 1

3

Because split doesn't change sen. The returnvalue of

sen.split(' ');

would be an array. Try:

var sen = 'I love javascript';
var arr = sen.split(' ');
console.log(typeof(arr));
answered Jul 24, 2014 at 23:53
Sign up to request clarification or add additional context in comments.

3 Comments

so the problem was that I needed to store the result of sen.split(' ') in a variable. Got it!
@HelloWorld - it would be more correct to say that the split function doesn't modify the original value
@jasonscript && jhinzmann - If either of you have time would you mind explaining? I understand the split function is used to split a string into an array. Why does it not modify the original value (or the data type for that matter) unless it is stored in a new variable?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.