ESNext: Proposals to look forward to (Full Stack Antwerp)

Yesterday I was invited as a speaker at the Full Stack Antwerp December 2018 Meetup at icapps.

At the meetup I gave an adaptation of my talk “What’s Next for JavaScript”. The talk itself – which got renamed to “ESNext: Proposals to look forward to” – goes more into depth onto the proposals themselves, and skips the coverage of ES2015 through ES2018 (which could be a talk all by itself).

With the yearly ECMAScript releases (ES2015..ES2018) of a lot of things have changed in JavaScript-land. And even more changes are ahead!

This talk takes a look at a few of the upcoming ECMAScript features, which will (hopefully) become part of the ECMAScript Language Specification in the near future.

The slides are up on slidr.io, and also embedded below:

Talk Outline:

  • TC39: Info on TC39, what they do, and how they work.
  • ESNext Proposal: Field Declarations
  • ESNext Proposal: Optional Chaining
  • ESNext Proposal: Null Coalescing
  • ESNext Proposal: Pipeline Operator
  • ESNext Proposal: Dynamic Imports
  • ESNext Proposal: Pattern Matching
  • ES2015 Refresher: Promises
  • ESNext Proposal: Cancellation API
  • ESNext Proposal: Function Bind Syntax
  • ESNext Proposal: Slice Notation
  • ESNext Proposal: Object.fromEntries()
  • Fin.

Thanks to the organisers for having me, and thanks to the attendees for coming to see me. I hope you all had fun attending this talk. I know I had making it (and whilst bringing it forward) 🙂

📅 If you missed out on the talk and want to see it, you can always attend Full Stack Ghent March 2019 Meetup. At said meetup I’ll bring forward the same talk.

What’s next for JavaScript? – A talk on ESNext by @bramus

I’m currently in Utrecht for Frontend United and have just finished my talk ”What’s next for JavaScript?”. Earlier this week I also gave a shortened version of this lecture at JSConf.be

With ES2015 a lot has changed in JavaScript-land. Lesser known releases are the ES2016 and ES2017 releases. This talk not only touches these two new releases, but also looks forward at what’s to come next for JavaScript (ES2018 and more).

The slides are up on slidr.io, and also embedded below:

UPDATE 2018.06.12 A recording of my session has been put online:

The talk consists out of a few sections:

  • JavaScript Yellow: How to get JavaScript Yellow on your website (a plea to using the right tool for the right job)
  • The JavaScript timeline: its birth, its standardisation, and its releases
  • ES2015: Highlight few of the ES2015 features I use on a daily basis
  • ES2016: All new features that are part of ES2016
  • ES2017: Highlight few of the ES2017 features I use on a daily basis
  • ES2018: Highlight few of the ES2018 features I use on a daily basis or get me excited
  • TC39: An intermezzo on TC39 and what they do, how they work, etc.
  • ESNext: An look at a selection of proposals that get me excited, but are not part of the ECMAScript Specification (yet)
  • ESNext, now: how/why you can use certain language features now, even though they’re not stage-4 yet
  • Fin.

Thanks to the organisers for having me, and thanks to the attendees for coming to see me. Extra thanks go out to Mathias Bynens for doing an impromptu review of my slides. I hope you all had fun watching this talk. I know I had making it (and bringing it forward) 🙂

And now … time for a beer 😉

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

ESNext: JavaScript “Nullish Coalescing Operator”

UPDATE December 2019: This feature has now advanced to Stage-4 and will be part of the ES2020 Specification! 🎉

One of my favorite ECMAScript Proposals is the “Optional Chaining Operator”. Another proposal that forms great duo with it is the “Nullish Coalescing Operator” (sometimes also referred to as “Nullary Coalescing Operator”).

Both proposals still are Stage-1, but don’t let that stop us from taking a peek into it right now.

💁‍♂️ Stage-1?

The Technical Committee which is concerned with the standardization of ECMAScript (e.g. TC39) has a 5 stage process in place, ranging from stage-0 to stage-4, by which it develops a new language feature.

Stage-1 is the Proposal stage. It signals that the committee is showing interest in the proposal and that it is seeking further investigation on how to tackle it. At this stage the proposal is subject to heavy changes. It is only when a proposal reaches Stage 4 that it is ready to become part of the ECMAScript Specification.

~

The problem

As explained in the “Optional Chaining Operator” post we can get properties of an object in a fail safe way using Short-Circuit Logic or by using the proposed Optional Chaining operator (?.) in the nearby future:

// Today: Extract firstName using Short-Circuit Logic
const firstName = message.body && message.body.user && message.body.user.firstName;
// Near future: Extract firstName using the Optional Chaining Operator
const firstName = message.body?.user?.firstName;

A common technique used is to add a default fallback value using the logical OR operator (||):

const firstName = message.body?.user?.firstName || 'Stranger';

Whilst this works fine, there is one problem with falsy values: when the left hand side of the OR expression evaluates to falsy (e.g. null, undefined, false, 0, empty string, …), the right hand side of the expression will be used. For null and undefined that’s not a problem, but it is for false, 0, empty string, etc.:

const message = {
    settings: {
        animationDuration: 0,
        showSplashScreen: false
    },
};

const showSplashScreen = message.settings?.showSplashScreen || true;
// --> true 🚫

The result here is true (the fallback), even though message.settings.showSplashScreen was defined to be false.

~

The solution

The proposed Nullish Coalescing Operator ?? is intended to provide a solution to this problem. It serves as an equality check against nullary values (e.g.
null or undefined). Whenever the expression to the left of the ?? operator evaluates to either undefined or null, the value defined to the right will be returned.

Combined with the Optional Chaining Operator, our code snipped can be fixed like this:

const message = {
    settings: {
        animationDuration: 0,
        showSplashScreen: false
    },
};

const showSplashScreen = message.settings?.showSplashScreen ?? true;
// --> false 🎉

Small change, big impact 🙂

~

So, when can we us this?

You can use the Nullish Coalescing Operator today already thanks to Babel’s plugin-proposal-nullish-coalescing-operator plugin (for use with Babel 7).

Do note that the proposal still Stage-1 (soon Stage-2 by the looks of it) and might still change in the future.

~

In short

💻 The examples embedded in this post are part of a talk on ESNext named “What’s next
 for JavaScript?”, which I recently gave at a Fronteers België meetup and Frontend United 2018 (Utrecht). You can check the slides / a recording out here. I’m available for bringing this talk at your meetup/conference.

👋 This post also got published on Medium. If you like it, please give it some love a clap over there.

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

JavaScript: What’s new in ECMAScript 2018 (ES2018)?

👋 This post also got published on Medium. If you like it, please give it some love a clap over there.

At the latest TC39 meeting the new features that will make it into the “ECMAScript® 2018 Language Specification” (ES2018) have been selected. All proposals that have reached stage-4 since the consolidation of ES2017 got selected. This post gives one a quick look at the features that made it into ES2018.

💁‍♂️ Stage-4?

The Technical Committee which is concerned with the standardization of ECMAScript (e.g. TC39) has a 5 stage process in place, ranging from stage-0 to stage-4, by which it develops a new language feature.

Stage-4 is the Finished Stage and indicates that the proposal is ready to become part of the ECMAScript Specification.

~

Rest/Spread Properties

When destructuring, Rest/Spread Properties allow you to collect the remaining properties of an object into a new object. Think of it as a magic magnet attracting all leftovers.

I use this one myself a lot, especially in a React (Native) context where I pluck certain values from this.props for internal use, and then forward all other props to the returned child component.

Additionally, if you turn your thinking-logic around a bit, Rest/Spread Properties provide you with a good way to remove a property from an object in an immutable way.

~

Asynchronous Iteration

With Asynchronous Iteration we get asynchronous iterators and asynchronous iterables. Asynchronous iterators just like regular iterators, except their next() method returns a promise for a { value, done } pair. To consume asynchronous iterables, we can now use the await keyword with for … of loops.

~

Promise.prototype.finally()

Promise.prototype.finally() finalizes the whole promises implementation, allowing you to register a callback to be invoked when a promise is settled (either fulfilled, or rejected).

A typical use case is to hide a spinner after a fetch() request: instead of duplicating the logic inside the last .then() and .catch(), one can now place it inside .finally()

~

RegExp related features

In total 4 RegExp related proposals made it into ES2018:

I especially digg the “RegExp named capture groups” feature, as it improves readability:

More info on these features can be found at Mathias Bynens – one of the driving forces behind these proposals – his blog: ECMAScript regular expressions are getting better!

~

Other new Features

To top it off a tweak to template literals landed: when using tagged template literals the restriction on escape sequences are removed, thus allowing things like \xerxes. Before this tweak an error would be thrown because \x is the start of a hex escape with erxes not being a valid hex value.

Tagged template literal?

💁‍♂️ As per MDN: If there is an expression preceding the template literal, the template string is called a “tagged template literal”. In that case, the tag expression (usually a function) gets called with the processed template literal, which you can then manipulate before outputting.

~

What now?

Do note that not all these features are readily available in all browsers. Meaning that they’re Stage-4 means that they are finished, and that browser vendors should implement them (some already have, others are in the process).

As for the future, I’m already looking forward at what’s next to come for JavaScript. Things like the Optional Chaining Operator already get me very excited 🙂

💻 The examples embedded in this post are part of a talk on ESNext named “What’s next
 for JavaScript?”, which I recently gave at a Fronteers België meetup. I’m currently still in the process of preparing the slides for publication. I’m available for bringing this talk at your meetup/conference.

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

JavaScript: Remove a property from an object immutably by destructuring it

Say you have a JavaScript object like this:

const user = {
    firstName: 'Bramus',
    lastName: 'Van Damme',
    twitter: 'bramus',
    city: 'Vinkt',
    email: 'bramus@bram.us',
};

And now say you want to create a copy of the whole object, containing all properties except for the email property.

# The oldskool way:

The first idea that came to my mind was to clone/copy the object and then successively remove email from the new object using the delete operator:

const userWithoutEmail = Object.assign({}, user);
delete userWithoutEmail.email;

But that could use some more ES2015 syntax, no?

# Remove an Object property using Destructuring + Rest Properties:

Thanks to Destructuring and Object Rest/Spread Properties (currently stage 3), we can also do this:

const {
    email,
    ...userWithoutEmail
} = user;

This little piece of code lifts email from the user object (e.g. destructuring), and then collects all remaining properties into userWithoutEmail (e.g. rest spreading). Handy!

# Remove a variable object property using Destructuring + Rest Properties:

If you want to remove a certain property through a variable containing its name, use this syntax:

const propertyToRemove = 'email';

const {
    [propertyToRemove]: removed,
    ...userWithoutEmail
} = user;

Since you’re using a dynamic field, you need to use [] to destrucutre the property from the object. Its result is then aliased into a variable named removed. What’s left is over is collected into userWithoutEmail

📣 The contents of this article is part of a talk on ESNext named “What’s next
 for JavaScript?” which I recently gave at a Fronteers België meetup. If you’re meetup/conference organiser, feel free to contact me to have me speak at your event.

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

ESNext: JavaScript “Optional Chaining Operator”

UPDATE December 2019: This feature has now advanced to Stage-4 and will be part of the ES2020 Specification! 🎉

UPDATE: The proposed operator got renamed from “Null Propagation Operator” to “Optional Chaining Operator”. This post has been updated to include this change.

Earlier today I was delighted to see that the “Optional Chaining Operator” in JavaScript has entered stage-1. This little gem – which I know from Coffeescript – is a real timesaver, and is something I’ve been looking forward to.

💁‍♂️ Stage-1?

The Technical Committee which is concerned with the standardization of ECMAScript (e.g. TC39) has a 5 stage process in place, ranging from stage-0 to stage-4, by which it develops a new language feature.

Stage-1 is the Proposal stage. It signals that the committee is showing interest in the proposal and that it is seeking further investigation on how to tackle it. At this stage the proposal is subject to heavy changes. It is only when a proposal reaches Stage 4 that it is ready to become part of the ECMAScript Specification.

The problem

Let’s start at the beginning. Say we have this simple Object named message:

const message = {
  body: {
    user: {
      firstName: 'Bramus',
      lastName: 'Van Damme',
    },
  },
};

To access the firstName property of that object, we can use this snippet right here:

const firstName = message.body.user.firstName;

However, this isn’t really safe: if message.body.user were not to exist, we’d get a JavaScript error:

const thisWillFail = message.body.inexistent.firstName;
// --> "Cannot read property 'firstName' of undefined"

Uh oh!

The hacky workaround

To fix this we – at this moment – can reside to Short-Circuit Evaluation:

const firstName = message.body && message.body.user && message.body.user.firstName;

Shouldn’t that return true?

💁‍♂️ The reason that this works it because of JavaScript returning the last encountered value – and not a boolean – when using Short-Circuit Logic.

To include a default fallback value, we can add some more Short-Circuit Logic, using the || operator:

const firstName = (message.body && message.body.user && message.body.user.firstName) || 'Stranger';

If the expression to the left of the || operator were to evaluate to something falsy (e.g. null, undefined, false, 0, empty string, …), the value to the right will be used.

Alternatively one could also use something like this:

const firstName = (((message || {}).body || {}).user || {}).firstName || 'Stranger';

(… Yeah, I know!?)

The proper solution

Now enter the “Optional Chaining Operator” ?. which provides us with a very elegant syntax and fail-safe approach to the issue described above:

const firstName = message.body?.user?.firstName || 'Stranger';

Whenever the expression to the left of the ?. operator evaluates to either null or undefined the whole expression it belongs to will evaluate to undefined, thus falling back to the default defined using the ||:

const firstName = message.body?.inexistent?.firstName || 'Stranger';

In the example above message.body?.inexistent evaluates to undefined. Therefore the entire message.body?.inexistent?.firstName expression will be considered to be undefined.

As a result the interpreter will then evaluate const firstName = undefined || 'Stranger';, to finally return 'Stranger' as the value for firstName.

Here’s to hoping that this one reaches stage-4 any time soon. As far as I can tell this is not in Babel (yet) the Babel folks are working on it.

ECMAScript Proposal: Optional Chaining →

💻 The examples embedded in this post are part of a talk on ESNext named “What’s next
 for JavaScript?”, which I gave at a Fronteers België meetup and Frontend United 2018 (Utrecht). You can check the slides / a recording out here. I’m available for bringing this talk at your meetup/conference.

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

ES6 ES2015: Looping over an Object with keys and values

javascript-logo-banner

Say you have an object like this:

const obj = {
    firstName: 'John',
    lastName: 'Doe',
    age: 50,
    eyeColor: 'blue'
};

Using lodash’s forEach you can easily loop over this object, with easy access to both the key and the value:

_.forEach(obj, function(value, key) {
    console.log(key + ' ' + value);
});

But what about ES2015? After fiddling a bit, I came to the conclusion that a simple one-liner is all it takes to loop over it:

for (const [key, value] of Object.entries(obj)) {
    console.log(`${key}: ${value}`);
}

The output will be this:

firstName: John
lastName: Doe
age: 50
eyeColor: blue

In case you were wondering, here’s how it works:

  1. Object.entries() returns an array (with numeric indices) of key-value pairs.
    object-entries
  2. Using for ... of we loop all those pairs.
  3. Thanks Array Destructuring we can assign easily assign both the key and value into the key and value variables.

Alternatively you can also get the same result using Array#forEach(), which might be more readable to you (and has a closer resemblance to _.forEach):

Object.entries(obj).forEach((entry) => {
    const [key, value] = entry;
    console.log(`${key}: ${value}`);
});

You can make this even more condense by destructuring directly in the function:

Object.entries(obj).forEach(([key, value]) => {
    console.log(`${key}: ${value}`);
});

💻 The examples embedded in this post are part of a talk on ESNext named “What’s next
 for JavaScript?”, which I gave at a Fronteers België meetup and Frontend United 2018 (Utrecht). You can check the slides / a recording out here. I’m available for bringing this talk at your meetup/conference.

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

Hybrid Apps with Ionic Framework

At the most recent #fronteersbe meetup I gave a talk entitled “Hybrid Apps with Ionic Framework”. You can check out the slides embedded below.

Slides with presenter notes (yet without animated gifs) – which might be a better option if you didn’t attend the talk – are also available.

JavaScript Roots: Core Language Essentials

(That’s a presentation embedded above. Use your left/right arrow keys to navigate through it. You might need to click it first in order to focus it.)

Whilst we, JavaScript developers, are nowadays spoiled with tools, frameworks, build systems, etc. we might tend to forget some of the core things contained in the JavaScript language.

Think of some core language things such as variables, variable types, functions, closures, IIFEs, etc. — these are all things that one should know as they can explain some of the — at first — odd looking behavior JavaScript has.

Yesterday, at a #fronteersbe meetup, I gave a talk just about that. The presentation is embedded above.