Rectangle 27 15

The chrome.storage API is asynchronous - it doesn't return it directly, rather passing it as an argument to the callback function. The function call itself always returns undefined.

This is often used to allow other methods to run without having to wait until something responds or completes - an example of this is setTimeout (only difference is that it returns a timer value, not undefined).

setTimeout(function () { alert(1); }, 10000);
alert(0);

Because setTimeout is asynchronous, it will not stop all code until the entire function completes, rather returning initially, only calling a function when it is completed later on - this is why 0 comes up before 1.

// "foo" will always be undefined
var foo = asyncBar(function (e) { return e; });

Generally, you should put what you want to do in your callback (the function that is called when the asynchronous function is completed). This is a fairly common way of writing asynchronous code:

function getValue(callback) {
  chrome.storage.sync.get("value", callback);
}

You could place an entire portion of your code inside the callback - there's nothing stopping you from doing so. So instead of doing the following:

console.log(getValue()); // typical synchronous method of doing something

This would probably be a better idea:

// how it would be done in asynchronous code
getValue(function (value) {
  console.log(value);
});

>this is why 0 comes up before 1. I see. Thanks!! It's very clear.

>var foo; >asyncBar(function (e) { foo = e; }); I think I tried something like this. But, I'll try it again now!

I tried this code. But, it returns undefined at the end of code in the post. var test; chrome.storage.sync.get("value", function(e){ console.log(e); test = e; });

This is the whole code without setMode(). var Options = function(){}; Options.prototype = { getMode: function(){ var test; chrome.storage.sync.get("value", function(e){ console.log(e); test = e; return test; }); } } var options = new Options(); console.log(options.getMode());

@crzyonez777: I seem to have misled you. That still wouldn't work for the same reasons I have outlined above - that was meant for if you were to use that (much) later somewhere else, test would still be undefined and return out of the function straight after that call.

javascript - Callback returns undefined with chrome.storage.sync.get -...

javascript google-chrome-extension
Rectangle 27 15

The chrome.storage API is asynchronous - it doesn't return it directly, rather passing it as an argument to the callback function. The function call itself always returns undefined.

This is often used to allow other methods to run without having to wait until something responds or completes - an example of this is setTimeout (only difference is that it returns a timer value, not undefined).

setTimeout(function () { alert(1); }, 10000);
alert(0);

Because setTimeout is asynchronous, it will not stop all code until the entire function completes, rather returning initially, only calling a function when it is completed later on - this is why 0 comes up before 1.

// "foo" will always be undefined
var foo = asyncBar(function (e) { return e; });

Generally, you should put what you want to do in your callback (the function that is called when the asynchronous function is completed). This is a fairly common way of writing asynchronous code:

function getValue(callback) {
  chrome.storage.sync.get("value", callback);
}

You could place an entire portion of your code inside the callback - there's nothing stopping you from doing so. So instead of doing the following:

console.log(getValue()); // typical synchronous method of doing something

This would probably be a better idea:

// how it would be done in asynchronous code
getValue(function (value) {
  console.log(value);
});

>this is why 0 comes up before 1. I see. Thanks!! It's very clear.

>var foo; >asyncBar(function (e) { foo = e; }); I think I tried something like this. But, I'll try it again now!

I tried this code. But, it returns undefined at the end of code in the post. var test; chrome.storage.sync.get("value", function(e){ console.log(e); test = e; });

This is the whole code without setMode(). var Options = function(){}; Options.prototype = { getMode: function(){ var test; chrome.storage.sync.get("value", function(e){ console.log(e); test = e; return test; }); } } var options = new Options(); console.log(options.getMode());

@crzyonez777: I seem to have misled you. That still wouldn't work for the same reasons I have outlined above - that was meant for if you were to use that (much) later somewhere else, test would still be undefined and return out of the function straight after that call.

javascript - Callback returns undefined with chrome.storage.sync.get -...

javascript google-chrome-extension
Rectangle 27 14

As pointed out by others, javascript function will always return undefined if you do not specify any return value. You can just ignore it. It's not going to cause any harm. But if it's annoying you too much then you can turn it off in repl. Repl has this property ignoreUndefined which is set to false by default. You can set it to true. Try this:

module.exports.repl.ignoreUndefined = true;

javascript - node.js displays "undefined" on the console - Stack Overf...

javascript node.js console undefined
Rectangle 27 2

d3.csv actually returns a useful value that can be used for attaching relevant callbacks. However, because the getThings doesn't have a return statement, then it will always yield undefined when invoked.

Remember that return applies to the nearest enclosing function, including anonymous functions such as the provided callback.

function getThings(code) {
    /* Without an explicit return, a function always evaluates
       to undefined when invoked. */
    return d3.csv("data.csv", function(data){ .. });
})

var test = getThings(..);
/* Now test is NOT undefined, but is also NOT the data
   for the asynchronous reasons discussed elsewhere.
   See the link above for correct usage. */
test.row(..);

d3.js - Javascript function returns undefined - Stack Overflow

javascript d3.js leaflet geojson
Rectangle 27 2

d3.csv actually returns a useful value that can be used for attaching relevant callbacks. However, because the getThings doesn't have a return statement, then it will always yield undefined when invoked.

Remember that return applies to the nearest enclosing function, including anonymous functions such as the provided callback.

function getThings(code) {
    /* Without an explicit return, a function always evaluates
       to undefined when invoked. */
    return d3.csv("data.csv", function(data){ .. });
})

var test = getThings(..);
/* Now test is NOT undefined, but is also NOT the data
   for the asynchronous reasons discussed elsewhere.
   See the link above for correct usage. */
test.row(..);

d3.js - Javascript function returns undefined - Stack Overflow

javascript d3.js leaflet geojson
Rectangle 27 2

d3.csv actually returns a useful value that can be used for attaching relevant callbacks. However, because the getThings doesn't have a return statement, then it will always yield undefined when invoked.

Remember that return applies to the nearest enclosing function, including anonymous functions such as the provided callback.

function getThings(code) {
    /* Without an explicit return, a function always evaluates
       to undefined when invoked. */
    return d3.csv("data.csv", function(data){ .. });
})

var test = getThings(..);
/* Now test is NOT undefined, but is also NOT the data
   for the asynchronous reasons discussed elsewhere.
   See the link above for correct usage. */
test.row(..);

d3.js - Javascript function returns undefined - Stack Overflow

javascript d3.js leaflet geojson
Rectangle 27 4

I'm guessing that chrome.extension.sendRequest is asynchronous, in which case sendCommand doesn't return anything. The response-handler inside sendCommand is the one that returns something, but that's not the same, as sendCommand returning something. So when you call sendCommand it returns undefined.

sendCommand
undefined
chrome.extension.sendRequest
chrome.extension.sendRequest(cmdJson, function(response){}

@ZeroDivide Well, I admit that I don't know the Chrome Extension API, but judging from the behavior you're describing, I'd say it's a fair bet that sendRequest is asynchronous.

Yeah its how contentscripts (injected into webpages) talks with an extension's background script(one script running in the background). I guess I'll just assume that it succeeds instead of passing the response back to the calling function.

@ZeroDivide: sendRequest indeed does not block--it and most other similar API functions in the Chrome API are asynchronous. You're going to have to rely on the callback to call another piece of code and notify it that it has succeeded or failed.

@ZeroDivide Assuming it to succeed sounds fragile to me, but it's your call. You could look into Deferred/Promises/Futures patterns. Or simply skip your sendCommand function, and call sendRequest directly, and proceed when you get a response

javascript - Why does this always return "undefined" - Stack Overflow

javascript google-chrome-extension
Rectangle 27 34

The JavaScript functions always return something. If you don't specify something to return in the function, 'undefined' is returned by default (you can check this out in Firebug too).

Don't worry though, this doesn't affect anything, you can ignore it.

+1. Thanks for the reply. Is there a way to get rid of 'undefined', what should be the syntax?

If you make a program (web app or command line), you'll never get "flying" undefineds, so don't worry about that.

When I don't enter any function or any character; then also "undefined" is displayed. Can you please explain what is happening under the hood?

What's happening under the hood. Enter asdasd for example and see this error: at REPLServer.eval (repl.js:80:21) ... So behind the scenes there's an eval() function which returns 'undefined'.

Thanks. Got it now :) I should start looking at how things are implemented and not just how to get it working.

javascript - node.js displays "undefined" on the console - Stack Overf...

javascript node.js console undefined
Rectangle 27 3

chrome.tabs.query is asynchronous, so your return executes before the theTab = tab in the callback or the callback itself is executed, So try:

function _getCurrentTab(callback){ //Take a callback
    var theTab;
    chrome.tabs.query({active:true, currentWindow:true},function(tab){
        callback(tab); //call the callback with argument
    });
};

_displayTab(tab){ //define your callback function
    console.log(tab);
 };

 _getCurrentTab(_displayTab); //invoke the function with the callback function reference

@tripRev This is the way you handle callbacks, if you are getting undefoned still just put a console.log(tab) inside your chrome.tabs.query callback itself and it will be undefined, because something else is wrong.

revisiting this after 3 years I can see you were absolutely correct. If you want a func which returns the current tab, you can't use the result straight away, you need to provide a cbfunc which uses it when it's done.

javascript - Putting chrome.tabs.query in a function always returns un...

javascript google-chrome google-chrome-extension
Rectangle 27 3

chrome.tabs.query is asynchronous, so your return executes before the theTab = tab in the callback or the callback itself is executed, So try:

function _getCurrentTab(callback){ //Take a callback
    var theTab;
    chrome.tabs.query({active:true, currentWindow:true},function(tab){
        callback(tab); //call the callback with argument
    });
};

_displayTab(tab){ //define your callback function
    console.log(tab);
 };

 _getCurrentTab(_displayTab); //invoke the function with the callback function reference

@tripRev This is the way you handle callbacks, if you are getting undefoned still just put a console.log(tab) inside your chrome.tabs.query callback itself and it will be undefined, because something else is wrong.

revisiting this after 3 years I can see you were absolutely correct. If you want a func which returns the current tab, you can't use the result straight away, you need to provide a cbfunc which uses it when it's done.

javascript - Putting chrome.tabs.query in a function always returns un...

javascript google-chrome google-chrome-extension
Rectangle 27 152

The output of console.log(anObject) is misleading; the state of the object displayed is only resolved when you expand the > in the console. It is not the state of the object when you console.log'd the object.

console.log(Object.keys(config))
console.log(JSON.stringify(config))
console.log

You will (usually) find the keys are being added after your console.log call.

javascript - Can't access object property, even though it exists. Retu...

javascript console.log
Rectangle 27 7

A simpler explanation is that module.exports is resolving to undefined inside the module that you are requiring. Post the code of the failing modules.

It also happens if your require a module that is already included somewhere earlier in the code.

due to the asynchronous nature of node, the files are "not yet" required

require is synchronous. This is not possible.

It is correct that if module A requires B, which in turn requires A, then A will be undefined in module B. But I'm not sure this is the problem.

Thanks for the clarification. I will edit that in. Since I am currently on the road for the next couple of days, I will post the code of the failing files asap when I am back home.

Hey Travis, as you can read from my comment above, I was stupid and overlooked the typing error my colleague had brought in. Nevertheless your point is very important, besides of me already editing it in my original post. Since I don't have enough reputation yet to give points, is there anyhting I can do to mark your answer as important?

Continue using Stackoverflow :) I'm patient.

javascript - Node require returns undefined - Stack Overflow

javascript node.js undefined require
Rectangle 27 7

A simpler explanation is that module.exports is resolving to undefined inside the module that you are requiring. Post the code of the failing modules.

It also happens if your require a module that is already included somewhere earlier in the code.

due to the asynchronous nature of node, the files are "not yet" required

require is synchronous. This is not possible.

It is correct that if module A requires B, which in turn requires A, then A will be undefined in module B. But I'm not sure this is the problem.

Thanks for the clarification. I will edit that in. Since I am currently on the road for the next couple of days, I will post the code of the failing files asap when I am back home.

Hey Travis, as you can read from my comment above, I was stupid and overlooked the typing error my colleague had brought in. Nevertheless your point is very important, besides of me already editing it in my original post. Since I don't have enough reputation yet to give points, is there anyhting I can do to mark your answer as important?

Continue using Stackoverflow :) I'm patient.

javascript - Node require returns undefined - Stack Overflow

javascript node.js undefined require
Rectangle 27 144

The output of console.log(anObject) is misleading; the state of the object displayed is only resolved when you expand the > in the console. It is not the state of the object when you console.log'd the object.

console.log(Object.keys(config))
console.log(JSON.stringify(config))
console.log

You will (usually) find the keys are being added after your console.log call.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

javascript - Can't access object property, even though it exists. Retu...

javascript console.log
Rectangle 27 237

For undeclared variables, typeof foo will return the string literal "undefined", whereas the identity check foo === undefined would trigger the error "foo is not defined".

For local variables (which you know are declared somewhere), no such error would occur, hence the identity check.

@goreSplatter You can't delete it now. :-) It was hard to choose, but the way the question is phrased, this answer is a better fit. Anyone who's interested in how undefined works in general (as I was) should also look at the other answers, especially @Tim's.

I would add quotation marks (typeof foo; // -> "undefined") to emphasise it is a string and not the primitive value undefined.

javascript - variable === undefined vs. typeof variable === "undefined...

javascript jquery undefined
Rectangle 27 227

For undeclared variables, typeof foo will return the string literal "undefined", whereas the identity check foo === undefined would trigger the error "foo is not defined".

For local variables (which you know are declared somewhere), no such error would occur, hence the identity check.

@goreSplatter You can't delete it now. :-) It was hard to choose, but the way the question is phrased, this answer is a better fit. Anyone who's interested in how undefined works in general (as I was) should also look at the other answers, especially @Tim's.

I would add quotation marks (typeof foo; // -> "undefined") to emphasise it is a string and not the primitive value undefined.

javascript - variable === undefined vs. typeof variable === "undefined...

javascript jquery undefined
Rectangle 27 9

I had the same issue. Solution for me was using the stringified output as input to parsing the JSON. this worked for me. hope its useful to you

var x =JSON.parse(JSON.stringify(obj));
console.log(x.property_actually_now_defined);

Yes it worked, but why is this required? I already have a JSON, why I need to do this?

@dilpeshjain I'm not exactly sure, but I would venture that we dont actually have JSON already (perhaps there is a lazy loading type scenario going on, i am not knowledgeable enough about that at the moment) , but passing whatever we do have into JSON.stringify requires a string to be returned (like the console.log call needs for printing). Because I know I can at least get a string, then I can use that string to create a JSON object for sure right away.

javascript - Can't access object property, even though it exists. Retu...

javascript console.log
Rectangle 27 17

Check if inside the object there's an array of objects. I had a similar issue with a JSON:

"terms": {
        "category": [
            {
                "ID": 4,
                "name": "Cirugia",
                "slug": "cirugia",
                "description": "",
                "taxonomy": "category",
                "parent": null,
                "count": 68,
                "link": "http://distritocuatro.mx/enarm/category/cirugia/"
            }
        ]
    }

I tried to access the 'name' key from 'category' and I got the undefined error, because I was using:

Then I realised it has got square brackets, that means that it has an array of objects inside the category key, because it can have more than one category object. So, in order to get the 'name' key I used this:

var_name = obj_array.terms.category[0].name

Maybe it's too late for this answer, but I hope someone with the same problem will find this as I did before finding the Solution :)

javascript - Can't access object property, even though it exists. Retu...

javascript console.log
Rectangle 27 17

Check if inside the object there's an array of objects. I had a similar issue with a JSON:

"terms": {
        "category": [
            {
                "ID": 4,
                "name": "Cirugia",
                "slug": "cirugia",
                "description": "",
                "taxonomy": "category",
                "parent": null,
                "count": 68,
                "link": "http://distritocuatro.mx/enarm/category/cirugia/"
            }
        ]
    }

I tried to access the 'name' key from 'category' and I got the undefined error, because I was using:

Then I realised it has got square brackets, that means that it has an array of objects inside the category key, because it can have more than one category object. So, in order to get the 'name' key I used this:

var_name = obj_array.terms.category[0].name

Maybe it's too late for this answer, but I hope someone with the same problem will find this as I did before finding the Solution :)

javascript - Can't access object property, even though it exists. Retu...

javascript console.log
Rectangle 27 6

I am using the result of a REST call. The result should be parsed from JSON to a JavaScript object.

There is one error I need to defend. If the args to the rest call were incorrect as far as the user specifying the args wrong, the rest call comes back basically empty.

if( typeof restResult.data[0] === "undefined" ) { throw  "Some error"; }

For my situation, if restResult.data[0] === "object", then I can safely start inspecting the rest of the members. If undefined then throw the error as above.

What I am saying is that for my situation, all the suggestions above in this post did not work. I'm not saying I'm right and everyone is wrong. I am not a JavaScript master at all, but hopefully this will help someone.

javascript - Detecting an undefined object property - Stack Overflow

javascript object undefined