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" }; }
Related
So i have this settings check function
function areConfigSettingsProper() {
var configurationLimits = {
minItems: 10,
}
var configSettingsProper = _.every(storageConfigurationViewModel.configSettings.data(),
function(configSetting) {
if (configSetting.Enabled)
{
//Rounds limits
if (configSetting.items < configurationLimits.minItems)
{
return {
isValid: false,
message: "To few items in storage"
};
}
return {
isValid: true,
message: ""
};
});
return configSettingsProper;
}
But this is said as it is returning a boolean still and therefore i cant access my message when i try to use it like this
const checkConfigSettings = areConfigSettingsProper();
if (checkConfigSettings.isValid) {
showSummary();
}
else {
showWarningWithConfirmation(checkConfigSettings.message);
}
But this doesnt show any message at all so for some reason i cant access it properly. So obviously i am doing something wrong. How should i handle this in a good practice? this is all done in an cshtml file
Your configSettingsProper funtion is actually calling every, not the function you hve passed as an argument. The return type of this function is boolean, hence your result.
Also, your declared function might not work as you expect it. every will check the return of this function for truthyness. Since you are returning an object there (your boolean value is just one of its properties), you can expect the result of configSettingsProper to be always true.
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.
I'm trying to implement a service using AngularJS to manage cookies.
angular
.module('myModule')
.service('CookiesService', ['$cookies', function ($cookies) {
var cookies = {
cookie1: {},
cookie2: {}
};
function CookiesService() {
}
CookiesService.prototype.update= function(name, options) {
cookies[name] = options ? options : {};
};
CookiesService.prototype.isCookie = function(name) {
if(!cookies.hasOwnProperty(name)) {
throw 'Unknown cookie name';
}
return cookies.hasOwnProperty(name);
};
function getter(prototype, name, getter) {
Object.defineProperty(prototype, name, {
get:getter,
enumerable: true,
configurable: true,
});
}
Object.keys(cookies).forEach(function(name) {
getter(CookiesService.prototype, name, function() {
try {
CookiesService.prototype.isCookie(name);
return $cookies.get(name);
} catch (e) {
throw new Error('Invalid cookie'); // never thrown!
}
});
/*Setter code*/
return new CookiesService();
});
}
]);
So basically, if I want to retrieve a cookie after setting it, I would simply call CookiesServices.
Howeber, if I try to call the getter to retrieve a cookie that doesn't exist, I expect to get an error in the console. Since I have the throw, but it seems that it is not working and I am not able to debug and see whether the code gets executed at this level or not.
Example: CookiesService.cookie3 <- gives me undefined, no error thrown.
Also assuming that I do as follows:
CookiesService.prototype.isCookie = function(name) {
return cookies.hasOwnProperty(name);
};
Object.keys(cookies).forEach(function(name) {
getter(CookiesService.prototype, name, function() {
if (!CookiesService.prototype.isCookie(name)) {
throw new Error("blabla");
}
return $cookies.get(name);
});
it won't throw the blabla error if I try to call CookiesService.cookie2
First, it might be a good idea to rename your function getter(){} to function createGetter(){}. This will make things easier to understand especially with the last param on said function also named "getter".
Second, you stated:
Howe[v]er, if I try to call the getter to retrieve a cookie that doesn't exist...
This simply will never happen:
Remember your foreach loop is creating getters for existing cookies (the stuff defined under var cookies). There will never be a getter defined on your service object that doesn't also have a corresponding value under cookies; thus doing something like CookiesService.cookie3 isn't calling a getter at all.
If you think about it, how could you expect to exercise code (e.g., get: function(){...}) for a getter that's never been defined anyways?
So calling CookiesService.cookie3 will never execute code that you setup for existing cookies and therefore will never break into your error throws.
What you are seeing with the 'undefined' error is JS literally telling you it's not a function, it's not a getter, it's not a property... it's not anything defined on the object CookiesService.
You can just check for undefined instead of waiting for an error. Yes in javascript you can access an undefined value. As long as you don't try to access a value within the undefined you won't get an error
Object.keys(cookies).forEach(function(name) {
getter(CookiesService.prototype, name, function() {
CookiesService.prototype.isCookie(name);
if ($cookies.get(name) !== undefined) return $cookies.get(name)
else throw new Error('Invalid cookie');
});
I am trying to understand one of the properties of js closures that says :
ref from Closures store references to the outer function’s variables
function myId()
{
var userID=999;
return
{
getId: function() {
return userID;
},
setId: function(newId) {
userID = newId;
}
};
}
var callInnerFun = myId();
console.log(callInnerFun.getId());
callInnerFun.setId(500);
console.log(callInnerFun.getId());
When i try running the above code in Node or even on the browser, i get the following error:
SyntaxError: function statement requires a name at getId: function() {
I have tried and failed to understand what am i really missing out on. Is it some syntactical error, or is it something to do with my text editor, sublime text, because, if i try running the exact same code as copied from the link given above, then things work.
Whereas in my code (above) the logic is still the same as the reference, just the indentation and the variable names have changed. Is it that changing these have broken my code ?
You have two bugs: the first is an extra closing brace before setId. Once you remove that, change:
return
{
to
return {
In Javascript, brace position matters since it inserts a semicolon after the return statement if you don't have one which you don't want. Also I changed the brace position in your myId definition. The final code is:
function myId() {
var userID=999;
return {
getId: function() {
return userID;
},
setId: function(newId) {
userID = newId;
}
};
}
var callInnerFun = myId();
console.log(callInnerFun.getId());
callInnerFun.setId(500);
console.log(callInnerFun.getId());
One '}' is extra here. And also it should be 'return {'
Change the below
getId: function() {
return userID;
}
},
to
getId: function() {
return userID;
},
Hope it helps !!
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 :)