0
var a = "the letter a";
var obj = {};

obj.brovo = "the letter b";
obj.charlie = "the letter c";

if (!obj.alpha) obj.alpha = a;

Since I wish to use this at different points in my code and will be using it multiple times I wish for it to be used as the following:

isNotSet(obj.alpha, a);

I wish this to equate obj.alpha = a;

I started with the following function:

function isNotSet (arg1, arg2) {
    if (!arg1) arg1 = arg2;
    return arg1;
}
2
  • 1
    You need not return the value. As the variable is passed by reference Commented Dec 4, 2015 at 22:05
  • why the down vote? this is :( this is my first question here. Commented Dec 4, 2015 at 22:24

2 Answers 2

3

The solution is really just a simple one-liner:

obj.alpha = obj.alpha || a;

If you really need a function, you can wrap it:

function isNotSet(obj, arg1, arg2) {
    obj[arg1] = obj[arg1] || arg2;
}

You should be aware, though, that both this solution and your proposed solution will overwrite the value if obj[arg1] is set to false (or any other falsy value).

If you want to handle those values properly, the easiest way would be:

function isNotSet(obj, arg1, arg2) {
    if(typeof obj[arg1] !== "undefined" && obj[arg1] !== null) { return; }
    obj[arg1] = arg2;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Perhaps 0 is considered valid though.
@Comptonburger - I mentioned that shortcoming in my answer.
@Comptonburger - Added another function that only defaults for null and undefined. Still doesn't check property ownership.
I did not think about falsy - TY
0

I was able to accomplish this with the following function:

isNotSet('alpha', a);

I just take the arg1 as just the Property Name then add it to the object then assign the value to that object with the Property Name.

function isNotSet (arg1, arg2) {
    if (!obj[arg1]) obj[arg1] = arg2;
}

2 Comments

That's not the best solution, because the object is being accessed via it's global scope. This will only work for that object variable named obj in your code.
You might want to use hasOwnProperty instead of !obj[arg1] but that depends on how you wont to handle null, undefined, 0, false and empty string.

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.