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.

henrywright
  • 10,070
  • 23
  • 89
  • 150
Hai Tien
  • 2,929
  • 7
  • 36
  • 55

3 Answers3

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.

JAL
  • 21,295
  • 1
  • 48
  • 66
  • 2
    why do you complicate things ? – Royi Namir Oct 05 '13 at 16:41
  • p.s. those kind of solutions are bad because of scoping issues. – Royi Namir Oct 05 '13 at 16:47
  • @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'. – JAL Oct 05 '13 at 16:52
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);
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 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 Oct 05 '13 at 16:52
  • @Shomz I'll remove your code from my answer. – Royi Namir Oct 05 '13 at 16:52
  • 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 Oct 05 '13 at 16:55
  • @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. – Royi Namir Oct 05 '13 at 16:59
  • It should be `if (!('ab' in window))`. – nnnnnn Oct 05 '13 at 17:06
1
if (typeof ab == 'undefined')
    var ab = 'x+y';
document.write(ab);
Shomz
  • 37,421
  • 4
  • 57
  • 85