Arrow function "expression expected" syntax error - javascript

I want to transform this code:
var formatQuoteAmount = function (tx) {
return Currency.toSmallestSubunit(tx.usd, 'USD');
};
var quoteAmounts = res.transactions.map(formatQuoteAmount);
into an anonymous arrow function. I've written this:
var quoteAmounts = res.transactions.map(tx => Currency.toSmallestSubunit(tx.usd, 'USD'));
I get expression expected syntax error at the arrow. I looked up the default syntax here and seems like the syntax of my code is correct. Any ideas what the problem might be?
I have it working with this syntax:
var quoteAmounts = res.transactions.map(function (tx) {
return Currency.toSmallestSubunit(tx.usd, 'USD')
});
but I want to make it a one-liner, with an arrow-function.
Running on node v5.3.0

I had the error expression expected reported by Webstorm when editing a Node.js program. In this case the solution is to set the language version to a version that supports this feature.

The following is what i did that work for me.
(1) I change the JavaScript language option to ECMAScript 6 as show in the selected answer by #Joe23
(2) I close the Webstorm project/application.
(3) Navigate to the project folder and delete the .idea folder in it. I believe this is the folder webstorm generated to keep information about the project/application.
(4) I reopen my project in webstorm and the errors are gone.

Arrow functions are available by default on the latest versions of node and other javascript runtimes. You need to enable support for them only if you're dealing with a really old runtime (0.12 and earlier if I recall correctly) in which case you need to add the "--harmony" flag when you start the node process.

Related

Our Java web application stopped showing the map when running on Internet Explorer 11 [duplicate]

I am using this jquery popup plugin from this link on my WordPress site. It's working fine on all browsers but giving the following error on IE11.
As others have mentioned, the Object.assign() method is not supported in IE, but there is a polyfill available, just include it "before" your plugin declaration:
if (typeof Object.assign != 'function') {
Object.assign = function(target) {
'use strict';
if (target == null) {
throw new TypeError('Cannot convert undefined or null to object');
}
target = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source != null) {
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
}
return target;
};
}
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Test page: http://jsbin.com/pimixel/edit?html,js,output (just remove the polyfill to get the same error you're getting on your page).
#John Doe
I figured out from your comment that you want to implement this in node/react stack. This is very different from original question and you should have asked your own ;)
Anyways, Heres what you need to do...
You can use [es6-object-assign][1]. It is an ES6 Object.assign() "polyfill".
First, in package.json in your root folder, add es6-object-assign as a dependency:
"dependencies": {
"es6-object-assign": "^1.0.2",
"react": "^0.12.0",
...
},
Then if you want to use it in node environment use:
require('es6-object-assign').polyfill();
If you are having the issue on front (browser) end...
Add it in your index.html file...
<script src="location_of_node_modules/es6-object-assign/dist/object-assign.min.js"></script>
<script>
window.ObjectAssign.polyfill();
</script>
location_of_node_modules depends on boilerplate you use, mostly just node_modules, but sometimes when index.html is in a subdirectory you need to use, ../node_modules
As per the documentation, Object.assign() is a new technology, part of the ECMAScript 2015 (ES6) standard:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
And it is not supported by IE.
A possible solution for this problem:
Add the script legacy.min.js before the custombox.min.js
source: custombox github project
#Andres-Ilich has the right answer to your question but you're asking the wrong question:
Why not just use a jQuery plugin that supports IE like Zurb's excellent Reveal: https://github.com/zurb/reveal
It will do everything you want and not throw this error.
Currently working on a jQuery popup myself:
https://github.com/seahorsepip/jPopup
Has everything you'd expect of a popup and more :D
Anyway back on topic, I'm currently writing version 2 which is a big rewrite and adds support for IE6 (version 1 was IE7+) and ran into a similiar error...
Original code that gave the error in IE6:
//Insane code for an insane browser
this._vars.fakeScrollbar = $("<div style=\"position:absolute;top:expression(document.documentElement.scrollTop);right:0;bottom:0;margin-left:-200px;width:0;overflow-y:scroll;height:expression(document.documentElement.clientHeight);z-index:9999999;\"></div>");
The hack I had to come up with:
//Insane code for an insane browser
this._vars.fakeScrollbar = $("<div>");
this._vars.fakeScrollbar.html("<div style=\"position:absolute;top:expression(document.documentElement.scrollTop);right:0;bottom:0;margin-left:-200px;width:0;overflow-y:scroll;height:expression(document.documentElement.clientHeight);z-index:9999999;\"></div>");
this._vars.fakeScrollbar = this._vars.fakeScrollbar.children();
Since you tagged the question with jQuery you can use the jQuery extend function. No need for a polyfill and it does deep merge as well.
For Example:
var object1 = {
apple: 0,
banana: { weight: 52, price: 100 },
cherry: 97
};
var object2 = {
banana: { price: 200 },
durian: 100
};
// Merge object2 into object1
$.extend( object1, object2 );
Result:
{"apple":0,"banana":{"price":200},"cherry":97,"durian":100}
please add script
<script src="https://cdn.jsdelivr.net/npm/es6-object-assign#1.1.0/dist/object-assign-auto.min.js"></script>
to html file to resolved this problem.
These error usually occurs when some html element id has the same id as some variable in the JavaScript function. After changing the name of one of them code worked.
Source : SCRIPT438: Object doesn't support property or method IE
Other link : jquery validation IE Object doesn't support property
Basically, Object.assign isn't supported by all browsers, however, it's possible to re-assign it at Object case it's not supported by the current browser.
It's pratice to make a polyfill function, which behaves in the same way as Object.assign(target, ...) of ES6.
I think the best solution is to iterate each argument after target, assign each property of arguments objects to target, considering a iteration between objects and arrays, to avoid creating references. Optionally, to not lost instances, you can detect if the last instance of the property is only equal to "Array" or "Object", and doing so you won't lost a Image interface (e.g) if you plan to create new references, but objects with these instances will still be reference.
Edit: the original Object.assign doesn't work in this way.
According to this solution, I've my own polyfill which can be found here.
React solution for IE11
Regarding shramee's answer, which stated something like this:
#JohnDoe from your comment, you want to implement this in node/react stack. This is very different from the original question, but you might use es6-object-assign, an ES6 Object.assign() "polyfill":
This polyfill was updated and things can be done a bit differently now:
in package.json in your root folder, add es6-object-assign as a dependency (executing npm i in a command line after):
"dependencies": {
"es6-object-assign": "^1.0.2",
"react": "^16.8.6",
...
},
Or simply run: npm i --save es6-object-assign
To use it in a node environment:
require('es6-object-assign').polyfill();
// Same version with automatic polyfilling
require('es6-object-assign/auto');
To use it in your index.html, just add the automatic polyfill JS file reference to it (if you have scripts in the <body> that invoke Object.assign() you may add it at the end of the <head> element).
Invoking directly from node_modules:
<script src="location_of_node_modules/es6-object-assign/dist/object-assign-auto.min.js"></script>
location_of_node_modules depends on your project structure (when index.html is in a subdirectory you might need: ../node_modules).
However, this might have not worked for you (due to node_modules folders access, e.g. you are using create-react-app). If so, just copy the JS file from the dist/ node_modules folder to the public/ folder and then:
<script src="%PUBLIC_URL%/object-assign-auto.js"></script>
You might want to use the non-minified file and add other customized polyfills (e.g. startsWith).

An object disappears after packing a JavaScript library

I have created a JavaScript library and packed it with these options selected : Shrink Variables and Base62 Encoded at this url: http://dean.edwards.name/packer/. In this library I have declared an object ax, but when I use the packed version in my web page I get an error saying Uncaught ReferenceError: ax is not defined.
The original code of this library looks like below.
var ax = {
scaleUp:function(win) {
//code omitted
},
downGrade:function(win) {
//code omitted
}
}
In my web page in which I am using this library, I have code like below. This code works, if instead of packing, I minify it using Microsoft's Minifier or just use the original JavaScript library without minification or packing.
var result = ax.downGrade(w);
Question :
Why is the variable ax not accessible with packed version? Do I need to add something else when using the packed version?
UPDATE 1:
I could not get the packed file to work but packing my code through another compression utility at following url worked in my case: http://jsutility.pjoneil.net/. It provided an equally good compression.
I am still not sure why the utility at original url failed to produce a working version of my library, even though my original code works without any errors on any web page.
Check your console for errors before trying to call ax. Explicitly place semi-colons where they belong.Example at the end of the definition for ax you should put a semi-colon, even though in standard code it's good as is. Remove the explicit var declarations. When I did these things:
ax = {
scaleUp:function(win) {
alert("up");
},
downGrade:function(win) {
alert("down");
}
};
result = ax.downGrade();
Ran without issue in jsFiddle and console: http://jsfiddle.net/7kdnw65n/. I suspect it has to do with how the algorithm "shrinks" the variables. The resulting pack was:
eval(function(p,a,c,k,e,r){e=String;if(!''.replace(/^/,String)){while(c--)r[c]=k[c]||c;k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('0={5:1(2){3("6")},4:1(2){3("7")}};8=0.4();',9,9,'ax|function|a|alert|downGrade|scaleUp|up|down|result'.split('|'),0,{}))

How can I attach an event handler to the process's exit in a native Node.js module?

I'm working on implementing correct memory management for a native Node.js module. I've ran into the problem described in this question:
node.js native addon - destructor of wrapped class doesn't run
The suggested solution is to bind the destructors of native objects to process.on('exit'), however the answer does not contain how to do that in a native module.
I've taken a brief look at the libuv docs as well, but they didn't contain anything useful in this regard, either.
NOTE: I'm not particularly interested in getting the process object, but I tried it that way:
auto globalObj = NanGetCurrentContext()->Global();
auto processObj = ::v8::Handle<::v8::Object>::Cast(globalObj->Get(NanNew<String>("process")));
auto processOnFunc = ::v8::Handle<::v8::Function>::Cast(processObj->Get(NanNew<String>("on")));
Handle<Value> processOnExitArgv[2] = { NanNew<String>("exit"), NanNew<FunctionTemplate>(onProcessExit)->GetFunction() };
processOnFunc->Call(processObj, 2, processOnExitArgv);
The problem then is that I get this message when trying to delete my object:
Assertion `persistent().IsNearDeath()' failed.
I also tried to use std::atexit and got the same assertion error.
So far, the best I could do is collecting stray ObjectWrap instances in an std::set and cleaning up the wrapped objects, but because of the above error, I was unable to clean up the wrappers themselves.
So, how can I do this properly?
I was also getting the "Assertion persistent().IsNearDeath()' failed" message.
There is a node::AtExit() function that runs just before Node.js shuts down - the equivalent of process.on('exit').
Pass a callback function to node::AtExit from within your add-on's init function (or where ever is appropriate).
The function is documented here:
https://nodejs.org/api/addons.html#addons_atexit_hooks
For example:
NAN_MODULE_INIT(my_exports)
{
// other exported stuff here
node::AtExit(my_cleanup);
}
NODE_MODULE(my_module, my_exports) //add-on exports
//call C++ dtors:
void my_cleanup()
{
delete my_object_ptr; //call object dtor, or other stuff that needs to be cleaned up here
}

"Error calling method on NPObject!" in Uploadify

I'm using Uploadify to upload file in my CMS. Everything works fine until recently. I got an error
Error calling method on NPObject
on this line
document.getElementById(jQuery(this).attr('id') + 'Uploader').startFileUpload(ID, checkComplete);
on this part
uploadifyUpload:function(ID,checkComplete) {
jQuery(this).each(function() {
if (!checkComplete) checkComplete = false;
document.getElementById(jQuery(this).attr('id') + 'Uploader').startFileUpload(ID, checkComplete);
});
},
I don't know why and after a day debugging and testing I found that if I remove replace(/\&/g, '\\&') from
String.prototype.escAll = function(){
var s = this;
return s.replace(/\./g, '\\.').replace(/\?/g, '\\?').replace(/\&/g, '\\&');
};
It then works again. I really don't know why.
Any helps would be appreciated!
I think the reason is in additional Javascript libraries you use.
Some libraries (for example Prototype.js or jQuery.js) change behaviour of your code. For example, you can't overload prototype in some cases. The result may be undefined in clear (obvious) places (like you use an array variable with wrong index). You should view the source code of additional libraries, probably they do with prototype something that breaks your code in the function you mentioned.
In my practice I had the situation when overloading of prototype worked incorrectly (it was String prototype like in your case).
So just don't use prototype.

Why is my JavaScript function sometimes "not defined"?

I call my JavaScript function. Why do I sometimes get the error 'myFunction is not defined' when it is defined?
For example. I'll occasionally get 'copyArray is not defined' even in this example:
function copyArray( pa ) {
var la = [];
for (var i=0; i < pa.length; i++)
la.push( pa[i] );
return la;
}
Function.prototype.bind = function( po ) {
var __method = this;
var __args = [];
// Sometimes errors -- in practice I inline the function as a workaround.
__args = copyArray( arguments );
return function() {
/* bind logic omitted for brevity */
}
}
As you can see, copyArray is defined right there, so this can't be about the order in which script files load.
I've been getting this in situations that are harder to work around, where the calling function is located in another file that should be loaded after the called function. But this was the simplest case I could present, and appears to be the same problem.
It doesn't happen 100% of the time, so I do suspect some kind of load-timing-related problem. But I have no idea what.
#Hojou: That's part of the problem. The function in which I'm now getting this error is itself my addLoadEvent, which is basically a standard version of the common library function.
#James: I understand that, and there is no syntax error in the function. When that is the case, the syntax error is reported as well. In this case, I am getting only the 'not defined' error.
#David: The script in this case resides in an external file that is referenced using the normal <script src="file.js"></script> method in the page's head section.
#Douglas: Interesting idea, but if this were the case, how could we ever call a user-defined function with confidence? In any event, I tried this and it didn't work.
#sk: This technique has been tested across browsers and is basically copied from the Prototype library.
I had this function not being recognized as defined in latest Firefox for Linux, though Chromium was dealing fine with it.
What happened in my case was that I had a former SCRIPT block, before the block that defined the function with problem, stated in the following way:
<SCRIPT src="mycode.js"/>
(That is, without the closing tag.)
I had to redeclare this block in the following way.
<SCRIPT src="mycode.js"></SCRIPT>
And then what followed worked fine... weird huh?
It shouldn't be possible for this to happen if you're just including the scripts on the page.
The "copyArray" function should always be available when the JavaScript code starts executing no matter if it is declared before or after it -- unless you're loading the JavaScript files in dynamically with a dependency library. There are all sorts of problems with timing if that's the case.
My guess is, somehow the document is not fully loaded by the time the method is called. Have your code executing after the document is ready event.
Verify your code with JSLint. It will usually find a ton of small errors, so the warning "JSLint may hurt your feelings" is pretty spot on. =)
A syntax error in the function -- or in the code above it -- may cause it to be undefined.
This doesn't solve your original problem, but you could always replace the call to copyArray() with:
__args = Array.prototype.slice.call(arguments);
More information available from Google.
I've tested the above in the following browsers: IE6, 7 & 8B2, Firefox 2.0.0.17 & 3.0.3, Opera 9.52, Safari for Windows 3.1.2 and Google Chrome (whatever the latest version was at the time of this post) and it works across all browsers.
If you're changing the prototype of the built-in 'function' object it's possible you're running into a browser bug or race condition by modifying a fundamental built-in object.
Test it in multiple browsers to find out.
This has probably been corrected, but... apparently firefox has a caching problem which is the cause of javascript functions not being recognized.. I really don't know the specifics, but if you clear your cache that will fix the problem (until your cache is full again... not a good solution).. I've been looking around to see if firefox has a real solution to this, but so far nothing... oh not all versions, I think it may be only in some 3.6.x versions, not sure...
Solved by removing a "async" load:
<script type="text/javascript" src="{% static 'js/my_js_file.js' %}" async></script>
changed for:
<script type="text/javascript" src="{% static 'js/my_js_file.js' %}"></script>
Use an anonymous function to protect your local symbol table. Something like:
(function() {
function copyArray(pa) {
// Details
}
Function.prototype.bind = function ( po ) {
__args = copyArray( arguments );
}
})();
This will create a closure that includes your function in the local symbol table, and you won't have to depend on it being available in the global namespace when you call the function.
This can happen when using framesets. In one frame, my variables and methods were defined. In another, they were not. It was especially confusing when using the debugger and seeing my variable defined, then undefined at a breakpoint inside a frame.
I'm afraid, when you add a new method to a Function class (by prtotyping), you are actually adding it to all declared functions, AS WELL AS to your copyArray(). In result your copyArray() function gets recursivelly self-referenced. I.e. there should exist copyArray().bind() method, which is calling itself.
In this case some browsers might prevent you from creating such reference loops and fire "function not defined" error.
Inline code would be better solution in such case.
I think your javascript code should be placed between tag,there is need of document load

Categories

Resources