Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I stumbled upon this puzzling error when looping over JavaScript objects using the for..in construct. I have a set of dummy data similar to this:
{
"12345678" : {
...
},
"12345679" : {
...
},
"12345680" : {
...
}
}
Maybe it matters, this object is retrieved from a Firebase database using the response's built-in .val() method. It is a regular js object.
However, when traversing the object, the variable declared inside the for..in loop is somehow undefined. I've removed all surrounding code except the loop, and the error still occurs:
for (key in data) {
console.log(data[key]);
}
// Throws ReferenceError: key is not defined
I am really baffled. How is this possible? I thought the variable passed to for..in was always available (or at least defined) inside the loop.
As mentioned in my comment, you'll probably need to define key; otherwise, you'll (probably) define a global variable, which may or may not work correctly. Also, to avoid unrelated properties from appearing in your loop, use hasOwnProperty:
for (var key in data) {
if (!data.hasOwnProperty(key)) {
continue;
}
console.log(data[key]);
}
See How do I loop through or enumerate a JavaScript object? for further information.
you just don't use the right syntax for for..in statement.
You need to define key variable with var (or let if you use ES6): in order to use it in the statement:
for(var key in data){
console.log(data[key])
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
While in VS Code, I hit the tab after typing return and the VS Code Intellisense auto-completed "return" to "this.return".
I've never seen this before and cannot find any documentation on it.
Does anybody know if this is actually a thing, or if VS Code possibly lost it's marbles.
Note: the object I was working in does not have any properties or functions called "return".
Well, an object could have a property called return:
const obj = {
return: () => { console.log('↩️'); }
};
obj.return();
Were you in the context of a class that had a return property, or maybe its superclass did?
(Honestly it seems more likely VS Code was just being weird.)
You can run console.log("this", this) in most modern browsers this will return the JSON data of this (the variable this refers to the current instance of declared object FYI), and console.log(typeof(this.return)) and it will likely return function (if you get undefined just change it from this.return to return;)
Likely the object either has a property called return that is a function, or something has gone wrong in the autocomplete.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Given the following function:
function lamePathValidator(path) {
if (typeof path !== 'string') {
throw new TypeError(`Invalid path "${path}": should be a string.`);
}
return path;
}
Is it considered bad practice if occasionally it's being used without storing the return value to a variable?
...
lamePathValidator('./data');
...
Edit: The only use case in which I need the returned value, is for property assignments in constructors, such as:
constructor(basepath) {
this._basepath = this._validatePath(basepath);
}
I could of course write:
constructor(basepath) {
this._validatePath(basepath)
this._basepath = basepath;
}
The former block is more concise though.
Edit #2:
I could also pass constructor parameters to a _validateAll(params) function since none of them are actually being altered in any way. It's "validate", not "sanitize" after all. :)
There are lots of functions that return data that is not always useful, but sometimes is. In those cases not storing the output when you don't need it makes sense.
However if the return value is never useful then you shouldn't be returning it in the first place. In your example function the path is not altered so there is no reason to return it, the calling code already has it.
A function can return a value if required. It is not mandatory to return some value from it. In your case there is no need to return any value.
Read the js function documentation here
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
var main = function() {
this.first = this;
}
console.log(new main().first);
The code is here :
Object is creating recursively ,I didnot understand why the console not throwing any error.
Please tell me if there is any concept behind this.
You are making it circular (not recursive) with this:
this.first = this
It's the same as if you do:
var obj = {}
obj.first = obj
obj.first will reference obj. That in javascript is like saying obj.first is obj. Really the javascript engine isn't creating infinite objects, just an object that has a reference to itself.
It doesn't throw an error simply because the value of a property of an object is allowed to be a reference to that object. You don't have any actual recursion here.
You'd only get an error if, for example, you wrote a function to recursively crawl down through the properties of the object, but that would be because you had too many functions on the stack and the self reference would only be a factor that led to that.
There's no recursion here. What you have is a self reference (where one object stores a property that refers to itself).
Your code does not throw because console.log() is smart enough to handle self references. It doesn't infinite loop just because of a self reference as it is coded to specifically handle that situation.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am getting the error:
bluebird.js:2118 Uncaught TypeError: generatorFunction must be a function
But I don't understand why this error is occurring, as I am passing it a generatorFunction.
export class Welcome {
fetch() {
Promise.coroutine(this.userData());
}
userData = function* getData() {
this.lotsData = yield this.testApi.getMock();
this.lotsData = JSON.stringify(this.lotsData, null, 4);
}
}
So a click event calls fetch() and that calls this.userData(). This is the console dump of this.userData:
GeneratorFunctionPrototype {}
_invoke: invoke(method, arg)
__proto__: GeneratorFunctionPrototype
Which tells me it most certainly is a generator. I am using all of this in an aurelia class if that somehow makes any difference (which it shouldn't I don't think). So why is it erroring that the generatorFuction must be a function?
The limited amount of code you posted is riddled with errors, but there is not enough to know what is correct and what is incorrect.
One thing is for sure this.userData() is a function call and not a reference to a function, which is what .coroutine() is expecting.
Whatever type returned by this.testApi.getMock() is what is being yielded, which we have no idea given what you posted, but that is probably not even relevant at this point, because what is returned is probably unknown/null anyway because you are assigning the yield to a variable of questionable scope. Your code is nowhere near the example from the documentation
PingPong.prototype.ping = Promise.coroutine(function* (val) {
console.log("Ping?", val)
yield Promise.delay(500)
this.pong(val+1)
});
The documentation has a very clear and well defined example you should follow, explicitly until you understand what you are actually doing.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
var p = new Person("xyz");
Some work has been done with p. Now p should point to nothing.
p = undefined;
or
p = null;
Which approach represents best practice for the empty object reference?
It's a matter of of interpretation, but null is rationally a better option
You're really asking whether the variable should be defined as:
a variable that has been declared but has not yet been assigned a value, i.e. undefined.
or
an assignment value as a representation of no value, i.e. null.
A Quote from the book Professional JS For Web Developers (Wrox) is appropriate here:
You may wonder why the typeof operator returns 'object' for a value that is null. This was actually an error in the original JavaScript implementation that was then copied in ECMAScript. Today, it is rationalized that null is considered a placeholder for an object, even though, technically, it is a primitive value."
Conclusion:
Using null is rational as it's to be considered as a placeholder for an object, but it wouldn't be wrong of you to use undefined as long as your system is consistent with it.
You can use both according to your requirement. look into this post for what exactly the difference between the two What is the difference between null and undefined in JavaScript?.
Undefined means a variable has been declared but has no value:
var item;
alert(item); //undefined
alert(typeof item); //undefined
Null is an assignment:
var item= null;
alert(item); //null
alert(typeof item); //object
Correct is:
p = null;
undefined is reserved for when variables are not initialised or for empty promises.