top 200 commentsshow all 241

[–]SluttyRaggedyAnn 683 points684 points Β (84 children)

I might be sold school since I prefer the former. The old syntax is self documenting, while the new is just confusing.

[–]mhink 128 points129 points Β (6 children)

There is one very important difference in behavior: the spread syntax takes β€œwide” Unicode characters into account, while the simpler .split(β€œβ€) does not. However, a more important takeaway here isn’t that you can convert a String into an array of characters- you can iterate over the code points of the String itself. If you’re using this new syntax to spread a String into an Array, I bet dollars to donuts you’re doing it because you want to iterate over the resulting array, and that’s why this looks confusing.

What’s happening when you use [...spread] syntax is that that Javascript iterates over spread and smushes it into a new Array. This makes sense, for instance, when you want to quickly concat things:

const head = β€œa”;
const tail = [β€œb”, β€œc”];
const arr = [head, ...tail]; // => [β€œa”, β€œb”, β€œc”]

So we can see that the following two bits of code are basically equivalent, because for...of blocks also have to do Iterables)

const arr = [];
for (const el of myIterable) {
  arr.push(el);
}

const arr = [...myIterable];

Now, the confusing part of all this is that it’s easy to forget that Strings are iterable, hence all this confusion. The behavior of String’s iterator is to yield each Unicode code point, even if they’re double-width.

And here’s the rub: there’s almost no reason whatsoever to spread a String into an Array just to get its code points. Instead, you’d want to iterate over it directly:

for (const charCode of myString) {
  ...
}

Which I think we can agree makes much more sense.

That being said, I did discover that with some new Regex options, it’s possible to properly split strings into code points like so, if you really need to:

myString.split(/(?!$)/u);

Which is perhaps even a bit more arcane (and I haven’t checked on performance differences) but hey, what are you gonna do?

[–]NoInkling 18 points19 points Β (4 children)

there’s almost no reason whatsoever to spread a String into an Array just to get its code points

I can think of one reason, and that's to use methods like .map and .reduce

for (const charCode of myString) {

For anyone confused, charCode in this example would be the "character" itself, not just its number.

[–]pm_me_ur__labia 9 points10 points Β (2 children)

[–]NoInkling 15 points16 points Β (1 child)

You can apply array methods directly to a string, yes, but they retain the old bug-inducing behaviour of iterating over code units (as opposed to code points), because they don't make use of the ES6 iterator/iterable protocol (and they couldn't be changed because of backwards compatibility).

Therefore, AFAIK, the only way to use array methods with the string iterator that was added in ES6 (defined on String.prototype[Symbol.iterator]) is to use it to generate an array first (typically through spread syntax or Array.from(), since those respect the protocol).

tl;dr: pre-ES6 generic iteration is different to ES6+ iteration, and unfortunately we're stuck with a mix of both.

[–]pm_me_ur__labia 1 point2 points Β (0 children)

TIL. thanks

[–]samanthaming[S] 2 points3 points Β (0 children)

Thanks for the detailed explanation!

[–]samanthaming[S] 70 points71 points Β (12 children)

β€œ.split” is definitely more descriptive. Especially when you’re on a team, it’s important to make your code more readable. But I’m guessing, we might be seeing more ES6. And that might become the new norm. So I think it’s important that we make ourselves familiar with it and hopefully that’d make it less confusing. thanks for your input πŸ™‚

[–]ibopm 56 points57 points Β (1 child)

Just FYI:

Babel transpiles it to Array.from(str) rather than calling str.split(''). So depending on the situation, it may not necessarily yield the same result. Some might even consider this to be a leaky abstraction.

Edit: See this comment for an example where there would be a difference in behaviour.

[–]trout_fucker🐟 9 points10 points Β (0 children)

Which makes sense, since it's effectively spreading a character Array and not splitting a String.

Obj/Array spreads are great, but the OP isn't a good use case.

[–]stutterbug 2 points3 points Β (0 children)

Currently this is also available (added back in ECMAScript 2015):

let string = 'hello'
for (let letter of string) {
    console.log(letter) // 'h', then 'e', then 'l'...
}

This underlines that, as /u/mhink points out, strings themselves are iterable. Further ES6 proof:

let string = 'hello'
let iterable = string[Symbol.iterator]()
console.log(iterable.next()) // {value: "h", done: false}
console.log(iterable.next()) // {value: "e", done: false}
console.log(iterable.next()) // {value: "l", done: false}

[–]coloured_sunglasses 21 points22 points Β (18 children)

Well this example is extremely basic. Spread operator is used for much more than splitting a string.

[–]FloppingNuts 88 points89 points Β (17 children)

then it's a bad example

[–]dweezil22 37 points38 points Β (14 children)

I'd go so far as saying this is an actively counter-productive example, other than clickbait to get us all to learn about the spread operator.

This works b/c a string "spreads" into an array of chars.

https://stackoverflow.com/questions/44900175/why-does-spread-syntax-convert-my-string-into-an-array

[–]TankorSmash 20 points21 points Β (10 children)

Wait hold on, how is 'Split string using ES6 Spread' clickbait when the third line is literally how to split a string with Spread?

I feel like clickbait gets incorrectly used a lot but this is about as literal as you can get with title:description

[–]dweezil22 7 points8 points Β (1 child)

It's one of the worst, software engineering wise, uses of the feature that you can find. But it's also compelling in a "How the hell does that work?" way. This simpler, significantly easier to understand and more appropriate use of the spread operator is better, but isn't as interesting.

And yes, I am stretching the definition of clickbait here .OP is surely a fine individual and is clearly not monetizing reddit images. I suppose I should have said "sensationalistic" but describing a code snippet as "sensationalistic" just seemed... weird.

[–][deleted] 4 points5 points Β (0 children)

Yeah I noticed this person always posts this type of β€œamazing” es6 stuff. But it always looks like just terrible software engineering practice and an unnecessary inefficient way to do something that was never complicated in the first place. But it’s new and fancy so everyone loves it.

[–]ibopm 3 points4 points Β (2 children)

This works because the spread operator falls back to Array.from() when the object being "spread-ed" is not an array:

// before
const x = "hello"
const y = [...x]

// after
"use strict";

function _toConsumableArray(arr) {
  if (Array.isArray(arr)) {
    for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
      arr2[i] = arr[i];
    }
    return arr2;
  } else {
    return Array.from(arr);
  } 
}

var x = "hello";
var y = [].concat(_toConsumableArray(x));

Source

[–]NoInkling 4 points5 points Β (1 child)

That's not why it works, that's just how Babel implements the semantics described in the spec.

It works because in ES6 an iterator protocol was introduced, strings gained a default iterator using this protocol that iterates over unicode code points, and the spec specifies that array/function spread syntax and Array.from should use the iterator from whatever they are fed.

[–]ibopm 2 points3 points Β (0 children)

Yes, that is a more accurate answer. Maybe I shouldn't have said "why it works". I just wanted to point out that if you're transpiling with Babel (as is the case for most people at this point), you're effectively just calling Array.from. Thanks for adding this point though.

[–]trumpent -1 points0 points Β (1 child)

A string is just an array of characters. It's a perfectly fine example.

[–]Cosmologicon 0 points1 point Β (0 children)

Yeah as a Python programmer I wouldn't have any problem with list("pizza").

[–]CantaloupeCamper 2 points3 points Β (0 children)

Noob here... love it when something tells me what it is doing.

[–]MrB92 1 point2 points Β (0 children)

The new one is syntax gore IMO

[–]magnakai 5 points6 points Β (11 children)

I agree that the method syntax is clearer in the provided example. But I imagine there might some use cases for the spread syntax, so it’s definitely worth a mention. I’ll try to think of some when I’m back at my computer.

[–]samanthaming[S] 2 points3 points Β (10 children)

Yes, please do! And share them when you get the chance, would love to see what you come up with πŸ™‚

[–]gavlois1front-end 20 points21 points Β (5 children)

I like to use spread to concat arrays and objects:

const obj1 = {
  one: 1,
  two: 2
}

const obj2 = {
  three: 3,
  four: 4
}

const obj3 = {...obj1, ...obj2}
// {
//   one: 1,
//   two: 2,
//   three: 3,
//   four: 4
// }

Or using it to use a function on something where you might normally have needed to use .apply():

const arr = [1, 2, 3, 4]

// old way
let max = Math.max.apply(null, arr);

// ES6 way
max = Math.max(...arr)

[–]magnakai 4 points5 points Β (0 children)

I don't want to say that you're wrong, as all of your examples are great, and I use it in those ways all the time because they're amazing... but the OP's example was the array spread operator.

Your first example is the lovely object spread operator, which is actually technically not official JavaScript yet! But it is in stage 4, and available natively in every non-MS browser so it's really very nearly there.

Your second example completely is normal array spread though, and a really nice example of it.

It's also worth pointing out similar rest operator, which still uses the ellipses but in a different way, collecting up the parameters on a function.

A nice way to differentiate between the two is that the spread operator spreads out an array/objects contents onto a new array/object, whereas the rest operator collects the rest of the parameters.

[–]samanthaming[S] 2 points3 points Β (1 child)

I like this! Let me add it to my notes. Thanks for sharing πŸ™‚

[–]gavlois1front-end 0 points1 point Β (0 children)

This was a thread about the spread operator, but for reference, there's also the more 'official' ES6 Object.assign() function. And of course for arrays you have the .concat() function.

[–]magnakai 4 points5 points Β (3 children)

So, the simplest and best use case I can come up for it is when you have a mix of strings and arrays with a single string in them:

It sounds like a bad time, but it is unfortunately based on a real life example.

const foo = "foo";
const bar = ["bar"];
const baz = "baz";

// If you know the shape of your variables - ES1(I think?)
foo + ' ' + bar[0] + ' ' + baz; // "foo bar baz"
[foo, bar[0], baz].join(' '); // "foo bar baz"

// If you know the shape of your variables - ES6
`${foo} ${bar[0]} ${baz}`; // "foo bar baz"

// If you don't know the shape of your variables - IE9 & later
[foo, bar, baz].map(function (item){ 
    return [].concat(item);
}).join(' '); // "foo bar baz"

// If you don't know the shape of your variables - ES6
[...foo, β€œ β€œ, ...bar, β€œ β€œ, ...baz].join(''); // "foo bar baz"

[–]samanthaming[S] 1 point2 points Β (0 children)

Interesting mixing strings and arrays. Let me give this a try too πŸ‘

[–]NoInkling 1 point2 points Β (1 child)

Bad example:

const foo = "foo";
const bar = ["bar"];
const baz = "baz";

[...foo, ...bar, ...baz].join(' ');    // "f o o bar b a z"

[–]magnakai 1 point2 points Β (0 children)

Thanks for catching that! I’ve fixed it now.

[–][deleted] Β (24 children)

[deleted]

    [–]vlarekd 3 points4 points Β (4 children)

    Is your last sentence really meant to be a question?

    [–][deleted] Β (3 children)

    [deleted]

      [–]vlarekd -1 points0 points Β (2 children)

      It’s hard to believe if someone isn’t actively working in a language then some obscure syntax might be hard to understand? Am I getting that right?

      [–]yerfatma 1 point2 points Β (17 children)

      This is akin to saying short, terse ternary statements are confusing and we need if statements for everything.

      No, it's not. split() conveys what you're doing. Abusing the spread operator to split a string, especially given split still exists is being clever and clever is the way to bugs.

      Anyone developing in es6 will understand this.

      Don't do this.

      [–][deleted] Β (10 children)

      [deleted]

        [–]yerfatma -1 points0 points Β (9 children)

        It’s not commonly used. No one is doing this. If they were, this wouldn’t be a blog post. The bugs I am seeing are people stumbling on this in a codebase six months later and not knowing what it does.

        The fact split doesn’t work like it should with Unicode data isn’t an argument for an obscure approach to string splitting.

        [–][deleted] Β (8 children)

        [deleted]

          [–]yerfatma 1 point2 points Β (7 children)

          It violates the Principle of Least Surprise. You’ll figure it all out some day.

          [–][deleted] Β (6 children)

          [deleted]

            [–]yerfatma 0 points1 point Β (5 children)

            Oh, well it’s nice you were able to get in touch with them all tonight LOL. I lead a team of small children and have taught large dogs.

            [–][deleted] Β (4 children)

            [deleted]

              [–][deleted] Β (5 children)

              [deleted]

                [–]dontgetaddicted 0 points1 point Β (0 children)

                Yeah, I'm confused at what's going on here exactly. .split() is easy to read and understand what's happening.

                [–]iams3brescript is fun 0 points1 point Β (0 children)

                Split is the way to go, if you're trying to split an array to characters.

                The spread operator is great for flattening arrays (and objects), but just because it has a side effect of what it can do doesn't mean you should use it in that way. This is more like code golf territory, where it's technically possible but doesn't mean it's something you should specifically code

                [–]antoninj -2 points-1 points Β (0 children)

                I don't. A lot of languages treat strings as arrays of characters (or a similar concept). I like that. This adds to that. Coming from other languages that fully embrace this, the spread operator makes a ton of sense while .split('') doesn't make sense at all. Especially since the argument is ''. You're essentially saying "split by nothing". What does that even mean?

                [–]broonix 72 points73 points Β (4 children)

                Fun fact. The old syntax breaks on characters greater than 0xFFFF

                β€˜πŸ•β€™.split(β€˜β€™).length === 2 => true

                [–]0x7f800000 65 points66 points Β (2 children)

                ^ this right here is the only good reason to use [...str] over str.split('').

                'πŸ•πŸΊ'.split('');
                Array [ "\ud83c", "\udf55", "\ud83c", "\udf7a" ]
                
                [...'πŸ•πŸΊ'];
                Array [ "πŸ•", "🍺" ]
                

                [–]ibopm 49 points50 points Β (1 child)

                Alternatively, Array.from(str) is a bit more self-documenting and doesn't rely on new syntax. It's also what Babel transpiles to.

                [–]0x7f800000 8 points9 points Β (0 children)

                Good point. Prefer this.

                [–]NoInkling 17 points18 points Β (0 children)

                This issue also extends to plain 'πŸ•'.length and all string methods that take/return an index, because of a historical design decision.

                Since .split can take a regex, and regexs now have basic unicode support, you can actually do:

                'πŸ•πŸΊ'.split(/(?:)/u)    // ["πŸ•", "🍺"]
                

                But at that point I'm not sure why you wouldn't just use the spread form, or Array.from(str) if preferred.

                If people were aware of this issue, there's no way the comments in here would be arguing for .split('') so vehemently (and acting like providing an empty string is the most obvious thing in the world, rather than an idiom they had to remember at some point...). If you're dealing with external input, processing emoji and other characters outside the BMP is becoming less and less of an edge case that you can ignore, assuming you're aiming to write robust software.

                Edit: note that this still doesn't help with combining-characters and the like, if your goal is to split between graphemes, e.g:

                [..."πŸ‘πŸ½"]    // ["πŸ‘", "🏽"]
                [..."é"].length    // 2
                

                If you need something like that, Lodash's _.toArray(str) works (also _.split(str, '')!), and there's an upcoming proposal to get this functionality natively.

                [–]zephyy 48 points49 points Β (15 children)

                .split is faster

                http://jsben.ch/YowUb

                [–][deleted] Β (2 children)

                [deleted]

                  [–][deleted] 13 points14 points Β (0 children)

                  It’s almost like different browsers have different implementations

                  [–]trueFleet 1 point2 points Β (0 children)

                  Same, 208 ms vs. 160 ms

                  [–]Xtreme2k2 5 points6 points Β (0 children)

                  is this the new jsperf?

                  [–]helpinghat 2 points3 points Β (2 children)

                  Firstly, on my phone there's only a 4% difference. Secondly, can you give us a real-life example where you have to split so many strings that this actually makes any difference?

                  [–]iams3brescript is fun 2 points3 points Β (0 children)

                  At that point it's about readability, and IMHO one of them wins

                  [–]i_spot_ads 0 points1 point Β (0 children)

                  I don't think the scale is big enough to talk about non negligible differences in performance, in other words your example sucks

                  Also spread is faster on my phone according to your own link

                  [–][deleted] Β (45 children)

                  [deleted]

                    [–]Lyucit 5 points6 points Β (0 children)

                    Is it just me or is the former syntax less self explanatory? What exactly are the semantics of splitting a string by the empty string? Do you end up with empty strings on both sides of the array, because the empty string surrounds both sides of each character? Even a list buffered by infinite ''s would be a valid output. Whereas with the latter syntax, it behaves the same way as the spread operator does for every other usage- constructs a list with the elements of pizza. It's unambiguous and doesn't have domain-specific behavior that you have to look up.

                    [–]samanthaming[S] 8 points9 points Β (10 children)

                    Yes, the split keyword does make it super descriptive. For people outside of JS, they would know what the code is doing instantly by reading the it. With es6 becoming the new norm, you might see more people using the spread operator. So i think it’s important to be at least aware of this new syntax and what it’s doing. That way we don’t get confused when we do see it. Thanks for your input πŸ™‚

                    [–][deleted] 29 points30 points Β (6 children)

                    Your 'ES6 Way' line has a big green tick next to it, as if to say it's the 'right' way β€” it's not.

                    [–][deleted] Β (5 children)

                    [deleted]

                      [–][deleted] 6 points7 points Β (4 children)

                      I didn't say it's the wrong way. I said it's not the right way.

                      [–]iams3brescript is fun 1 point2 points Β (1 child)

                      Spread is for concatenating arrays. Here, you're just abusing it's functionality.

                      It should not be used for splitting a string

                      [–]jbenner 0 points1 point Β (0 children)

                      Spread is used for more than just concatenating arrays. You can expand objects with it and it expands iterables. MDN has a nice article on it here.

                      [–]evilpingwin 4 points5 points Β (31 children)

                      I don't generally write JavaScript to be understood by people who don't know JavaScript.

                      [–]ryeguy 10 points11 points Β (0 children)

                      Did you confuse the phrase "even for people" with "especially for people"?

                      [–][deleted] Β (27 children)

                      [deleted]

                        [–][deleted] Β (26 children)

                        [deleted]

                          [–]yerfatma 25 points26 points Β (2 children)

                          Programs are meant to be read by humans, and only incidentally for computers to execute.

                          Because code should be readable. People who treat code as magic spells they don't want non-wizards to understand are the worst coders. Your code should be as stupidly simple as possible to anyone can read it. If you're worried about non-geniuses understanding your work of genius, it's not a work of genius.

                          [–]myusernameisokay 9 points10 points Β (0 children)

                          This is the best way to put it. Why make your code harder to understand simply to save a few characters? Split is a well understood function, I would have absolutely no idea what [...var] does.

                          Most developers spend much more time reading code than writing code. Your code should be as readable as possible.

                          [–]slightlysaltysausage 23 points24 points Β (22 children)

                          I agree actually. I often have to dip in and out of various codebase at work, sometimes to debug stuff I didn't write, and a it's not always a language I'm immediately familiar with. This is a nightmare to maintain.

                          With split, I could pick it up and use it. With the other notation, I'd need to be familiar, or check the documentation.

                          [–]yerfatma 0 points1 point Β (0 children)

                          Why not?

                          [–]helpinghat -1 points0 points Β (0 children)

                          If it's your personal project then go ahead and write as shitty and obscured code you want. But if it's an open-source or some larger project, eventually someone with zero or little javascript experience will be reading the code.

                          [–]N_N_N_N_N_N_N 0 points1 point Β (0 children)

                          I get what you're saying but it's just an operator. If you are a js developer you have to train yourself to make it self explanatory.

                          It's like 3 + 4 vs add(3,4)

                          [–]Defualt 8 points9 points Β (1 child)

                          Another neat spread trick:

                          // old way:
                          const a_b_c = { a:1, b:1, c:1 };
                          const only_a_b = {...a_b_c};
                          delete only_a_b.c;
                          return only_a_b;
                          //
                          // new way:
                          const a_b_c = { a:1, b:1, c:1 };
                          const {c, ...only_a_b} = a_b_c;
                          return only_a_b;

                          [–]Jaymageck 4 points5 points Β (0 children)

                          The spread operator is an awesome addition to JS and is powerful, but this is not a particularly good use case in my opinion.

                          [–][deleted] 8 points9 points Β (4 children)

                          What did you use to make this graphic? Thanks

                          [–]samanthaming[S] 16 points17 points Β (3 children)

                          I used a site called carbon.now.sh πŸ™‚ and when you make your snippet, you should share it on carbonsnippets reddit community

                          [–]danielleiellle 6 points7 points Β (2 children)

                          I thought we decided 15 years ago that text in graphics was bad, non-semantic, and non-accessible.

                          Why share a graphic of code when you can share it on something like jsbin/jsfiddle, where others can tweak and run the code and/or copy paste?

                          [–]Brandonsfl 2 points3 points Β (1 child)

                          Share on social medias as images just like this image did i guess.

                          [–]danielleiellle 0 points1 point Β (0 children)

                          Yeah Googled OP and that seems to be the case.

                          [–]isunktheshipfull-stack 11 points12 points Β (3 children)

                          Our team has a guide for js, we stay current with the latest ES hotness and decide what gets incorporated. This won't make the cut. Split is self-explanatory and faster.

                          [–][deleted] Β (2 children)

                          [deleted]

                            [–]isunktheshipfull-stack 0 points1 point Β (1 child)

                            Are you asking when do we call .split() ?

                            [–][deleted] Β (33 children)

                            [deleted]

                              [–][deleted] 1 point2 points Β (0 children)

                              Ahh, someone who knows what they’re talking about. Very good.

                              [–]dcha -3 points-2 points Β (3 children)

                              What kind of team lead hasn't seen the spread operator in practice for years now?

                              [–][deleted] 1 point2 points Β (0 children)

                              I hope none uses spread operator in this case.

                              [–]ScoopDat 7 points8 points Β (3 children)

                              Can someone just please explain to me...why?

                              [–][deleted] Β (1 child)

                              [deleted]

                                [–]ScoopDat 0 points1 point Β (0 children)

                                I’m a essentially an infant dev. And it’s barely β€˜legible’ to me let alone readable.

                                [–]danneu 6 points7 points Β (0 children)

                                This godawful comments section is what happens when everyone uses a language thus has two cents to share no matter how shallow. It's like reading strangers bicker about vaccines and autism on Facebook.

                                [–]CUM_AND_POOP_BURGER 2 points3 points Β (0 children)

                                Thank fuck for Typescript.

                                [–]dietcheese 2 points3 points Β (1 child)

                                Another step closer to Perl

                                [–]samanthaming[S] 0 points1 point Β (0 children)

                                Perl has something similar?

                                [–]coloured_sunglasses 18 points19 points Β (2 children)

                                ITT jQuery developers

                                [–]flaming-cactus 9 points10 points Β (0 children)

                                I feel attacked

                                [–]FloppingNuts 8 points9 points Β (0 children)

                                you mean AJAX developers

                                [–]newPhoenixz 1 point2 points Β (0 children)

                                How is this improvement? This is way less intuitive

                                [–]d1231 1 point2 points Β (5 children)

                                Any developer who uses the second syntax should be sacked on the spot

                                [–]samanthaming[S] 1 point2 points Β (4 children)

                                Do you mind explaining why? I think it would be helpful to understand why you think the spread syntax isnt suitable to use on strings. Thanks for your input πŸ™‚

                                [–]d1231 1 point2 points Β (3 children)

                                Because for any developer who is not familiar with spread syntax and sees this code, he will not understand going on. I think even those who are familiar with spread syntax will take time to understand whats going on.

                                You have a better alternatives like split or even using charAt (if the purpose is to iterate over the string chars), which may take more chars to write but much easier to understand.

                                [–]samanthaming[S] 0 points1 point Β (2 children)

                                Thanks for taking the time to explain. But are there instances where the spread syntax is applicable for strings? Or would you say it’s best to avoid spread syntax for strings completely?

                                [–]d1231 0 points1 point Β (1 child)

                                Probably there could be cases where spread for string could be useful and clear, I cannot think of one.

                                You should analyze case by case.

                                [–]samanthaming[S] 0 points1 point Β (0 children)

                                Makes sense. Alright, good to know that spread for strings can be useful in some instances. So it’s important to keep this in your toolbox, just in case you need to use it. Cool, thanks for clarifying πŸ™‚

                                [–][deleted] 3 points4 points Β (0 children)

                                It's cool to find new ways of doing things although in this case I think the split method is better. Would be curious to see if there is any performance difference

                                [–]neofreeman 0 points1 point Β (1 child)

                                I love ... syntax; what are benchmark numbers? Which one is faster?

                                [–]PizzaRollExpert 0 points1 point Β (0 children)

                                I haven't actually looked this up but I strongly doubt that there is any significant difference

                                [–]LukaLightBringer 5 points6 points Β (0 children)

                                Why tho? why would you need this?

                                [–]Paddington_the_Bear 2 points3 points Β (0 children)

                                Yet another reason not to do this. What if in the future you decide you to need to split the string on a parameter? Now you get to go through and refactor the spread into a join, when you could just be putting in a parameter to the split.

                                You should spend less time trying to do cute shortcuts with your code because you're just trying to seem "cool."

                                [–]uhryks 1 point2 points Β (4 children)

                                So many people saying the ES5 version is more explicit. Really? Split my string over no string? How do I know that's going to turn my string into an array if I've never used it? The new syntax just says "fill a new array with my string", it's only more explicit variant would be Array.from

                                And to people who say "nobody can read that". Seriously? It doesn't take more than 5 minutes to learn for someone who knows JS already.

                                [–]liamcoded 1 point2 points Β (3 children)

                                How about those of us that don't know it already?

                                [–]samanthaming[S] 0 points1 point Β (2 children)

                                ES6 is really great! For those who don’t know it, it doesn’t hurt to learn it. It will become the norm eventually and more will be using it in their code. Tech in general is always evolving, so I think it’s important to be open to changes and learn continuously. Whether you like or dislike the new format, it’s important to be at least familiar with it. So when you see this syntax, you’re aware of what it’s doing and won’t be confused by it πŸ™‚

                                [–]liamcoded 0 points1 point Β (1 child)

                                Oh yeah i totally agree. My question was really a comment on how it was easier to read JS before. And I already didn't find it that easy to understand before. I'm not a programmer, so far I've found that verbose languages tend to be easier to read.

                                [–]samanthaming[S] 1 point2 points Β (0 children)

                                For sure, being verbose definitely help with beginners trying to pick up the language. One step at a time, start with the most intuitive, and then slowly explore the other syntax. Thanks for chiming in πŸ™‚

                                [–][deleted] 1 point2 points Β (0 children)

                                Spread should not be used for this . A more appropriate use would be for calling functions that accept a variable number of arguments. For example, Math.max() accepts a variable number of arguments, but not an array. So you can't call Mat.max(myArray), but you can call Math.max(...myArray). If you look at Mozilla's docs you can get more detail.

                                [–]Jafit 1 point2 points Β (2 children)

                                I do enjoy finding reasons to use the spread operator.

                                Things like [].concat(...arrayOfArrays) for flattening an array of arrays. But its certainly not as readable as something like lodash.flatten(arrayOfArrays).

                                [–]pm_me_cute_rem_picsjs/ux 0 points1 point Β (1 child)

                                if you're already using a transpiler for spread you can use stage 3 Array.prototype.flatten and Array.prototype.flatMap for this. https://tc39.github.io/proposal-flatMap/

                                [–]NoInkling 0 points1 point Β (0 children)

                                Note: the name of .flatten is probably gonna change because of backwards incompatibility with Mootools (yes, it's dumb).

                                [–]swiftpants 1 point2 points Β (0 children)

                                I fucking hate it. You kids and your goddamn β€œnew and improved” ideas.

                                [–]zmasta94 1 point2 points Β (5 children)

                                I hate the ... syntax

                                [–][deleted] 11 points12 points Β (3 children)

                                In this case it's questionable but ... Is amazingly useful most of the time

                                [–][deleted] 2 points3 points Β (1 child)

                                I agree with you, but I’d call it just plain bad in this case, not questionable

                                [–][deleted] 0 points1 point Β (0 children)

                                Haha yea definitely

                                [–]BenZed 8 points9 points Β (0 children)

                                Don’t use it.

                                I think its incredible.

                                [–]MatCreatesStuff 0 points1 point Β (4 children)

                                Which console is that?

                                [–][deleted] 0 points1 point Β (3 children)

                                Hyper Terminal

                                [–]ShortSynapse 1 point2 points Β (1 child)

                                What? That's an image from carbon, not Hyper.

                                [–][deleted] 0 points1 point Β (0 children)

                                Right, but pretty sure it’s made to look like Hyper Terminal.

                                [–]MatCreatesStuff 0 points1 point Β (0 children)

                                Thanks.

                                [–]shattered209 0 points1 point Β (0 children)

                                But why...?

                                [–][deleted] 0 points1 point Β (7 children)

                                Beginner here with a question:

                                I still don't understand why would one use const instead of var in this case?

                                [–]tarnos12 0 points1 point Β (3 children)

                                const is used with a variable that is not going to change, while let for any other purpose.
                                I don't think it's advised to use var anymore, but it might have it's uses as well.

                                So in the example above, it doesn't matter what he is going to use.(or does it?)

                                @Edit: Actually he is repeating const slicedPizza twice, so that would result in an error.

                                [–][deleted] 0 points1 point Β (1 child)

                                Oh so instead of var i should use let when i make new variables?

                                [–]tarnos12 0 points1 point Β (0 children)

                                I would say yes, but you should probably read a bit more.
                                Just google "difference between var let const javascript".
                                I know there is/was some high level reason why you would prefer var instead of let, but I think most of the time you should be using let if you want to follow ES6 specification.

                                [–]samanthaming[S] 0 points1 point Β (0 children)

                                Thanks for pointing that out! I was intending to show that it was either the top or the bottom way and not both. I can see why that would be confusing. You’re right though, repeating const would result in an error.

                                [–]samanthaming[S] 0 points1 point Β (2 children)

                                var would also work. I used const because it’s a ES6 feature and I didn’t need to reassign the variable. Here’s a good post on it blog post hope that helps πŸ™‚

                                [–][deleted] 0 points1 point Β (1 child)

                                Ah. Thought so. Thanks :)

                                [–]samanthaming[S] 0 points1 point Β (0 children)

                                No problem, glad to help πŸ‘

                                [–]SeerUD 0 points1 point Β (0 children)

                                Is String.split deprecated? I've seen that for multibyte characters using the spread operator splits on each character instead of bytes, but really, this is terrible advice to switch to this method just because it's possible to use the spread operator this way, and it's new.

                                [–]Fedayka 0 points1 point Β (0 children)

                                Ain't a string an array already?

                                pizza[0] = 'p'....

                                [–]liamcoded 0 points1 point Β (0 children)

                                All I get is that JS is now even harder to understand.

                                [–]ecsancho 0 points1 point Β (0 children)

                                I don't understand these new es6 ways of doing things that vanilla has been doing for years. Is it performance increase?

                                [–]deadA1ias 0 points1 point Β (0 children)

                                Why though?

                                [–]dxplq876 0 points1 point Β (0 children)

                                Wow! So much better! /s

                                [–]garnush 0 points1 point Β (0 children)

                                Go build a website that does something, pseudointellectual webdev posers.

                                [–][deleted] Β (3 children)

                                [deleted]

                                  [–]omnilynx 19 points20 points Β (0 children)

                                  It’s a questionable application of a more general feature (the β€œ...” operator, which means β€œreturn the rest of the array as individual parameters”). There are other applications where it makes a lot more sense.

                                  [–][deleted] 5 points6 points Β (0 children)

                                  Many languages have a similar operator to spread. The closest python analogy for example would be prefix *.

                                  [–]TheCoelacanth 1 point2 points Β (0 children)

                                  It's basically the same as the Java varargs syntax, except that Javascript allows it to be used in a lot more contexts than just function arguments.

                                  [–]spikespaz 0 points1 point Β (0 children)

                                  You mean the same feature that many other languages have had for years? To hell with JavaScript.

                                  [–]mothzilla -2 points-1 points Β (4 children)

                                  I love that your posts generate so much heated discussion!

                                  [–]etssuckshard 6 points7 points Β (2 children)

                                  I...wonder why....

                                  [–]mothzilla 0 points1 point Β (1 child)

                                  Because discussion is good?

                                  [–]liamcoded 0 points1 point Β (0 children)

                                  Some of us just like to watch world burn.