1

The following code works on browsers but not in Node.js. Why?

[a, b] = 'hey,there'.split(',');
console.log(a);

2 Answers2

3

ES6 allows something called destructuring assignments. (Nicely explained here. And here is a link to the draft spec. ) That's what you've got in your code.

It looks like it is an ES6 feature that Firefox has adopted early. (Maybe too early). Unfortunately, this is par for the course with JavaScript runtimes. Many of them give access to features from upcoming specs ahead of time. You've got to keep your eyes peeled to make sure you're not using something that has not quite yet been officially adopted.

Louis
  • 146,715
  • 28
  • 274
  • 320
  • Firefox didn't add the ES2015 feature early, ES2015 added a feature Firefox had had for nine years. :-) (Specifically, destructuring assignment was [in Firefox 2](https://en.wikipedia.org/wiki/SpiderMonkey#Versions) in 2006.) During the 1999-2009 gap in specifications (because people in different organizations couldn't agree on what direction to go), Mozilla's dialect of JavaScript got many features, some of which ended up in ES2015 (in some cases, markedly changed). – T.J. Crowder Jul 22 '20 at 15:51
  • It's also worth noting that since you posted your answer, [the process](https://tc39.es/process-document/) has changed to *ensure* that features are in implementations (like Firefox and/or Chrome and/or Node.js and/or Safari, etc.) before they're in the spec. :-) – T.J. Crowder Jul 22 '20 at 15:53
  • @T.J.Crowder Thanks for the clarifications. – Louis Jul 22 '20 at 18:54
2

Your code is considered in ECMAscript 6.This is called array destructuring. You can see its features here https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7

your code will run on current version of Firefox (28) but not Google chrome (33) you can check the compatibility of you browser from this site http://kangax.github.io/es5-compat-table/es6/

If you want to run it in Google-chrome there's a flag named Enable Experimental JavaScript appeared in the chrome://flags ==> make this flag = true then you can run it

NodeJs support ECMASript 6 but you will run it using the following command

node --harmony yourapp.js

Tareq Salah
  • 3,720
  • 4
  • 34
  • 48