3

Im trying to construct a script that will check if a url variable called result exists and if it does then it checks if the value equals success or not.

I tried the following but if result doesn't exist then it errors my script as undefined

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}
var first = getUrlVars()["result"];
alert(first);
0

2 Answers 2

3

And why don't you simply check if it is undefined ?

if (first !== undefined)
     alert(first);
else alert('ooops');

Or you probably can also define something like a 'default value':

var first = getUrlVars().result || '';
Sign up to request clarification or add additional context in comments.

Comments

0

If "result" isn't in the query string, then it won't be put into the vars object.

So if you want to keep the:

'first = getUrlVars()["result"]'

thing going, you're going to have to accept that if "result" wasn't there at all, then it's going to show up as undefined (which is the result you get when you ask for an array index that's not holding anything, or an object property that hasn't been set).

If you're dead-set against having that, try:

var first = getUrlVars()["result"] || "not-success";

The || will allow you to return whatever you want as the value for first, in the case that

vars.result === undefined;


first = result || false;
first = result || {};
first = result || fire_this_function("no-result");
// first now equals the return value of the function if result === undefined

These are all the same as saying:

if (result === undefined) { first = "........"; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.