Yes since it's running asynchronously, by the time result.rows is assigned to the currentCauses variable, the line return currentCauses has already been executed thus the value is undefined.
You may want to do that as follow
var resulttofgetCauses;
function getCauses(){
var currentCauses;
client = pg.connect(connectionString, function(err, client, done){
if(err) console.log(err);
client.query('SELECT * FROM causes', function(err, result){
//console.log(result.rows);
console.log('poo');
currentCauses=result.rows;
//console.log(currentCauses);
resulttofgetCauses = currentCauses;
});
});
};
getCauses();
To be more specific with the answer, executing 'SELECT * FROM causes' sql does not give you the result right after its execution time. It takes at least 0.00something seconds to retrieve the data from database. So in the very short time between 'executing sql' and 'receiving requested data' JavaScript has already executed return currentCauses; while the correct data is still in the progress of retrieving. Because it's async and won't wait. There are good example code out there on the internet you may want to check out.
Plus It's a good practice to define function as follow
getCauses = function () { ... }
Answer from Eugene Yu on Stack OverflowYes since it's running asynchronously, by the time result.rows is assigned to the currentCauses variable, the line return currentCauses has already been executed thus the value is undefined.
You may want to do that as follow
var resulttofgetCauses;
function getCauses(){
var currentCauses;
client = pg.connect(connectionString, function(err, client, done){
if(err) console.log(err);
client.query('SELECT * FROM causes', function(err, result){
//console.log(result.rows);
console.log('poo');
currentCauses=result.rows;
//console.log(currentCauses);
resulttofgetCauses = currentCauses;
});
});
};
getCauses();
To be more specific with the answer, executing 'SELECT * FROM causes' sql does not give you the result right after its execution time. It takes at least 0.00something seconds to retrieve the data from database. So in the very short time between 'executing sql' and 'receiving requested data' JavaScript has already executed return currentCauses; while the correct data is still in the progress of retrieving. Because it's async and won't wait. There are good example code out there on the internet you may want to check out.
Plus It's a good practice to define function as follow
getCauses = function () { ... }
Because currentCauses is initialized in an async invoked function (the function passed as param to pg.connect) after you have already returned from getCauses function. By the time you return the value of currentCauses is undefined.
The value of this depends on the calling context.
You'd either need to bind the object in question, roughly:
this.p[i][j].events.onInputDown.add(myMethod.bind(this), this);
(But as your code currently stands this would have the same issue) or rely on whatever the framework in question provides in the way of binding.
Welcome to JS.
Using this on JS opens up a whole world of pain. You should avoid it until you are really sure how it works or rename it to something else on your scope:
var self = this;
function create() {
self.p = [];
//etc
}
function randomizeWin(){
self.winX = Math.floor(Math.random() * 3);
self.winY = Math.floor(Math.random() * 3);
}
function myMethod(sprite){
console.log(self.p[self.winX][self.winY]==sprite);
}
The chrome.tabs.query() method is asynchronous. Therefore, the value of currentURL is not yet defined when the last line is run.
Looking into async/await functions should help you code your program to wait for the callback to resolve before it moves on further.
The callback is async and that’s why you can’t rely on the outer console.log. The outer log happens before the async callback which is still waiting in the event queue. After outer log happens, the callback is processed and so you can successfully log the tabs value inside that callback only.
Refer this documentation for more insights:- http://developer.chrome.com/extensions/overview.html#sync-example
TL;DR: It does not.
You can see content of your variable test, il will output the same thing as before. In fact it is the variable assignement that returns the undefined you see here.
For instance:
var test = 'Hello' // => undefined
test // => 'Hello'
Another case is printing your variable with console.log. If you do so, the return value will be undefined but the output will be your variable content (Hello here).
console.log(test) // return: undefined / print: Hello
What's returning undefined is the statement itself that you entered into the console, NOT the value of var text.
To see that console.log(text) or simply type text in the console.

When you refer to a variable within a function JS first checks if that variable is declared in the current scope, i.e., within that function. If not found it looks in the containing scope. If still not found it looks in the next scope up, and so forth until finally it reaches the global scope. (Bear in mind that you can nest functions inside each other, so that's how you get several levels of containing scope though of course your exmaple doesn't do that.)
The statement:
b=1;
without var declares a global variable that is accessible within any function, except that then in your first function you also declare a local b. This is called variable shadowing.
"But", you say, "I declare the local b after document.write(b)". Here you are running into declaration "hoisting". A variable declared anywhere in a function is treated by the JS interpreter as if it had been declared at the top of the function (i.e., it is "hoisted" to the top), but, any value assignment happens in place. So your first function is actually executed as if it was like this:
function run(){
var b; // defaults to undefined
document.write(b); // write value of local b
b=1; // set value of local b
}
In your second function when you use this.b, you'll find that this refers to window, and global variables are essentially properties of window. So you are accessing the global b and ignoring the local one.
In your third function you don't declare a local b at all so it references the global one.
When you write b = 1, you're creating a property in the global object.
In an ordinary function, b will refer to this global.
Since your function contains var b;, b within the function refers to the local variable. (var statements create local variables throughout the function, no matter where the var is).
However, the executable portion of the var statement (b = 1) is only executed at that point.
I'm a bit confused about Javascript undefined & null.
null generally behaves similarly to other scripting languages' concepts of the out-of-band ‘null’, ‘nil’ or ‘None’ objects.
undefined, on the other hand, is a weird JavaScript quirk. It's a singleton object that represents out-of-band values, essentially a second similar-but-different null. It comes up:
When you call a function with fewer arguments than the arguments list in the
functionstatement lists, the unpassed arguments are set toundefined. You can test for that with eg.:function dosomething(arg1, arg2) { if (arg2===undefined) arg2= DEFAULT_VALUE_FOR_ARG2; ... }With this method you can't tell the difference between
dosomething(1)anddosomething(1, undefined);arg2will be the same value in both. If you need to tell the difference you can look atarguments.length, but doing optional arguments like that isn't generally very readable.When a function has no
return value;, it returnsundefined. There's generally no need to use such a return result.When you declare a variable by having a
var astatement in a block, but haven't yet assigned a value to it, it isundefined. Again, you shouldn't really ever need to rely on that.The spooky
typeofoperator returns'undefined'when its operand is a simple variable that does not exist, instead of throwing an error as would normally happen if you tried to refer to it. (You can also give it a simple variable wrapped in parentheses, but not a full expression involving a non-existant variable.) Not much use for that, either.This is the controversial one. When you access a property of an object which doesn't exist, you don't immediately get an error like in every other language. Instead you get an
undefinedobject. (And then when you try to use thatundefinedobject later on in the script it'll go wrong in a weird way that's much more difficult to track down than if JavaScript had just thrown an error straight away.)This is often used to check for the existence of properties:
if (o.prop!==undefined) // or often as truthiness test, if (o.prop) ...do something...However, because you can assign
undefinedlike any other value:o.prop= undefined;that doesn't actually detect whether the property is there reliably. Better to use the
inoperator, which wasn't in the original Netscape version of JavaScript, but is available everywhere now:if ('prop' in o) ...
In summary, undefined is a JavaScript-specific mess, which confuses everyone. Apart from optional function arguments, where JS has no other more elegant mechanism, undefined should be avoided. It should never have been part of the language; null would have worked just fine for (2) and (3), and (4) is a misfeature that only exists because in the beginning JavaScript had no exceptions.
what does
if (!testvar)actually do? Does it test for undefined and null or just undefined?
Such a ‘truthiness’ test checks against false, undefined, null, 0, NaN and empty strings. But in this case, yes, it is really undefined it is concerned with. IMO, it should be more explicit about that and say if (testvar!==undefined).
once a variable is defined can I clear it back to undefined (therefore deleting the variable).
You can certainly assign undefined to it, but that won't delete the variable. Only the delete object.property operator really removes things.
delete is really meant for properties rather than variables as such. Browsers will let you get away with straight delete variable, but it's not a good idea and won't work in ECMAScript Fifth Edition's strict mode. If you want to free up a reference to something so it can be garbage-collected, it would be more usual to say variable= null.
can I pass undefined as a parameter?
Yes.
You cannot (should not?) define anything as undefined, as the variable would no longer be undefined – you just defined it to something.
You cannot (should not?) pass undefined to a function. If you want to pass an empty value, use null instead.
The statement if(!testvar) checks for boolean true/false values, this particular one tests whether testvar evaluates to false. By definition, null and undefined shouldn't be evaluated neither as true or false, but JavaScript evaluates null as false, and gives an error if you try to evaluate an undefined variable.
To properly test for undefined or null, use these:
if(typeof(testvar) === "undefined") { ... }
if(testvar === null) { ... }
It's possible the author came from an environment where all variables were required to be initialized when declared. Some code-checking tools will also complain if variables are not initialized before they are used (even if the first use is to assign a value).
Given your two examples, I always do the second one, but never the first.
function Foo() {
this.bar = undefined;
....
}
This creates an explicit list of properties available at a glance for maintenance purposes.1 It's equivalent to declaring public members in class-based object oriented languages:
class Foo:
def __init__(self):
self.bar = null;
Relying on the default undefined in Javascript is similar to using setattr to create dynamic properties in Python - you can do it, and it's the right solution in some rare cases, but it's not going to help the maintainers.
1I don't use null for this, because sometimes null is a valid value - checking if a property is null or undefined tells me if it got initialized at all before being used somewhere.