-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"?

remkovdm
  • 150
  • 9
  • 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. – Halcyon Mar 07 '16 at 13:04
  • 1
    [Version 1](http://jsbin.com/sayewa/1/edit?js,console) & [Version 2](http://jsbin.com/sayewa/2/edit?js,console) — Removing that `var` makes no difference. – Quentin Mar 07 '16 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. – James Thorpe Mar 07 '16 at 13:05
  • If `condition` is `false` it doesn't do the `+24h`. I think that's what OP means. – Halcyon Mar 07 '16 at 13:05
  • @Quentin replace the line from version 2 with only `deliver;` – remkovdm Mar 07 '16 at 13:14
  • 1
    Yeah, I don't really understand. What did you expect `deliver;` to do? – JJJ Mar 07 '16 at 13:17
  • @Juhana `weekday[d.getDay()];` like declared on line 3 – remkovdm Mar 07 '16 at 13:19
  • Sorry, but that's just not how JavaScript works. You can't re-initialize a variable like that, and I don't know why you would expect it to do work. – JJJ Mar 07 '16 at 13:20

1 Answers1

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335