DataViewJS block not rendering correct message

What I’m trying to do

I found here a dataviewjs snippet so a custom message could be displayed on a header and someone else added more code so it could randomly pick a specific phrase with the condition of being morining, evening or afternoon. Sometimes this random phrases are displayed and other times I get the generic “Good Morning! NaN” and not It's a new day. I can’t find the link where they posted this snippet or who did it, but here’s what I have:

let morning = [
    "Let's do great work today!",
    "It's a new day!"
];

let afternoon = [
    "Let's finish the day well!",
    "Let's keep up our focus!",
    "Need another cup of coffee? ☕"
];

let evening = [
    "Time to relax!",
    "Your cat misses you!"
];

const currentHour = moment().format('HH'); 
let greeting; 

if (currentHour >= 17 || currentHour < 5) { 
    greeting = "🌙 Good Evening! "
        + evening[Math.floor(Math.random()*evening.length)];
} else if (currentHour >= 5 && currentHour < 12) { 
    greeting = "🌞 Good Morning! " +
        + morning[Math.floor(Math.random()*morning.length)];
} else { 
    greeting = "🌞 Good Afternoon! "
        + afternoon[Math.floor(Math.random()*afternoon.length)];
} 
dv.header(3,greeting);

Things I have tried

I don’t code on Javascript, but I have read the DataView API and docs. I have also read a bit of the basics of javascript. I also tried to trouble shoot and when I take off the part about reproducing the random messages I get the expected Good Morning or Good Evening.

const currentHour = moment().format('HH'); 
let greeting; 

if (currentHour >= 17 || currentHour < 5) { 
    greeting = "🌙 Good Evening! "
} else if (currentHour >= 5 && currentHour < 12) { 
    greeting = "🌞 Good Morning! " 
} else { 
    greeting = "🌞 Good Afternoon! "
} 
dv.header(3,greeting);

I suspect that the double + is what gives you this answer. There is one at the end of the line, and one at the start of the next line. Remove either, and I reckon it’ll start behaving as expected.

You were right. I have no idea how I missed it. I literally reviewed the code so many times haaha. It’s solved now.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.