-5

My question is about the following code:

var d = new Date();
var weekday = ["su", "mo", "tu", "we", "th", "fr", "sa"];
var deliver = weekday[d.getDay()];

if(condition){
    if(d.getDay() == 1){
       d.setHours(d.getHours() + 24); // adds a day
    }
    if(d.getUTCMonth() == 0 && d.getUTCDate() == 1){
        // do something
    } else {
        // version 1 or version 2
    }
}

//version 1: var deliver = weekday[d.getDay()];
//           document.getElementById("leverdatum").innerHTML = deliver;

//version 2: document.getElementById("leverdatum").innerHTML = deliver;;

Why, if I use version 1, the output is "tu" and if I use version 2 the output is "mo"?

8
  • Because of this? d.setHours(d.getHours() + 24); // adds a day. You shouldn't put var inside block-statements becuase of variable hosting, that might take away some of the confusion. Commented Mar 7, 2016 at 13:04
  • 1
    Version 1 & Version 2 — Removing that var makes no difference. Commented Mar 7, 2016 at 13:04
  • I think there's more to this than you're showing - how are you seeing this output? The additional var there won't make any difference, it's in the same scope. Commented Mar 7, 2016 at 13:05
  • If condition is false it doesn't do the +24h. I think that's what OP means. Commented Mar 7, 2016 at 13:05
  • 1
    Yeah, I don't really understand. What did you expect deliver; to do? Commented Mar 7, 2016 at 13:17

1 Answer 1

1

The presence (or lack thereof) of var on that line does absolutely nothing.

The significant part is = weekday[d.getDay()];.

Because it is (at the time of writing) Monday, d.setHours(d.getHours() + 24); // adds a day will add a day. Making the day Tuesday.

But if you don't convert the value of d into a day and assign it to deliver after you change the value of d, then you will continue to have the original string.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for understanding my question!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.