1

Javascipt: Making variable into default?

I have code like this :

<script>
document.write(ab);
</script>

ab is a variable but it's not declared yet because I want it will be changing by Users. The default result I want it displays is x+y (for example as). But When Users enter any variable, the result need to be changed. For instance :

<script>
var ab = "The users change code";
</script>

The result will change is The users change code

So, Do you have any idea for my issue. Thank for your help.

3
  • 3
    Read any basic guide to javascript and you'll figure this out within minutes. Commented Oct 5, 2013 at 16:39
  • 3
    Can you rephrase your question?. Commented Oct 5, 2013 at 16:40
  • Possible duplicate of stackoverflow.com/questions/16696642/… Commented Oct 5, 2013 at 16:44

3 Answers 3

2

Just to be pedant :

You said :

ab is a variable but it's not declared yet 

shom's answer should work fine.

But if I was a robot which analyze your question :

this would pass although you have declared it :

    var ab=undefined;
    if (typeof ab === 'undefined')
        var ab= 'x+y';
    document.write(ab);

the safest way (as answering to your :"not declared yet "):

 if (!('ab' in window))
  var ab = 'x+y';
  document.write(ab);
Sign up to request clarification or add additional context in comments.

5 Comments

If you want to use my answer in your answer, perhaps you could've added a comment instead... Should I now write another answer to elaborate on this answer?
@Shomz I'll remove your code from my answer.
It's still there, but never mind. I said this because it's happening more and more on SO lately, and I can't figure out why are people taking others' answers.
@Shomz I removed your code. and the second code is a code which the whole world ( including me) would have given . just to make it different. i will write it better and add === which is much more precise (and correct). no one is stealing no one's code.
It should be if (!('ab' in window)).
2

You can do this in various ways. A ternary is a simple one.

var ab=(typeof ab==='undefined'?) x+y : ab;

This says that if ab is undefined, set it to x+y, otherwise leave it at the current, presumably user set, value.

There may be better ways to handle all of this. Post more code if you'd like.

3 Comments

why do you complicate things ?
p.s. those kind of solutions are bad because of scoping issues.
@Royi I agree, that's why I solicited more code and said this whole thing could be done more cleanly. The ternary style is seen fairly often for setting defaults in my experience. I like that it looks like an assignment straight off, not an 'if'.
1
if (typeof ab == 'undefined')
    var ab = 'x+y';
document.write(ab);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.