Cerdarius
Cerdarius

Reputation: 81

Chaining array and string methods in javascript

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()

Upvotes: 3

Views: 4212

Answers (4)

Eugene Mihaylin
Eugene Mihaylin

Reputation: 1776

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.

Upvotes: 3

Prasad Telkikar
Prasad Telkikar

Reputation: 16079

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

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386730

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

Upvotes: 6

OliverRadini
OliverRadini

Reputation: 6466

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'))

Upvotes: 3

Related Questions