Posted in Information Technology, javascript

Javascript ES2015 ES2016 ES2017 ES2018 cheatsheet

A quick overview of new JavaScript features in ES2015, ES2016, ES2017, ES2018 and beyond.

Block scoping

Let

function fn () {
  let x = 0
  if (true) {
    let x = 1 // only inside this `if`
  }
}

Const

const a = 1

let is the new var. Constants work just like let, but can’t be reassigned. See: Let and const

Backtick strings

Interpolation

const message = `Hello ${name}`

Multiline strings

const str = `
hello
world
`

Templates and multiline strings. See: Template strings

Binary and octal literals

let bin = 0b1010010
let oct = 0o755

See: Binary and octal literals

New methods

New string methods

"hello".repeat(3)
"hello".includes("ll")
"hello".startsWith("he")
"hello".padStart(8) // "   hello"
"hello".padEnd(8) // "hello   " 
"hello".padEnd(8, '!') // hello!!!
"\u1E9B\u0323".normalize("NFC")

See: New methods

Classes

class Circle extends Shape {

Constructor

  constructor (radius) {
    this.radius = radius
  }

Methods

  getArea () {
    return Math.PI * 2 * this.radius
  }

Calling superclass methods

  expand (n) {
    return super.expand(n) * Math.PI
  }

Static methods

  static createFromDiameter(diameter) {
    return new Circle(diameter / 2)
  }
}

Syntactic sugar for prototypes. See: Classes

Exponent operator

const byte = 2 ** 8
// Same as: Math.pow(2, 8)

#Promises

Making promises

new Promise((resolve, reject) => {
  if (ok) { resolve(result) }
  else { reject(error) }
})

For asynchronous programming. See: Promises

Using promises

promise
  .then((result) => { ··· })
  .catch((error) => { ··· })

Using promises with finally

promise
  .then((result) => { ··· })
  .catch((error) => { ··· })
  .finally(() => { // logic independent of success/error })

The handler is called when the promise is fulfilled or rejected.

Promise functions

Promise.all(···)
Promise.race(···)
Promise.reject(···)
Promise.resolve(···)

Async-await

async function run () {
  const user = await getUser()
  const tweets = await getTweets(user)
  return [user, tweets]
}

async functions are another way of using functions.

See: async function

#Destructuring

Destructuring assignment

Arrays

const [first, last] = ['Nikola', 'Tesla']

Objects

let {title, author} = {
  title: 'The Silkworm',
  author: 'R. Galbraith'
}

Supports for matching arrays and objects. See: Destructuring

Default values

const scores = [22, 33]
const [math = 50, sci = 50, arts = 50] = scores
// Result:
// math === 22, sci === 33, arts === 50

Default values can be assigned while destructuring arrays or objects.

Function arguments

function greet({ name, greeting }) {
  console.log(`${greeting}, ${name}!`)
}
greet({ name: 'Larry', greeting: 'Ahoy' })

Destructuring of objects and arrays can be also be done in function arguments.

Default values

function greet({ name = 'Rauno' } = {}) {
  console.log(`Hi ${name}!`);
}
greet() // Hi Rauno!
greet({ name: 'Larry' }) // Hi Larry!

Reassigning keys

function printCoordinates({ left: x, top: y }) {
  console.log(`x: ${x}, y: ${y}`)
}
printCoordinates({ left: 25, top: 90 })

This example assigns x to the value of the left key.

Loops

for (let {title, artist} of songs) {
  ···
}

The assignment expressions work in loops, too.

Object destructuring

const { id, ...detail } = song;

Extract some keys individually and remaining keys in the object using rest (…) operator

#Spread

Object spread

with Object spread

const options = {
  ...defaults,
  visible: true
}

without Object spread

const options = Object.assign(
  {}, defaults,
  { visible: true })

The Object spread operator lets you build new objects from other objects.

See: Object spread

Array spread

with Array spread

const users = [
  ...admins,
  ...editors,
  'rstacruz'
]

without Array spread

const users = admins
  .concat(editors)
  .concat([ 'rstacruz' ])

The spread operator lets you build new arrays in the same way.

See: Spread operator

#Functions

Function arguments

Default arguments

function greet (name = 'Jerry') {
  return `Hello ${name}`
}

Rest arguments

function fn(x, ...y) {
  // y is an Array
  return x * y.length
}

Spread

fn(...[1, 2, 3])
// same as fn(1, 2, 3)

Default, rest, spread. See: Function arguments

Fat arrows

Fat arrows

setTimeout(() => {
  ···
})

With arguments

readFile('text.txt', (err, data) => {
  ...
})

Implicit return

numbers.map(n => n * 2)
// No curly braces = implicit return
// Same as: numbers.map(function (n) { return n * 2 })
numbers.map(n => ({
  result: n * 2
})
// Implicitly returning objects requires parentheses around the object

Like functions but with this preserved. See: Fat arrows

#Objects

Shorthand syntax

module.exports = { hello, bye }
// Same as: module.exports = { hello: hello, bye: bye }

See: Object literal enhancements

Methods

const App = {
  start () {
    console.log('running')
  }
}
// Same as: App = { start: function () {···} }

See: Object literal enhancements

Getters and setters

const App = {
  get closed () {
    return this.status === 'closed'
  },
  set closed (value) {
    this.status = value ? 'closed' : 'open'
  }
}

See: Object literal enhancements

Computed property names

let event = 'click'
let handlers = {
  [`on${event}`]: true
}
// Same as: handlers = { 'onclick': true }

See: Object literal enhancements

Extract values

const fatherJS = { age: 57, name: "Brendan Eich" }

Object.values(fatherJS)
// [57, "Brendan Eich"]
Object.entries(fatherJS)
// [["age", 57], ["name", "Brendan Eich"]]

#Modules

Imports

import 'helpers'
// aka: require('···')
import Express from 'express'
// aka: const Express = require('···').default || require('···')
import { indent } from 'helpers'
// aka: const indent = require('···').indent
import * as Helpers from 'helpers'
// aka: const Helpers = require('···')
import { indentSpaces as indent } from 'helpers'
// aka: const indent = require('···').indentSpaces

import is the new require(). See: Module imports

Exports

export default function () { ··· }
// aka: module.exports.default = ···
export function mymethod () { ··· }
// aka: module.exports.mymethod = ···
export const pi = 3.14159
// aka: module.exports.pi = ···

export is the new module.exports. See: Module exports

#Generators

Generators

function* idMaker () {
  let id = 0
  while (true) { yield id++ }
}
let gen = idMaker()
gen.next().value  // → 0
gen.next().value  // → 1
gen.next().value  // → 2

It’s complicated. See: Generators

Posted in javascript

No selenium server jar at the specific location

End to end testing with protractor is very important for developers doing BDD or TDD and using Angular
To install protractor there is a common error encountered of “Warning: there’s no selenium server jar at the specified location“.
Though there are several solutions online, and some include you specifying the selenium jar folder in your protractor configuration file, I disagree with this solution because if you are in a team and have other developers contributing to the project, this solution may not work on their machine
So the solution that I did that fixed this was that, instead of running
webdriver-manager update
as specified in protractor site, you should run this command instead
./node_modules/protractor/bin/webdriver-manager update
This would update the webdriver that your app is using
and voila, the error should be gone, and you should see a selenium folder in the protractor folder in your app
You can drop a comment if you have any other question
Posted in Information Technology, javascript, Software Engineering

Javascript singleton

(1) UPDATE 2019: ES7 Version

class Singleton {
    static instance;

    constructor() {
        if (instance) {
            return instance;
        }

        this.instance = this;
    }

    foo() {
        // ...
    }
}

console.log(new Singleton() === new Singleton());

(2) ES6 Version

class Singleton {
    constructor() {
        const instance = this.constructor.instance;
        if (instance) {
            return instance;
        }

        this.constructor.instance = this;
    }

    foo() {
        // ...
    }
}

console.log(new Singleton() === new Singleton());

Best solution found: http://code.google.com/p/jslibs/wiki/JavascriptTips#Singleton_pattern

function MySingletonClass () {

  if (arguments.callee._singletonInstance) {
    return arguments.callee._singletonInstance;
  }

  arguments.callee._singletonInstance = this;

  this.Foo = function () {
    // ...
  };
}

var a = new MySingletonClass();
var b = MySingletonClass();
console.log( a === b ); // prints: true

For those who want the strict version:

(function (global) {
  "use strict";
  var MySingletonClass = function () {

    if (MySingletonClass.prototype._singletonInstance) {
      return MySingletonClass.prototype._singletonInstance;
    }

    MySingletonClass.prototype._singletonInstance = this;

    this.Foo = function() {
      // ...
    };
  };

var a = new MySingletonClass();
var b = MySingletonClass();
global.result = a === b;

} (window));

console.log(result);
Posted in Information Technology, javascript

Sass cheatsheet

Variables

$red: #833;
body {
  color: $red;
}

Nesting

.markdown-body {
  p {
    color: blue;
  }

  &:hover {
    color: red;
  }
}

Comments

/* Block comments */
// Line comments

Mixins

@mixin heading-font {
  font-family: sans-serif;
  font-weight: bold;
}
h1 {
  @include heading-font;
}

with parameters

@mixin font-size($n) {
  font-size: $n * 1.2em;
}
body {
  @include font-size(2);
}

with default values

@mixin pad($n: 10px) {
  padding: $n;
}
body {
  @include pad(15px);
}

with a default variable

// Set a default value
$default-padding: 10px;
@mixin pad($n: $default-padding) {
  padding: $n;
}
body {
  @include pad(15px);
}

Extend

.button {
  ···
}
.push-button {
  @extend .button;
}

Composing

@import './other_sass_file`;

The .scss or .sass extension is optional.

#Color functions

rgba

rgb(100, 120, 140)
rgba(100, 120, 140, .5)
rgba($color, .5)

Mixing

mix($a, $b, 10%)   // 10% a, 90% b

Modifying HSLA

darken($color, 5%)
lighten($color, 5%)
saturate($color, 5%)
desaturate($color, 5%)
grayscale($color)
adjust-hue($color, 15deg)
complement($color)    // like adjust-hue(_, 180deg)
invert($color)
fade-in($color, .5)   // aka opacify()
fade-out($color, .5)  // aka transparentize() - halves the opacity
rgba($color, .5)      // sets alpha to .5

Getting individual values

HSLA

hue($color)         // → 0deg..360deg
saturation($color)  // → 0%..100%
lightness($color)   // → 0%..100%
alpha($color)       // → 0..1 (aka opacity())

RGB

red($color)         // → 0..255
green($color)
blue($color)

See: hue()red()

Adjustments

// Changes by fixed amounts
adjust-color($color, $blue: 5)
adjust-color($color, $lightness: -30%)   // like darken(_, 30%)
adjust-color($color, $alpha: -0.4)       // like fade-out(_, .4)
adjust-color($color, $hue: 30deg)        // like adjust-hue(_, 15deg)
// Changes via percentage
scale-color($color, $lightness: 50%)
// Changes one property completely
change-color($color, $hue: 180deg)
change-color($color, $blue: 250)

Supported: $red $green $blue $hue $saturation $lightness $alpha

#Other functions

Strings

unquote('hello')
quote(hello)
to-upper-case(hello)
to-lower-case(hello)
str-length(hello world)
str-slice(hello, 2, 5)      // "ello" - it's 1-based, not 0-based
str-insert("abcd", "X", 1)  // "Xabcd"

Units

unit(3em)        // 'em'
unitless(100px)  // false

Numbers

floor(3.5)
ceil(3.5)
round(3.5)
abs(3.5)
min(1, 2, 3)
max(1, 2, 3)
percentage(.5)   // 50%
random(3)        // 0..3

Misc

variable-exists(red)    // checks for $red
mixin-exists(red-text)  // checks for @mixin red-text
function-exists(redify)
global-variable-exists(red)
selector-append('.menu', 'li', 'a')   // .menu li a
selector-nest('.menu', '&:hover li')  // .menu:hover li
selector-extend(...)
selector-parse(...)
selector-replace(...)
selector-unify(...)

#Feature checks

Feature check

feature-exists(global-variable-shadowing)

Features

  • global-variable-shadowing
  • extend-selector-pseudoclass
  • units-level-3
  • at-error

#Loops

For loops

@for $i from 1 through 4 {
  .item-#{$i} { left: 20px * $i; }
}

Each loops (simple)

$menu-items: home about services contact;

@each $item in $menu-items {
  .photo-#{$item} {
    background: url('images/#{$item}.jpg');
  }
}

Each loops (nested)

$backgrounds: (home, 'home.jpg'), (about, 'about.jpg');

@each $id, $image in $backgrounds {
  .photo-#{$id} {
    background: url($image);
  }
}

While loops

$i: 6;
@while $i > 0 {
  .item-#{$i} { width: 2em * $i; }
  $i: $i - 2;
}

#Other features

Conditionals

@if $position == 'left' {
   position: absolute;
   left: 0;
}
@else {
   position: static;
}

Interpolation

.#{$klass} { ... }      // Class
call($function-name)    // Functions

@media #{$tablet}
font: #{$size}/#{$line-height}
url("#{$background}.jpg")

Lists

$list: (a b c);

nth($list, 1)  // starts with 1
length($list)

@each $item in $list { ... }

Maps

$map: (key1: value1, key2: value2, key3: value3);

map-get($map, key1)

 

Posted in Information Technology, javascript

Bootstrap cheatsheet

Screen sizes

         768          992                1200
'     '     '     '     '     '     '     '     '
<---------^------------^------------------^--------->
     xs         sm              md             lg
   (phone)   (tablet)        (laptop)       (desktop)

Min:

@media (min-width: @screen-sm-min) // >= 768px (small tablet)
@media (min-width: @screen-md-min) // >= 992px (medium laptop)
@media (min-width: @screen-lg-min) // >= 1200px (large desktop)

Max:

@media (max-width: @screen-xs-max) { // < 768px (xsmall phone)
@media (max-width: @screen-sm-max) { // < 992px (small tablet)
@media (max-width: @screen-md-max) { // < 1200px (medium laptop)

Columns

.container
.container-fluid
.col-xs-1
.col-sm-1
.col-md-1
.col-lg-1
.col-md-offset-1

Mixins:

@include make-xs-column(12);
@include make-sm-column(6);
@include make-md-column(3);
@include make-lg-column(3);
@include make-sm-column-offset(1);
@include make-sm-column-push(1);
@include make-sm-column-pull(1);

Utilities

.pull-left
.pull-right
.hidden-{xs,sm,md,lg}
.visible-{xs,sm,md,lg}
.visible-{xs,sm,md,lg,print}-{block,inline,inline-block}
.center-block  /* margin: auto */
.clearfix
.text-{center,left,right,justify,nowrap}
.text-{lowercase,uppercase,capitalize}
.show
.hidden
<a data-toggle='modal' data-target='#new'>
#new.modal.fade(role='dialog')
  .modal-dialog // .modal-lg, .modal-sm
    .modal-content
      .modal-header
        %h4.modal-title hello
        %button.close{type: 'button', data: { dismiss: 'modal' }}
          %span{'aria-hidden' => true}!= "&times;"
          %span.sr-only Close
      .modal-body
        ...
      .modal-footer
        ...
%button.btn{data: { |
  toggle: 'modal', |
  target: '#chooseTheme', |
  remote: '/path/to/remote'}
  Change Theme
.modal.fade#chooseTheme
  .modal-dialog.modal-xl
    .modal-content
      .modal-header
        %h4.modal-title Choose a theme

      .modal-body
        .spinner-panel.-lg
          %i

Tooltip

<span
  data-toggle='tooltip'
  title='tooltip'
  data-placement='left|top|bottom|right'>
$(function () {
  $('[data-toogle~="tooltip"]').tooltip()
})

Input groups

.input-group
    input.form-control(type='text')
    .input-group-addon years

 

Posted in javascript, Software Engineering

CSS flexbox cheatsheet

Simple example

.container {
  display: flex;
}
.container > div {
  flex: 1 1 auto;
}

Container

.container {
  display: flex;
  display: inline-flex;
  flex-direction: row;            /* ltr - default */
  flex-direction: row-reverse;    /* rtl */
  flex-direction: column;         /* top-bottom */
  flex-direction: column-reverse; /* bottom-top */
  flex-wrap: nowrap; /* one-line */
  flex-wrap: wrap;   /* multi-line */
  align-items: flex-start; /* vertical-align to top */
  align-items: flex-end;   /* vertical-align to bottom */
  align-items: center;     /* vertical-align to center */
  align-items: stretch;    /* same height on all (default) */
  justify-content: flex-start; /* horizontal alignment - default */
  justify-content: flex-end;
  justify-content: center;
}

Child

.container > div {
  /* This: */
  flex: 1 0 auto;

  /* Is equivalent to this: */
  flex-grow: 1;
  flex-shrink: 0;
  flex-basis: auto;
  order: 1;
  align-self: flex-start;  /* left */
  margin-left: auto;       /* right */
}

#Tricks

Vertical center

.container {
  display: flex;
}

.container > div {
  width: 100px;
  height: 100px;
  margin: auto;
}

Vertical center (2)

.container {
  display: flex;
  align-items: center;     /* vertical */
  justify-content: center; /* horizontal */
}

Reordering

.container > .top {
 order: 1;
}

.container > .bottom {
 order: 2;
}

Mobile layout

.container {
  display: flex;
  flex-direction: column;
}

.container > .top {
  flex: 0 0 100px;
}

.container > .content {
  flex: 1 0 auto;
}

A fixed-height top bar and a dynamic-height content area.

Table-like

.container {
  display: flex;
}

/* the 'px' values here are just suggested percentages */
.container > .checkbox { flex: 1 0 20px; }
.container > .subject  { flex: 1 0 400px; }
.container > .date     { flex: 1 0 120px; }

This creates columns that have different widths, but size accordingly according to the circumstances.

Vertical

.container {
  align-items: center;
}

Vertically-center all items.

Left and right

.menu > .left  { align-self: flex-start; }
.menu > .right { align-self: flex-end; }
Posted in gwt, Information Technology, javascript

Why is GWT still relevant?

Introduction

Google Web Toolkit (GWT) is an AJAX toolkit that allows development of AJAX based web application wit the use of Java Programming.

Advantages

1. Most coding problems are caught during compile time.

2. Runs on all platforms

3. Runs on all browsers

4. When created Java code is compiled, specific AJAX code is generated for every browser (Write one set of code that can run on all browsers).

5. GWT includes a lot of pre-built components.

6. GWT is Object Oriented because it is based from Java which converts it to JS(JavaScript)

7. IDEs like Eclipse makes coding with Java easier by allowing quick coding, shortcuts, code generation, and code analysis.

8. The compiler removes dead code and minifies it. The code is split into separate JavaScript files that helps the application load gradually as you visit new screens.

9. Manages static resources. CSS and images in code requires explicit declaration in the Java code.

10. Have an inbuilt structure for server-side component.

GWT started off well as a framework that converts Java into JavaScript, but it did not stay like that for long. One of the big developers had with GWT was the initiate learning curve specially for people that did not use Java language before. It took people months to learn GWT properly and see and effective return on time investment, and even with months of learning it did not seem like it was worth their time to learn more about GWT.

Disadvantages

1. Requires Browser plugin for development. The browser is not being maintained to work with newer browsers. This made it difficult for developers to adopt this framework.

2. Every time you change coding from the client side you are required to recompile. This made developing with GWT slower compared to other frameworks. Developers are used to just quickly refreshing the browser to see the changes.

3. The UI for GWT was initially good but as time passed GWT did not improve, rather they stayed stagnant on the UI development side. This made it difficult to choose GWT over other frameworks.

4. The last update for GWT was October 19, 2017. This means that the developers of this framework have stopped trying to improve this framework (basically abandoned it).

The world was also moving towards cloud-based web applications. Google tried to bring back GWT to life by putting in enough resources to trying and evolve the GWT framework.

Evolution

1. In 2012 2.5.0 was released which laid the foundation for the SuperDev mode. SuperDev mode works better for the modern browsers which makes compiling and seeing the results faster.

2. History management — which allows the user to navigate in the application using the browser’s back and forward buttons.

3. Made the SuperDev mode the default for application building.

Challenges for teams initially

1. There is no standardization of framework — This can lead to confusing for the team on which one to choose.

2. If you want to improve the look and feel of the website/s the team creates you have to either create your own CSS or use CSS frameworks instead of using GWT’s UI design since it looks old and outdated.

3. Since there are only a few people and companies using GWT now most developers/companies will choose to use other frameworks.

Screenshot from: https://trends.builtwith.com/framework/Google-Web-Toolkit [1]

Conclusion

There are currently 43.360 websites using Google Web Toolkit (GWT)[1]. GWT was a good framework that converts Java into JavaScript but it had problems with keeping up with other frameworks that kept on evolving to what the developer needs and wants. Since after Google stopped developing GWT themselves the framework’s improvement have slowed down and that is when GWT started its decline in popularity. Most websites that are currently using GWT technology seem to be older websites because most developers will opt-out of using GWT as a framework because there are other frameworks that are better maintained and have kept up with the changes. It is best for developers to learn other frameworks than to learn GWT.

References

[1] “Google Web Toolkit Usage Statistics”, BuiltWith® Pty Ltd, https://trends.builtwith.com/framework/Google-Web-Toolkit

Accessed: 3/30/2019

[2] “Super Dev Mode” GWTProject.org, http://www.gwtproject.org/articles/superdevmode.html

Accessed: 3/30/2019

[3] “Overview” GWTProject.org, http://www.gwtproject.org/overview.html

Accessed: 3/30/2019

[4] “GWT is coming back … in 2015”, Blog.Xam.de, https://blog.xam.de/2014/02/gwt-is-coming-back-in-2015.html

Posted in Information Technology, javascript

A Look at JavaScript’s Future

Every market is ruled by certain common concepts, and JavaScript development is no exception.

The product lifecycle is a concept that you can apply to several different environments to understand and predict their behavior. It is a business concept that helps us understand the stages that a product goes through during its life, explaining the impact of these stages on its popularity measure—in most cases, sales. If we observe market behavior patterns, we can estimate the current stage of a product and therefore make some predictions about its popularity.

Diagram of the product development lifecycle

There are four stages: introduction, growth, maturity, and decline, and on the chart above, you can see the impact on expected product sales for each stage. For example, smartphones sales aren’t growing like five years ago—actually, quite the opposite is true—so we can fairly say that smartphones are getting into their maturity stage.

In the past few years, we’ve seen the introduction of a lot of new technologies in JavaScript, but we needed time to see how the market was going to adopt them. Nobody wants to be the specialist on another promising technology that ends with zero adoption. Now, however, is the time to take another look. In this article, I will take a look at how popular JavaScript is becoming and the factors that may have affected this popularity, and I will try to predict what the future of JavaScript will look like.

The Future of JavaScript Language Features

Since the European Computer Manufacturers Association (ECMA) established the year-based release cycle for ECMAScript, a standardized JavaScript specification, we haven’t seen a lot of new features coming to the language—just a few each year. This could be one of the reasons we saw an increase of adoption of languages that compile to ES5 like TypeScript or ReasonML, both bringing features to the language that are highly requested by the community. This is not new—JavaScript went through this process before (CoffeeScript) and, in the end, those features ended up being merged into the language standard itself, and that’s probably the future that we can expect for these new typed features, too.

But now we are starting to see a game changer move in the compile-to-js market with the increasing availability of WebAssembly in the browsers. Now, we can use almost any language and compile it to run at almost native speed in a browser and, more importantly, we are starting to see support for future-proof features like support for threads that will allow us to take advantage of the multi-processor architecture that represents the inevitable future of all devices.

The official toolchain for WebAssembly will help you to compile C/C++, but there are a lot of community provided compilers for different languages, like RustPythonJava, and Blazor (C#).

Particularly, the Rust community is pretty active and we started to see complete front-end frameworks like Yew and Dodrio.

This brings a lot of new possibilities to browser-based apps, and you only need to test some of the great apps built with WebAssembly to see that near-native browser-based apps are a reality now, e.g., Sketchup or Magnum.

Adoption of typed languages that compile to ES5 is mature enough, the players are well established, and they won’t disappear (or be merged with ES) in the near future, but we’ll see a slow shift in favor of typed languages with WebAssembly.

Web

Front-end Frameworks

Every year, we see a big fight on the front-end frameworks market for the web, and React has been the indisputable winner for the past few years—since the introduction of their game-changer technology, the Virtual DOM, we saw an almost obligated adoption from their counterparts in order to remain relevant in the battle.

Some years ago, we saw the introduction of a radical new approach to web application development with Svelte, the “compiler framework” that disappears at compile time leaving small and highly efficient JavaScript code. However, that feature was not enough to convince the community to move to Svelte, but with the recent launch of Svelte 3.0, they introduced real reactive programming into the framework and the community is thrilled, so perhaps we are witnessing the next big thing in front-end frameworks.

Inspired by the destiny operator:

var a = 10;
var b <= a + 1;
a = 20;
Assert.AreEqual(21, b);

Svelte brings reactivity to JavaScript by overloading the use of label statements with reactivity at compile time by instructing the code to be executed in topological order:

var a = 10;
$: b = a + 1;
a = 20;
Assert.AreEqual(21, b);

This is a radical new idea that might help in different contexts, so the creator of Svelte is also working on svelte-gl, a compiler framework that will generate low-level WebGL instructions directly from a 3D scene graph declared in HTMLx.

Needless to say that ReactAngular, and Vue.js won’t disappear overnight, their communities are huge, and they’ll remain relevant for several years to come—we are not even sure if Svelte will be the actual successor, but we can be sure of something: We’ll be using something different sooner or later.

WebXR and the Future of the Immersive Web

Virtual reality has been struggling for the past 60 years to find a place in the mainstream, but the technology was just not ready yet. Less than ten years ago, when Jon Carmack joined Oculus VR(now part of Facebook Technologies, LLC), a new wave of VR started to rise, and since then, we’ve seen a lot of new devices supporting different types of VR and of course the proliferation of VR-capable applications.

Browser vendors didn’t wanted to lose this opportunity, so they joined with the WebVR specification allowing the creation of virtual worlds in JavaScript with WebGL and well-established libraries like three.js. However, the market share of users with 6dof devices was still insignificant for massive web deployments, but the mobile web was still able to provide a 3D experience with the device orientation API, so we saw a bunch of experiments and a lot of 360 videos for a while.

In 2017, with the introduction of ARKit and ARCore, new capabilities were brought to mobile devices and all sorts of applications with AR and MR experiences.

However it still feels a little unnatural to download one specific app for one specific AR experience when you are exploring your world around you. If we could only have one app to explore different experiences… This sounds familiar. We solved that problem in the past with the browser, so why not give it another shot?

Last year, Mozilla introduced the WebXR Device API Spec (whose last working draft, at the time of this writing, is from two weeks ago) to bring AR, VR, and MR (ergo XR) capabilities to the browser.

A few of the most important browser vendors followed with their implementation, with an important exception: Safari mobile, so to prove their point, Mozilla released a WebXR capable browser under the iOS platform WebXR Viewer.

Now, this is an important step because the combination of AR and VR brings 6dof to mobile devices and mobile device-based headsets like Google Cardboard or the Samsung Gear VR, as you can see in this example, increasing the market share of 6dof devices by a large margin and enabling the possibility of a large-scale web deployment.

At the same time, the guys at Mozilla have been working on a new web framework to facilitate the creation of 3D worlds and applications called A-Frame, a component-based declarative framework with HTML syntax based on three.js and WebGL, having just one thing in mind—to bring back the fun and ease of use to web programming.

This is part of their crusade to the immersive web, a new set of ideas on how the web should look like in the future. Luckily for us, they are not alone, and we’ll start to see more and more immersive experiences on the web.

If you want to give it a try, go ahead download the WebXR Viewer and visit this site to see the possibilities of the immersive web.

Once again, standard browser-based apps won’t fade in a year or two—we’ll probably always have them. But 3D apps and XR experiences are growing and the market is ready and eager to have them.

Native Support for ES6

Almost every technology invented in JavaScript in the past decade was created to solve problems generated by the underlying implementation of the browsers, but the platform itself has matured a lot over these past few years, and most of those problems have disappeared, as we can see with Lodash, which once reigned the performance benchmarks.

The same is happening with the DOM, whose problems once were the actual inspiration for the creation of web application frameworks. Now, it is a mature API that you can use without frameworks to create apps—actually, that’s what web components are. They are the “framework” of the platform to create component-based apps.

Another interesting part of the platform evolution is the language itself. We’ve been using Babel.jsfor the past few years to be able to use the latest features of ECMAScript, but since the standard itself started to stagnate a little bit in the last few years, that was enough time to allow the browser vendors to implement most of their features, including native support of the static import statement. So now, we can start to consider the creation of applications without Babel.js or other compilers since we have (again) the support of the language features in the platform it self, and since Node.js uses the same V8 VM as Google Chrome, we’ve started to see stronger support of ES6 in Node.js, even with the static import statement under the experimental-modules flag.

This doesn’t mean that we’ll stop seeing apps being compiled at a professional level, but it means that starting with a browser-based application will be easy and fun as it once was.

Server-side JavaScript

Even though JavaScript started with server side in 1995 with the Netscape Enterprise Server, it wasn’t until Ryan’s Dahl presentation in 2009 that JavaScript started to be seriously considered for server-side apps. A lot of things happened in the past decade to Node.js. It evolved and matured a lot, creating once again the opportunity for disruption and new technologies.

In this case, it comes from the hand of its very own creator, Ryan Dahl, who has been working on a new perspective of server-side secured apps with Deno, a platform that supports natively the latest language features as async/await, and also the most popular compile-to-js language TypeScript, targeting the best performance thanks to their implementation in Rust and the usage of Tokio, but more importantly with a new security philosophy that differentiates it from most of the server-side platforms like PythonRuby, or Java). Inspired by the browser security model, Deno will let you use the resources of the host only after the user explicitly granted the permissions to the process, which might sound a bit tedious at the beginning, but it might result in a lot of implications by allowing us to run unsecured code in a secured environment by just trusting the platform.

Node.js will still be there in the future but may be we’ll start to see serverless services like AWS Lambda and Azure Functions to provide the Deno functionality as an alternative to provide unsecured server-side code execution on their systems.

 

writer : ALEJANDRO HERNANDEZ

source: https://www.toptal.com/javascript/predicting-javascript-future