I am new to javascript. I have two documents--an old and a new--that I am comparing. However, I am getting a syntax error somewhere in the code below.
Somewhere in here, my code is blowing up. The error says "expression does not eval to a function." Any syntactic ideas of where I'm writing an incorrect statement?
if(userCtx.name != oldDoc.Document.attributeA) {
for (var key in oldDoc.Document)
{
if(newdoc.Document.hasOwnProperty('key')
{
if(oldDoc.Document[key] != newDoc.Document[key])
{
if(key === 'attributeB')
{
return;
}
else
{
throw(forbidden: 'Only admins may change this field.')
}
}
}
}
}
if(newdoc.Document.hasOwnProperty('key') <-- I am missing a )
To throw an object literal, replace the round brackets with curly brackets:
throw {
forbidden: 'Only admins may change this field.'
};
Is the code you posted inside of a function definition? I've seen that error when defining functions that get passed as arguments to something else, and forgotten to wrap the function in parenthesis.
For example:
"compare": "function(docA, docB) { ... }"
should be:
"compare": "(function(docA, docB) { ... })"
And possibly one more...
Is this inside a function? If not you might be getting an error on the return;
Related
This code given below is supposed to evaluate if a value coerces to true or false. How does this work? for example if I want to know if a string- "my string" will be coereced to true or false, how do I use the to determine that?
I have tried to replace val in the code below with "my string" everywhere val shows up
function logTruthiness (val) {
if (val) {
console.log("Truthy!");
} else {
console.log("Falsy.");
}
}
function logTruthiness ("my string") {
if ("my string") {
console.log("Truthy!");
} else {
console.log("Falsy.");
}
}
error
function logTruthiness ("my string") {
SyntaxError: Unexpected string
You could submit a value directly to it:
logTruthiness("my string");
You could also submit a variable:
let str = "my string";
logTruthiness(str);
But you don't want to change the function declaration itself (which is what you did by trying to modify the parameter to a pre-defined string)
Actually I figured out the answer after reading about functions.
So the function is kind of chain of commands that will be executed, one has to provide the value after declaring the function.
Thanks for the patience.
hullo all,
jslint is mad at me.
i'm making a function within a loop, but i'm also not quite sure how to fix it, since it seems i would need to curry the result such that the function matches the signature expected by request for a callback as well as perform variable capture correctly or perform some other javascript devilry to simplify that.
edit: the code as it is works fine. i'd just like to know how to make it so the linter isn't made at me anymore!
the section of code looks like the following:
function func(cb) {
request({ params }, (error, response) => {
const devices = response.body;
let completedCounter = 0;
for (const device of devices) {
request({ params }, (err, response) => {
if (!err && response.statusCode === 200) {
completedCounter += 1;
if (completedCounter === devices.length) {
cb(null, "message here");
}
} else {
cb(err, "message here");
}
});
}
});
}
sorry if my terminology isn't typical javascript terminology- i'm a confused c++/python/lisp programmer outside his comfort zone!
the linter output is:
39:10 error Don't make functions within a loop no-loop-func
I'm not exactly sure what you're trying to do in the code, as there are parts missing (or parts that are gratuitous, which I've commented or stubbed out, below), but this lints in the most recent version of JSLint.
/*jslint node, es6, for, white */
var request = require("request");
function func(cb) {
"use strict";
var params = {};
// See https://plus.google.com/108103301822680819489/posts/ZWBUMhYGcrH
request(params, function (ignore, response) {
const devices = response.body;
var completedCounter = 0;
Object.keys(devices).forEach(function(/*k*/) {
// var device = devices[k]; // `device` is unused, so we need neither it nor `k`, above
var params2 = {};
request(params2, function (err, response2) {
if (!err && response2.statusCode === 200) {
completedCounter += 1;
if (completedCounter === devices.length) {
cb(null, "message here");
}
} else {
cb(err, "message here");
}
});
});
});
}
func(); // Needs to be used or exported somehow.
Farts/Arrow Notation in JSLint
JSLint does want a "fart" (arrow notation) to return in a single line. Otherwise, JSLint prefers you use function ( notation to make what you're doing more clear.
Check the discussion here, at the JSLint discussion group. Crockford demonstrates what I suggest, above, and then Lee Chase adds...
Arrow functions have a problem with { }, mainly is it a multiline
function or an object.
As it happens your function returns nothing as multiline arrow
functions need a return.
That makes some sense. And the OP at that link makes precisely the mistake JSLint is trying to help you avoid. That is, the stylistic error did in fact (in that case) cause a functional one.
Your "function in a loop" issue
Using forEach with Object.keys, another set of JSLint recommendations (Object.keys and for) helps eliminate the overhead of redeclaring functions as well. You don't, as a rule, want to use for (x in y).
Though why JSLint does not consider for... of to be a "good part" of ES6, I don't know.
I have this javascript code which is not working.
function myfun()
{
return
{
alert("para");
}
};
myfun();
I have read about the javascript's automatic semicolon insertion. I corrected the above code as
return{
alert("para");
}
But still got the error : unexpected token (.
I wonder why?
NOTE: I don't need the solution but I need the explanation why the above code in not working.
EDIT
According to the book, javascript the good parts, the return statement if returns value must be in same line as return expression.
ie
return {
status: true
};
AND
return
{
status: true
};
Is wrong.Then How come
function myfun(para)
{
var status;
return
{
status : alert(para)
};
};
myfun("ok");
produce no error.It won't work but shows no error as well.It works when the { is in the same line as return.
ie
function myfun(para)
{
var status;
return{
status : alert(para)
};
};
myfun("ok");
In
return {
alert("para");
}
the {...} are interpreted as object literal. An object literal has the form
{
key: value,
//...
}
Object literals cannot contain arbitrary statements.
Looks like you've difficulties with ASI and the difference between run-time and parsing-time.
Where as
return {
status: true
};
is a correct way to return an object, ASI will take an action in the following code:
return
{ // ^-- ASI will insert a semicolon here
status: true
};
The semicolon is automatically inserted, and at run-time all lines after return are ignored. However, at parsing time, everything counts, and if there's a syntax error, like in your first example, an error will be thrown.
The reason why you are getting that error is because JS is expecting a value to the key "para".
There is no compulsion to return in a JavaScript function. If your intention is to test if the control goes to the function, you can simply change it to
function myfun() { alert("para"); }
if you want to return an object with string "para" you should change it to
function myfun() { return { "text": "para" }; }
In the Restify framework code I found this function:
function queryParser(options) {
function parseQueryString(req, res, next) {
// Some code goes there
return (next());
}
return (parseQueryString);
}
Why would the author write return (next()); and return (parseQueryString);? Does it need parentheses there and if so, why?
Using parentheses when returning is necessary if you want to write your return statement over several lines.
React.js offers a useful example. In the return statement of the render property in a component you usually want to spread the JSX you return over several lines for readability reasons, e.g.:
render: function() {
return (
<div className="foo">
<h1>Headline</h1>
<MyComponent data={this.state.data} />
</div>
);
}
Without parentheses it results in an error!
More generally, not using parentheses when spreading a return statement over several lines will result in an error. The following example will execute properly:
var foo = function() {
var x = 3;
return (
x
+
1
);
};
console.log(foo());
Whereas the following (without the parentheses) will throw errors:
var foo = function() {
var x = 3;
return
x
+
1
;
};
console.log(foo());
It doesn't need to be that way, but it's valid JavaScript code. Actually it's quite uncommon to see such syntax. I guess it's a personal preference of the author.
Parenthesis are used for two purposes in a return statement.
To support multi-line expression as mentioned in #Andru Answer.
To allow returning object in arrow function like the below:
() => ({ name: 'Amanda' }) // Shorthand to return an object
This is equivalent to
() => {
return { name : 'Amanda' }
}
For more information, please check this article.
https://medium.com/#leannezhang/curly-braces-versus-parenthesis-in-reactjs-4d3ffd33128f
// Create a component named MessageComponent
var MessageComponent = React.createClass({
render: function() {
return (
<div>{this.props.message}</div>
);
}
});
NOTE Why do we need the parentheses around the return statement (line
3)? This is because of JavaScript's automatic semicolon insertion.
Without the parentheses, JavaScript would ignore the following lines
and return without a value. If the JSX starts on the same line as the
return, then parentheses are not needed.
Taken from here.
Just to add to what others have said.
Using brackets around the return value is valid JavaScript, but mostly a bad thing to do.
Mostly bad because it doesn't add anything yet increases the size of the JavaScript which means that there is more to download to the browser. Yes most people have fast broadband connections, but don't lose sight of the fact that everything you put in the JavaScript file needs to be downloaded so avoid unnecessary code bloat. This probably doesn't matter if you use a tool to compact your code (minifier has already been mentioned), but not everyone does.
Sometimes it might aid readability. Hard pressed to think of an example in this case, but if the use of brackets makes your JavaScript clearer to you as the developer and thus easier to maintain then use them - even if it goes against what I said about code bloat.
Why would the author write return (next()); ... ?
Regarding next():
Probably because his function is something like this:
function next()
{
var i=0;
return function (){
// Do something with that closured i....
}
}
Regarding (xxx);:
It is unnecessary. Every minifier will remove it.
Example (uglifyJS):
becomes:
I tried:
var a = function() {
return true || true
}
console.log(a());
//return: true
var a = function() {
return
true || true
}
console.log(a());
//return: undefined
var a = function() {
return (
true || true
)
}
console.log(a());
//return: true
While Andru's answer is popular, it is wrong that parantheses are required for multiline return statement. Here, you can see an object of foo and bar is returned with no parantheses needed.
function foo () {
return {
foo: 'foo',
bar: 'bar',
}
}
console.log(foo())
As long as the return line is not just empty space or linebreak, you can have a multiline return just fine. Otherwise Automatic Semicolon Insertion takeover and break your return statement as demonstrated by Andru.
Regarding your question, I am onboard with Darin's answer.
This may be old but the return () can be used in this way:
function parseQueryString(req, res, next) {
var id = req.param('id');
return (id ? "Foo" : "Bar");
}
Less code, easy to read :)
I have a javascript method that takes a single parameter. That parameter can be a path (in which case the function will use ajax to resolve the variable, a function (which will be called to resolve the variable, or valid markup (which will be used directly).
I'm looking for suggestions for distinguishing between a string that represents a path and a string that represents markup.
Note: I'm not too concerned if the markup is invalid
Well if you are stuck with the function you got, than you would have to use a regular expression to dtermine what you got. Problem with that, it can be error prone.
You are better off passing in an object and letting the object tell you what you have based on what properties it has.
function myMethod( obj ) {
if (obj.path) {
console.log("I have a path:", obj.path);
} else {
console.log("I have a path:", obj.html);
}
}
myMethod({"path":"/foo/bar/"});
myMethod({"html":"<p>/foo/bar/</p>"});
You can use something like this:
function validate(param) {
if (typeof(param) == 'function') {
console.log('It is a function!')
} else if (typeof(param) == 'string') {
if (param.indexOf('http') == 0) {
console.log('It is a path!')
} else {
console.log('It is a markup!')
}
}
}
It's far from perfect (especially in Path department) but it's a starting point.
Demo: http://jsfiddle.net/4369k/