0

Using javascript, for some reason I can't output "Tuesday" by the function even though d.getDay() is 2.

<!DOCTYPE html>
<html>
<body>

<p>The getDay() method returns the weekday as a number:</p>

<p id="demo"></p>

<script>
function getDayOfWeek(day){
    if (day == 1){
        return "Monday";
    else if (day == 2){
        return "Tuesday";
    else{
        return "Otherday";
    }
}

var d = new Date();
document.getElementById("demo").innerHTML = getDayOfWeek(d.getDay());
</script>

</body>
</html>

3 Answers 3

4

It looks like you're missing the closing curly braces on your else statements. I've updated your snippet below.

function getDayOfWeek(day){
    if (day == 1) {
        return "Monday";
    } else if (day == 2) {
        return "Tuesday";
    } else {
        return "Otherday";
    }
}

var d = new Date();
document.getElementById("demo").innerHTML = getDayOfWeek(d.getDay());
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, that's exactly the problem.
3

Check your curly brackets. Working version:

JSFiddle

<!DOCTYPE html>
<html>
<body>

<p>The getDay() method returns the weekday as a number:</p>

<p id="demo"></p>

<script>
function getDayOfWeek(day){
    if (day == 1)
    {
        return "Monday";
     }
    else if (day == 2)
    {
        return "Tuesday";
    }
    else
    {
        return "Otherday";
     }
}

var d = new Date();
document.getElementById("demo").innerHTML = getDayOfWeek(d.getDay());
</script>

</body>
</html>

Comments

0

The problem to solve this is so easy, you just forget close your 'if', and 'else if' using this => '}'

<!DOCTYPE html>
<html>
<body>

<p>The getDay() method returns the weekday as a number:</p>

<p id="demo"></p>

<script>
function getDayOfWeek(day){
if (day == 1){
    return "Monday";
}else if (day == 2){
    return "Tuesday";
}else{
        return "Otherday";
    }
}

var d = new Date();
document.getElementById("demo").innerHTML = getDayOfWeek(d.getDay());
</script>

</body>

1 Comment

Add some explanation to answer for how this help in solving current issue. which make this answer more useful for OP and others

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.