0

I want to refactor this code in a nicer way without exceeding an 80 char line limit.

 document.getElementById('latest-date').innerHTML =
    (
      days[date.getDay() -1] + ' ' + date.getDate() + ' ' +
      months[date.getMonth()] + ', ' + date.getFullYear() + ' - ' +
      date.getHours() + ':' + date.getMinutes()
    );

I wanted to use Template Literals but I think when I go to newline in order to follow char limit it will automatically add \n?

An example of the output of the current code is :

Thur 24 Aug, 2017 - 18:30
Dean Coakley
  • 1,675
  • 2
  • 11
  • 25

1 Answers1

1
document.getElementById('latest-date').innerHTML = (`
  ${days[date.getDay() -1]} ${date.getDate()}
  ${months[date.getMonth()]}, ${date.getFullYear()} - 
  ${date.getHours()}:${date.getMinutes()}    
`);

I think that should do it.

davedeecoder
  • 225
  • 4
  • 14
  • I asked for ES6 refactor because I really don't want to add JQuery to the project. Nice solution and it does look nice, but doesn't answer my question directly. I marked as duplicate question anyway as suggested by community. – Dean Coakley Aug 31 '17 at 18:15
  • 3
    @Dean this doesn't use jQuery. It is using template literals. The `$` is deceiving, but that has nothing to do with jQuery –  Aug 31 '17 at 18:21
  • Exactly what @TinyGiant said. When you're inside the backticks (` `) you use ${ } to input a javascript variable and anything outside of it is rendered HTML. That's what you can remove all of you + ' ' + etc. – davedeecoder Aug 31 '17 at 18:25
  • 1
    -1: This does exactly what is not wanted, it adds linebreaks to the result string. – Bergi Aug 31 '17 at 19:34
  • @Dave Wow! My mistake. This actually works perfectly and is not using JQuery like I thought. However, I'm still confused why this works. – Dean Coakley Aug 31 '17 at 20:59
  • @Dave How come it doesn't work here?: https://jsbin.com/jupoqemigo/edit?js,console – Dean Coakley Aug 31 '17 at 21:05
  • Glad it worked! I pushed it out without testing it (don't tell). I'll try and explain it simply: The reason template literals help is you don't need to constantly go inside and outside a string when you want to concatenate. The backticks give you the power to start a string but anytime you put ${javascript} or a ${variable} or a {date.getDate()} in there it automatically concatenates it for you. Anything outside of ${} will be considered part of that string. Hope that helps @Deancoakley – davedeecoder Aug 31 '17 at 21:05
  • @Dave Hmm, I found that if I `console.log()` it has the \n but if I `document.write()` it. My desired output in one line is achieved. This is strange to me. – Dean Coakley Aug 31 '17 at 21:08