Skip to content

ES6 Features in JXA

Thadeu Luz edited this page Feb 21, 2018 · 11 revisions
← previous · · · · · · · · · · · · · · next →

Update: As of macOS Sierra, the JXA JavaScriptCore is that from Safari ~10.1, which supports not only 100% of ECMAScript 6, according to Kangax's table, but even parts of ES2017 (‘ES7’), like async functions! Go wild, if your scripts will only ever run on Sierra and above. (=

From my experimentation, it turned out that JXA supports some ES6 features!

Support for javascript language features is dependent on the version of OSX. JXA uses a version of the JavaScriptCore engine that seems to correspond with the version of Safari that is bundled with the OS. So in Yosemite, it's Safari 8. In El Capitan, it's Safari 9. See kangax's compatibility table and find the "SF" columns to see the language support for different versions of Safari.

Spread operator

Allows you to explode array into arguments:

var array = [1, 2, 3]
f(...array)
var a = [1, 2, 3, 4]
var b = [5, 6, 7, 8]
var concated = [...a, ...b]

concated
#    => [1, 2, 3, 4, 5, 6, 7, 8]

But you cannot do it the other way around, sadly.

Array and Object Destructuring

var a = 1
var b = 2

[a, b] = [b, a]
#    => [2, 1]

a
#    => 2
b
#    => 1
var object = { cat: 1, dog: 2 }
var { cat, dog } = object

cat
#    => 1
dog
#    => 2

String Interpolation

You can use ES6 template literals in JXA.

var name = "Brandon"
console.log(`Hi, ${name}!`)
#    =>  Hi, Brandon!

Arrow functions

Arrow function do work but there's a catch.

const a = () => 1

a()
#    => 1

If creating a shebang file, this will work

#!/usr/bin/env osascript -l JavaScript

// Works
function run(argv) {
  console.log(JSON.stringify(argv));
}

But this will not

#!/usr/bin/env osascript -l JavaScript

// Will not run
const run = argv => {
  console.log(JSON.stringify(argv));
};
← previous · · · · · · · · · · · · · · next →
You can’t perform that action at this time.