ES6 default parameters? - javascript

I'm trying to use default parameter values, but getting this error:
SyntaxError: Unexpected token =
Is this working in node now? I'm using 5.9.1
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/default_parameters
I also tried messing with passing flags to node without success.
node --harmony_default_parameters
It seems like a basic part of ES6 so hope it would be working by now!

Is this working in node now?
Not yet. It's only available for testing under a flag. V8 v4.9 (released in Chrome 49) is the earliest stable version of V8 that supports default parameters. Nodejs v5.9.1 runs on top of V8 v4.6.85.31. You can use the command node -p process.versions.v8 for checking the current V8 version. Also, you have to wait until Nodejs v6.x for a complete support of default parameters. You can see this issue for more details.

The problem seems to be a result of mixing ES6 style functions:
getReply: (input, userId = null) => { // No good
getReply: function(input, userId = null) { // OK

You can find the list of what ES6 features are currently supported by Node here. As it stands, it doesn't look like default paremeters are implemented, or at least not fully.

Related

jest is failing to find `bota` and `atob`

Creating a jest test like:
test("btoa", () => {
expect(btoa("aaa")).toStrictEqual("YWFh");
});
fails with
ReferenceError: btoa is not defined
however, node does define btoa as of node 16, and so the following:
console.log(bota("aaa"))
correctly outputs YWFh.
How can I configure jest to get this test to pass? Clearly something is happening in the jest test runner to not execute in the current node environment, or otherwise is stripping specific built-ins, only I can't seem to find any documentation on how to debug or adjust this.
Update
There are work arounds by writing the encoding manually in "pure js" or depending on something that's similar, but I'm particularly interested in why the jest execution ending is failing to find built-ins that seem to be present in other environments.
This also works fine in other testing frameworks like mocha, so it's clearly related to the jest runner in particular.
Update
After much searching and head scratching as to why btoa/atob are available in node but NOT available in jest running in node, I finally figured it out. Jest runs all tests inside a vm, which is an isolated sandbox environment. The btoa/atob methods are not automatically exposed on the global object inside of a VM. Best explained by example:
const vm = require('vm');
// this works outside the vm - but for legacy reasons only
// you shouldn't be doing this in the first place
btoa('aaa'); // -> "YWFh"
const context = vm.createContext({});
const code = 'btoa("aaa")';
vm.runInContext(code, context); //-> Uncaught ReferenceError: btoa is not defined
Note: The answer described below is still the "solution" - you need to define these methods for use in node, and then you need to expose them using jest's globalSetup.
Original answer
The root of your problem is the fact that NodeJS and web browsers have different APIs. For example, I get this deprecation notice when I try to use btoa in my node application.
The first part of the solution is that you need to provide your own atob/btoa methods for use in NodeJs (see examples here). Then you need to make these available using jest's globalSetup config:
/** Encodes a string as base64 format */
global.btoa = (str: string) => Buffer.from(str, 'binary').toString('base64');
/** Decodes a base64 encoded string */
global.atob = (str: string) => Buffer.from(str, 'base64').toString('binary');
If you don't feel comfortable doing this yourself, there are libraries and tools out there that do it for you (jsdom, phantomjs, testing-library). These libraries essentially replicate the browser APIs in a node environment for doing things like running tests, server-side rendering, etc. I recommend reading about testing web frameworks for code examples and techniques.

Syntax error, node.js with the following "Object.keys(colors).forEach((code) => " [duplicate]

Is Node.js supporting => function keyword alias already? If yes, starting from which version? How to enable this language extension?
(function() { console.log('it works!') })()
Becomes
(() => { console.log('it works!') })()
In short: yes, arrow functions are reasonably well supported in Node.js since version 4.4.5.
Completely correct support starts with version 6. Initial support was introduced as far as v0.12 but is was very incomplete and disabled by default until v4.0 when it got better. See Node's ES6 compatibility table for details: http://node.green/#ES2015-functions-arrow-functions.
The syntax you're referring to is "arrow function" syntax. It is a feature of ECMAScript 6, also known as "Harmony". The ES6 standard is now finalized, but engines are still implementing its new features.
The V8 now has arrow function support. Node runs on the V8 engine, but it can take some time for Node to incorporate the latest version into its code base.
Whenever it is added, it might possibly be enabled only via a --harmony command-line flag.
You can follow this issue: https://code.google.com/p/v8/issues/detail?id=2700
Currently (as 02.05.2014) arrow functions have been implemented and waiting until this functionality will be landed in v8: https://codereview.chromium.org/160073006/
After then we'll need to wait, until v8 version with arrow function would be integrated into Node.JS. You can follow Node.JS changelog there: https://github.com/joyent/node/blob/master/ChangeLog (search for "v8: upgrade to ....")
kangax's compatibility tables can keep you up-to-date with what is currently available in Node.
Experimental features can be enabled using the instructions on this page:
All shipping features are turned on by default on Node.js
Staged feature require a runtime flag: --es_staging (or its synonym, --harmony)
In progress features can be activated individually by their respective harmony flag (e.g. --harmony_destructuring) but this is highly discouraged

How to get rid of editor’s error for object.key

I have the following code that basically gets some JSON data, looks for the keys with "servergenre", and saves the results in an array.
This is a follow up of this question.
let result = [];
Object.keys(data).forEach( key => {
if(/servergenre/.test(key)){
result.push(data[key])
}
});
Even though the code is working correctly, in some editors it raises syntactic errors:
"key": unsolvable variable or type key
"=>": expression expected
"if( / server...": formal parameter name expected
")){": , expected
"});": statement expected
Here is an image to show you where the errors are:
As I said the code is working fine, I just need it to be fixed or another approach to get rid of the errors.
Furthermore, many compressors and minifiers do not support this bit of code. So I can’t minify it.
Thanks in advance.
ES2015, formerly known as ES6, is a more recent version of JavaScript, which introduces features such as the => syntax for functions you are using.
Not all features of ES2015 are fully supported in all browsers, so many people who use it pass it through a compiler (“transpiler”) first to convert it to ES5, which is supported by all browsers. Babel is one such transpiler. But if you are only targeting newer browsers, that would explain why the => syntax is working for you.
You just need to change your editor settings to understand that syntax. Exactly how you do that depends on what text editor you are using. It could be that your editor's built-in JavaScript mode doesn't know how to read ES2015 syntax, and you need to either upgrade your editor or install a third-party plugin that provides an updated error-checker. Or it could be that your editor supports both ES5 and ES2015, and it thinks you are trying to write your project only in ES5. In this case you just need to go to the settings and tell your editor that you mean for this project to use ES2015 (or ES2016, which is currently the most recent version).
Fat arrows are ES6 syntax. If that causes trouble, just write good old ES5 :
let result = [];
Object.keys(data).forEach( function(key) {
if(/servergenre/.test(key)){
result.push(data[key])
}
});

Foundation Sites (6) javascript order

I am utterly confused as how to insert individual foundation javascript. it always seem to break my code. for example I need to use the dropdown menu js. in the documentation it state
Initializing
The file foundation.dropdownMenu.js must be included in your JavaScript to use this plugin,
along with foundation.core.js.
This plugin also requires these utility libraries:
foundation.util.keyboard.js
foundation.util.box.js
foundation.util.nest.js
this seem simple enough so I did the following in this order
bower_components/foundation-sites/js/foundation.core.js //check
bower_components/foundation-sites/js/foundation.util.mediaQuery.js
bower_components/foundation-sites/js/foundation.util.timerAndImageLoader.js
bower_components/foundation-sites/js/foundation.util.keyboard.js //check
bower_components/foundation-sites/js/foundation.util.box.js //check
bower_components/foundation-sites/js/foundation.util.nest.js //check
bower_components/foundation-sites/js/foundation.dropdown.js
bower_components/foundation-sites/js/foundation.dropdownMenu.js //check
bower_components/foundation-sites/js/foundation.equalizer.js
I follow what logical for me core 1st than util than plugin
yet it told me foundation.util.nest.js:6 Uncaught SyntaxError: Unexpected token =
if I put all foundation.min.js file the error go away, so I know it must be a dependency is missing or the order is not correct
is there any resource out there that is clear on the dependency of foundation js? instead everytime I have to trail and error it.
I'm having the same issue on my end. I am using Foundation as a GIT subtree in my project and actually have used this on a site I made just last week.
It seems that the problem is a newer version of function parameter declarations. In the code I had working, v6.1.2, the code in foundation.util.nest.js is:
Foundation.Nest = {
Feather: function(menu, type){
menu.attr('role', 'menubar');
type = type || 'zf';
versus the code in the newest version 6.2.0 which is:
const Nest = {
Feather(menu, type = 'zf') {
menu.attr('role', 'menubar');
It's that default/fallback declaration of "type" that seems to ruin everything. I look forward to a fix myself.
According to this link, my current version of Chrome (48) doesn't yet support default function parameters.
As of Foundation v6.2.0 the JavaScript codebase has been updated to ES6.
https://github.com/zurb/foundation-sites/releases
You'll need to add Babel to your build process to compile the ES6 code.
They have supplied a tutorial for this here:
https://github.com/zurb/foundation-sites/wiki/Upgrading-to-Foundation-6.2
Hope this helps.

Parse can't find localStorage variable in React Native

I have a React Native app that works fine with the Chrome debugger open. Once I disable it though, I keep getting the following error whenever I try to make any Parse calls:
The call stack leads back to the following code attempting to log a user in:
Parse.User.logIn(
email,
password,
{
success: function(res) {
console.log('success');
},
error: function(error) {
console.log(error.code + ' ' + error.message);
}
}
);
I've tried removing the console statements, in case the error had to do with the console not being available, but no avail. This happens with other Parse calls, and always has to do with the missing localStorage variable.
Thanks in advance for any help!
UPDATE:
Looks like there is a similar issue with Firebase. https://groups.google.com/forum/#!topic/firebase-talk/Y_usPRhOIYA
They mention that the problem has to do with there not being a polyfill for localStorage.
The answers above are technically right, but Parse has provided a solution that doesn't require a polyfil or downgrading. This was due to my perpetual lack of reading. I found this on the Parse React docs:
As of version 1.6, the Parse JS SDK has a different build for React
Native. If you're using Parse+React on React Native, you'll need to
require the 'parse-react/react-native' package instead.
For example:
// For React Native apps
var React = require('react-native');
var Parse = require('parse/react-native');
var ParseReact = require('parse-react/react-native');
Sorry for not mentioning I was using Parse React as well. I thought the problem was just with Parse, as I hadn't begun to add data subscriptions via Parse React.
That's correct (with polyfill). There is no localStorage added as polyfill nor the Apple's embedded javascriptCore engine has localStorage implemented (where Chrome's v8 has it implemented of course). Main reason is that localStorage is synchronous and React should only work with asynchronous operations by design.
There is a nice solution/mini-polyfill that replaces localstorage with an in-memory version: https://gist.github.com/juliocesar/926500 . That should let parse use localstorage for cache (that's the main purpose they are using it now I believe). The data will not be persistently stored between application executions. I am not sure if you can disable localstorage use by Parse, but that's another possibility to explore.
I downgraded to 1.5.0 and working now.
"dependencies": {
"parse": "1.5.0",
I do not think that even being forced to use Parse+React is a good enough solution. For example I am building my app with Redux, it makes a lot more sense for me to keep all of my API Requests inside my action creators.
In 1.6.0 Parse is forcing us to use Local Storage, when React Native does not support it. React Native does however support AsyncStorage.
For me I just downgraded to 1.5, hopefully they will give an option to use Local Storage or Async Storage in the future.
So people that stumble upon this and would not like to be forced to use Parse+React your answer is to downgrade to 1.5, in your package.json change your dependencies to "parse": "1.5.0".
This problem can easily be fixed by:
npm install localstorage-polyfill
and then in App.js
import 'localstorage-polyfill';
EDIT: this error potentially means you have outdated or incompatible library dependencies. You can try to reinstall with rm -rf node_modules; npm install

Categories

Resources