Live data from Hacker News

Overview of JavaScript ES6 features

adrianmejia.com

181–190 of 250 posts

Re: Overview of JavaScript ES6 features

#181

I have a question: What does `for element of arr` buy me over `arr.forEach(element => ...)` I don't find the for...of syntax particularly appealing or useful, but I might be missing something. Is it a matter of preference?

for-of works with any iterable. break/return/throw work as expected. I imagine (eventually if not already) for-of will be slightly more performant, but that's just a hunch. Personally I find the for-of syntax more readable.

Not only that, but in the future when async/await lands (or right now if you are willing to compile and can put up with potential breakage), for-of becomes a godsend.

The lack of inner functions means that you can await during part of a loop without a bunch of fuckery with the inner function with forEach.

Re: Overview of JavaScript ES6 features

#182
post #159

Earlier quoted context omitted.

That makes a lot of sense for c++ constness, which has virtually nothing to do with JavaScript's const. C++ constness is significantly more far-reaching and therefore more work to get right. I agree with his position. JavaScript const is just a matter of typing 2 more characters and in exchange you make your code more readable (because you communicate "this stuff will never change from here on", which makes understan…

> C++ constness is significantly more far-reaching and therefore more work to get right. I'm not familiar with C++, can you explain more?

A const variable means that variable won't change. So `const int i = 6` means i will never change. But often you'll use pointers or references, these are C++'s way for a variable to point to data elsewhere. You can also make the pointers or references themselves const. Finally, you can make functions const too, which lets you turn C++ into half a haskell.

First pointers and references. For simplicitly I'm going to ignore references and focus on pointers - the difference is not very interesting in this context. In most languages you probably know, referring to objects is done implicitly: variables that "are" objects are actually references to objects located elsewhere, and variables that are primitive types (numbers, booleans, strings) are just right there. Because of this, in JavaScript you can do this:

    var a = {};
    var b = a;
    b.moo = 6;
    a.moo === 6; // true
In here, a and b point to some object that "is" neither a or b - the object itself just floats around in memory and it'll exist until neither a, b, nor anyone else points to it anymore and the GC decides it has to go.

In C++, you'll need pointers or references for this, eg.

    somestruct a;
    somestruct* b = &a; //b now points to a
    a.moo = 6;
    b->moo == 6; // true
(-> is just C++ shorthand for "follow the pointer and then do a property lookup).

Ok now const.

    somestruct const a;
    a.moo = 6; // error! can't modify a const.
Ok well how about

    somestruct a;
    somestruct* const b = &a;
    b->moo = 6;
    a.moo === 6; // true
This means the pointer is const. That works because we never change where b is pointing to. So how about:

    somestruct a;
    somestruct const* const b = &a;
    b->moo = 6;
    a.moo === 6; // true

Oh damn. Crying baby. Const functions will have to wait for some other day.

Re: Overview of JavaScript ES6 features

#183

The most interesting part about template strings was skipped over: tagged template literals. You can prefix a template string with a function which will get called with the list of string parts and the values passed in ${...} parts, and then it's up to the function to choose how to join the values up into the resulting string (or hell, you could make it return something besides a string if you want). The function can…

How does this work? I can't find any examples and I also don't really understand what mechanism makes your npm module work.

A tagged template literal is just a special ES6 syntax for calling a function with a specific set of arguments. You could pass a function which returns all of the arguments as an array to see what's passed in. Try the following in the console of a modern browser:

    function log(...args) { return args; }
    log `abc ${'blah'} fooo\n ${12+3} bar`;
Or you could even shorten the above down to this:

    ((...args)=>args) `abc ${'blah'} fooo\n ${12+3} bar`;
The expression will evaluate to this:

    [["abc ", " fooo\n ", " bar"], "blah", 15]
The first argument is an array of the parts of the literal text, and then the rest of the arguments are the values that were passed in. Additionally, the first argument (the array of string parts) has the `raw` property set to point to an array of string parts with the backslash escapes uninterpreted.

Here's an example re-implementation of `String.raw`:

    function raw({raw}, ...values) {
      const parts = new Array(raw.length*2-1);
      parts[0] = raw[0];
      for (let i=0, len=values.length; i

Re: Overview of JavaScript ES6 features

#184
post #55

While I'm a big believer in most of the ES6 changes (arrow functions! let/const! classes! generators!), I am not a big fan of many of the new destructuring features. They can actually make your code less approachable if you don't already know what's going on.

Exactly, and this is a big problem where I work. I believe code should be readable, even by those with only cursory knowledge of the language. Object shortcuts is also a problem I think. For example, I had a method like this: const getObj = (id, store) => { return { id: id name: store.something.name }; }; The linter gave an error on it because I used {id: id}. It was like the linter was trying to make my code harder…

You know instead of:

  const getObj = (id, store) => { return { id } }
You could write:

  const getObj = (id, store) =>  ({ id })

Re: Overview of JavaScript ES6 features

#185
post #164

Some of these features are really nice, but JS is on a path to become as complex as C++.

That's the natural result of being unable to remove any features to maintain legacy compatibility.

Well unlike the majority of C++ warts, JS is doing a very good job of "hiding" it's ugly parts with things like "use strict"

Things like `with` and a bunch of ugly parts were hidden with the introduction of "use strict", and i'm more than confident it will happen again in the future with something similar that can let you "opt in" to an even stricter JS that leaves behind the "current" warts of javascript in favor of much better ways.

Re: Overview of JavaScript ES6 features

#186
post #179
post #175

Earlier quoted context omitted.

537M here. babel* matches the following packages: node_modules/babel node_modules/babel-core node_modules/babel-eslint node_modules/babel-plugin-array-includes node_modules/babel-plugin-transform-runtime node_modules/babel-preset-node5 node_modules/babel-register node_modules/babel-runtime Of course you can just pretend I'm lying.

I believe that you're getting that number, but there might be something wrong with your install. I just installed all of those packages and ended up at 6MB.

I don't think it's such a stretch. From facebook's yarn announcement[1]:

> or example, updating a minor version of babel generated an 800,000-line commit that was difficult to land and triggered lint rules for invalid utf8 byte sequences, windows line endings, non png-crushed images, and more. Merging changes to node_modules would often take engineers an entire day.

I just did a fresh install in a new directory and ended up with 114M worth of dependencies, so I'm not entirely sure what the difference is.

My point is. 50MB, 114MB, or 500MB worth of javascript dependencies is a massive footprint. It works and I'm relatively happy with what it does, but I don't see this as a stable, long term thing.

[1]: https://code.facebook.com/posts/1840075619545360

Re: Overview of JavaScript ES6 features

#187
post #94

Earlier quoted context omitted.

`const` means that the variable binding itself is immutable. It only affects the variable binding, not the value it points to. If it affected the value it pointed to, what would happen in this type of situation? let x = {}; const y = x; x.a = 5;

This is trivially testable in most browsers inspection tools. The answer is it works fine. x.a === y.a === 5 This is because you are simply declaring the binding of y to the object bound to x constant. This does not impact your ability to rebind x or to alter the contents of the object, it simply prevents you from rebinding y. let x = {a:5} x = {} console.log(x.a) // undefined --- const y = {a:5} y = {} // Uncaught T…

The question was rhetorical to try to demonstrate that it might result in surprising behavior if const just manipulated its values to make them become immutable. If adding the `const y = x;` line made the object referenced in `x` be immutable, then the 3rd line would fail, which I don't is a consequence desired even by people who thought const made things immutable.

I guess one alternative idea for how const would work could be an implementation where `x.a = 5` worked but `y.a = 5` failed. But then what happens if you pass `y` into a function which then tries to assign the `a` property on it? Is the const-ness part of the value passed into the function, or is it a property on variable bindings, and you could only pass `y` to functions that accepted a const variable? That kind of function type checking isn't something usual to javascript currently. And then is the const-ness deep? Is `y.foo.a = 5;` blocked? Mutable DOM elements are a big part of javascript. If the object happened to contain a reference to an element that needed to be manipulated, then you won't be able to do something like `y.foo.element.textContent = "new foo content";`. Going down this road it's now getting to be a pretty big feature that doesn't cleanly fit with the rest of the language or common tasks.

Maybe the naming is a little unfortunate: Javascript's `const` has more in common with Java's `final` than C's `const`.

Re: Overview of JavaScript ES6 features

#188
post #139

Earlier quoted context omitted.

const vs let is an "immutable by default" vs "mutable by default" type of difference. it's not just a style difference, it can help you write stateless code if you assume immutability. but yeah.

Native objects in JavaScript are already immutable as in you can not change them, only create new objects. Const will not make your object immutable! Try this: const foo = {bar: 1} foo.bar = 2; It will only avoid having the pointer re-pointed to another object. It's better to just try avoiding global variables, and use a naming convention like uppercase and/or underscore for constants and global variables. Const is p…

You can call `Object.freeze()` if you want immutable properties.

Re: Overview of JavaScript ES6 features

#189

The most interesting part about template strings was skipped over: tagged template literals. You can prefix a template string with a function which will get called with the list of string parts and the values passed in ${...} parts, and then it's up to the function to choose how to join the values up into the resulting string (or hell, you could make it return something besides a string if you want). The function can…

SQL actually demonstrates a good use case for custom template handlers. It's not SQL, but we're using a template handler to make writing parameterized queries trivial for ArangoDB: https://github.com/arangodb/arangojs#aql

Example:

    var userCollection = db.collection('_users');
    var role = 'admin';
    db.query(aql`
        FOR user IN ${userCollection}
        FILTER user.role == ${role}
        RETURN user
    `)
The template handler returns an object with the parameterized query string and the parameter values, which the `query` method understands. Because collection parameters are syntactically distinct from regular parameters this also avoids accidentally passing in arbitrary strings as collection names -- and of course it completely avoids injection attacks as a category.

In my experience this is actually much more comfortable to use than a "fluent" API that tries to map the query language to the programming language (i.e. `select('id').from('foo')` and so on).

Full disclosure: I wrote that library.

Re: Overview of JavaScript ES6 features

#190
I gave a more complete overview of ES6 (and ES2016 and so on) features at a user group last month. Slides:

http://files.meetup.com/11421852/WhatsNewInJavaScript.pdf

The slides are mostly code examples and I tried to go for completeness rather than detail, so there are some mentions you don't normally see in these overviews (e.g. the article doesn't mention proxies).

Post reply on HN