3

I try to chain some array and string methods but it doesn't work. It'd be great if anyone could explain to me why a function such as this doesn't work:

const scream = text => text.split('').push('!').join('').toUpperCase()
4
  • 1
    Check out the docs on push (it does not return the array you pushed to, which should be clear if you look at the error that gets thrown) Commented Oct 31, 2018 at 9:30
  • push() "returns the new length of the array" - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Oct 31, 2018 at 9:34
  • what is sample text and what is expected Commented Oct 31, 2018 at 9:35
  • 2
    This looks a complicated version of (text + '!').toUpperCase() Commented Oct 31, 2018 at 9:38

4 Answers 4

6

You could use Array#concat to return an array with another value instead of Array#push, which returns the new length, but is not part of a fluent interface for a later joining (which needs an array).

const scream = text => text.split('').concat('!').join('').toUpperCase();

console.log(scream('hi'));

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

Comments

3

Push doesn't return the array. Here's an example that demonstrates what's happening with push, and shows another way to do it:

const scream = text => text.split('').push('!').join('').toUpperCase()

const test = ['a', 'b', 'c'];
const result = test.push('!')

console.log(result)

const newScream = text => [
  ...text,
  '!'
].join('').toUpperCase()

newScream('hello')

console.log(newScream('hello'))

Comments

3

If you want to add 1 ! at the end:

const scream = text => text.split('').concat('!').join('').toUpperCase();

If you want to add it after each letter:

const scream = text => text.split('').map(e => e + '!').join('').toUpperCase();

The push don't return array, so join is not called on array in your case.

Comments

1

If you want to add character/string at the end of string use concat(<ch>) function. If you want to change case to upper then use toUpperCase() function.

Or

Simply you can use + operator to concat two strings and append ! to it.

var str = "Hello World";
    var res = str.toUpperCase().concat("!");
    var result = (str + '!').toUpperCase();
    console.log(res);
    console.log(result);

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.