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 Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 31875052 › variable-is-undefined-after-assignment-on-javascript
Variable is undefined after assignment on JavaScript - Stack Overflow
June 5, 2017 - You are essentially assigning undefined to it in comp2 = comp[2], if the argument dateText does not have at least 2 / at where to split. ... T.J. Crowder – T.J. Crowder · 2015-08-07 10:09:43 +00:00 Commented Aug 7, 2015 at 10:09 · dateText value is 08/07/2015, the weird thing here is when I alert(comp2) after the assignment of comp2 it will alert 2015, after that line, comp2 will be undefined.
🌐
Dmitri Pavlutin
dmitripavlutin.com › 7-tips-to-handle-undefined-in-javascript
7 Tips to Handle undefined in JavaScript - Dmitri Pavlutin
March 23, 2023 - Accessing the variable evaluates to undefined. An efficient approach to solve the troubles of uninitialized variables is whenever possible to assign an initial value. The less the variable exists in an uninitialized state, the better. Ideally, you would assign a value right away after declaration const myVariable = 'Initial value'.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › undefined
undefined - JavaScript - MDN Web Docs - Mozilla
In all non-legacy browsers, undefined is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it. A variable that has not been assigned a value is of type undefined. A function returns undefined if a value was not returned.
🌐
Quora
quora.com › In-JavaScript-why-does-a-variable-declaration-return-undefined
In JavaScript, why does a variable declaration return undefined? - Quora
Quora is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.
Find elsewhere
Top answer
1 of 4
18

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.

2 of 4
3

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.

Top answer
1 of 10
589

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:

  1. When you call a function with fewer arguments than the arguments list in the function statement lists, the unpassed arguments are set to undefined. 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) and dosomething(1, undefined); arg2 will be the same value in both. If you need to tell the difference you can look at arguments.length, but doing optional arguments like that isn't generally very readable.

  2. When a function has no return value;, it returns undefined. There's generally no need to use such a return result.

  3. When you declare a variable by having a var a statement in a block, but haven't yet assigned a value to it, it is undefined. Again, you shouldn't really ever need to rely on that.

  4. The spooky typeof operator 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.

  5. 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 undefined object. (And then when you try to use that undefined object 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 undefined like any other value:

    o.prop= undefined;
    

    that doesn't actually detect whether the property is there reliably. Better to use the in operator, 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.

2 of 10
24

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) { ... }
🌐
Codedamn
codedamn.com › news › javascript
Handling Undefined Variable Errors in JavaScript
March 26, 2023 - 1. What is the difference between null and undefined? null and undefined are two distinct data types in JavaScript. undefined is the default value assigned to a declared variable that has not been initialized, while null is an intentional absence ...
🌐
Tutorial Republic
tutorialrepublic.com › faq › how-to-determine-if-variable-is-undefined-or-null-in-javascript.php
How to Determine If Variable is Undefined or NULL in JavaScript
In JavaScript if a variable has been declared, but has not been assigned a value, is automatically assigned the value undefined. Therefore, if you try to display the value of such variable, the word "undefined" will be displayed.
Top answer
1 of 1
4

Identifiers don't update when you change the source you used to set them.

var o = {prop: function () {return 'old ref';}};
var foo = o.prop; // foo() === "old ref"
o.prop = function () {return 'new ref';};
foo(); // "old ref"

However, it may also be worth noticing

var e = o; // o as before
o.prop = function () {return 'even newer ref';};
e.prop(); // "even newer ref"
e === o; // true

When the identifier references an Object it's referencing the same object and not a copy, so changes made to it effect them all. This is because you're accessing the Object with the identifier rather than the property of that Object, i.e. e === o

If you were to then do o = fizz, o now points to a different thing to e so e !== o

var fizz = {buzz: "I'm something new!"};
o = fizz;
e.buzz; // undefined, e points at {prop: function () {...}}, not fizz
o.prop(); // TypeError, o points at fizz, not e
o.buzz; // "I'm something new!"
e === o; // false
fizz === o; // true

Lastly, by looking over what you were attempting to do you may need to consider "was there anything before?". This is why your code is throwing an Error currently.

function change(obj, prop, echo) {
    var prev_method = obj[prop];
    obj[prop] = function () {
        if (prev_method) // only if we had something before
            prev_method.apply(this, arguments); // try to invoke it
        console.log(echo);
    };
}

var o = {};
change(o, 'spell', 'H');
change(o, 'spell', 'e');
change(o, 'spell', 'l');
change(o, 'spell', 'l');
change(o, 'spell', 'o');

o'spell'; // returns undefined, logs H, e, l, l, o
🌐
Medium
medium.com › front-end-weekly › defining-the-undefined-in-javascript-2a448d5635cc
Defining the undefined in JavaScript | by Gigarthan | Frontend Weekly | Medium
January 27, 2018 - Simply saying, when you create a variable and leave it without assigning a value to it, JavaScript will automatically assign a value called undefined.
🌐
W3Schools
w3schools.com › jsref › jsref_undefined.asp
JavaScript undefined Property
The undefined property indicates that a variable has not been assigned a value, or not declared at all. undefined() is an ECMAScript1 (JavaScript 1997) feature.
🌐
freeCodeCamp
freecodecamp.org › news › javascript-check-if-undefined-how-to-test-for-undefined-in-js
JavaScript Check if Undefined – How to Test for Undefined in JS
November 7, 2024 - When a variable is declared or initialized but no value is assigned to it, JavaScript automatically displays "undefined". It looks like this: ... Also, when you try accessing values in, for example, an array or object that doesn’t exist, it ...
🌐
GitHub
gist.github.com › hartleybrody › 9726031
Variable scoping in Javascript can be confusing so I set out to make notes of the basic rules so that I can reference them later. Hope these are useful to others, happy to talk pull requests for corrections. · GitHub
April 15, 2014 - You might expect this to alert out “100”, but it will actually alert out “undefined” since the inner var num declaration is hoisted to the top of the foo() function’s scope, where it is given the value "undefined". There is no block level scope, yet... variables created inside if-statements and for-loops are available to code outside that statement · as we’ve seen in code block 4, they can be hoisted up and overwrite references even before they’re assigned to