About javascript

const quizData = [
{
        question: "What is the most used programming language in 2019?",
    a: "Java",
        b: "C",
    c: "Python",
        d: "JavaScript",
    correct: "d",
    },
{
        question: "Who is the President of US?",
    a: "Florin Pop",
        b: "Donald Trump",
    c: "Ivan Saldano",
        d: "Mihai Andrei",
    correct: "b",
    },
{
        question: "What does HTML stand for?",
    a: "Hypertext Markup Language",
        b: "Cascading Style Sheet",
    c: "Jason Object Notation",
        d: "Helicopters Terminals Motorboats Lamborginis",
    correct: "a",
    },
{
    question: "What year was JavaScript launched?",
        a: "1996",
    b: "1995",
        c: "1994",
    d: "none of the above",
        correct: "b",
},
];

const quiz = document.getElementById(“quiz”);

/**
 * @type {NodeListOf<HTMLInputElement>}
 */

const answerEls = document.querySelectorAll(".answer");

const questionEl = document.getElementById("question");

const a_text = document.getElementById(“a_text”);

const b_text = document.getElementById("b_text");

const c_text = document.getElementById(“c_text”);

const d_text = document.getElementById("d_text");

const submitBtn = document.getElementById(“submit”);

let currentQuiz = 0;

let score = 0;


loadQuiz();

function loadQuiz() {

    deselectAnswers();
const currentQuizData = quizData[currentQuiz];
    questionEl.innerText = currentQuizData.question;
a_text.innerText = currentQuizData.a;
    b_text.innerText = currentQuizData.b;
c_text.innerText = currentQuizData.c;
    d_text.innerText = currentQuizData.d;
}

function getSelected() {

    let answer = undefined;
answerEls.forEach((answerEl) => {
        if (answerEl.checked) {
        answer = answerEl.id;
        }
    });
return answer;

}

function deselectAnswers() {
answerEls.forEach((answerEl) => {
        answerEl.checked = false;
});

}

submitBtn.addEventListener("click", () => {
// check to see the answer
    const answer = getSelected();
if (answer) {
        if (answer === quizData[currentQuiz].correct) {
        score++;
    }
        currentQuiz++;
    if (currentQuiz < quizData.length) {
            loadQuiz();
    } else {
            quiz.innerHTML = `
            <h2>You answered correctly at ${score}/${quizData.length} questions.</h2>
                
                <button onclick="location.reload()">Reload</button>
            `;
        }
    }
});

The section below is HTML.

<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Quiz App</title>
    <link rel="stylesheet" href="style.css" />
        <script src="script.js" defer></script>
</head>
    <body>
    <div class="quiz-container" id="quiz">
            <div class="quiz-header">
            <h2 id="question">Question text</h2>
                <ul>
                <li>
                        <input type="radio" id="a" name="answer" class="answer"/>
                    <label id="a_text" for="a">Question</label>
                    </li>
                <li>
                        <input type="radio" id="b" name="answer" class="answer" />
                    <label id="b_text" for="b">Question</label>
                    </li>
                <li>
                        <input type="radio" id="c" name="answer" class="answer" />
                    <label id="c_text" for="c">Question</label>
                    </li>
                <li>
                        <input type="radio" id="d" name="answer" class="answer"/>
                    <label id="d_text" for="d">Question</label>
                    </li>
            </ul>
            </div>
        <button id="submit">Submit</button>
        </div>
</body>
</html>

Can anyone explain why the characteristic of word “checked” is “any”?
Why and how the “any” is used?

At a guess, your editor is trying to infer Typescript type information, but hasn’t been told that your answerEls are html form checkbox elements.

Thank you for your explanation.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

I assume you’re using VSCode, which doesn’t really make much distinction between Typescript and JavaScript (they use the same mechanism in the editor) when it tries to do things like autocomplete, or just basically check if your code has errors.

So if I use JSDoc syntax, which VSCode also understands, and specify what answerEls is:

Then VSCode now tells me what checked has to be instead of just a generic any:

1 Like

Is the “NodeListOf” in the first picture typed manually?

It is, and the format does matter. It’s wrapped in a comment. Read about the JSDoc utility (link in his post) to read about it. But yes, you’ll manually tell it it’s a list of nodes (hence nodeListOf) and each element in that list is an html form input element.

I would like to know why VScode knows how to deselect answers? Why does VScode know how to check? What does “answerE1.id” represent? is there any relationship between “answerE1.checked = false” and “answer = answerE1.id”?

So we know that vs code can handle JSDoc format, and we know that the array of elements (the NodeListOf) contend contains HTMLInputElement types. By the Mozilla Developer docs, we can see all the available attributes and methods of an input element - and those attributes include type, id , and checked (among others).

The JSDoc interface, built into vscode, knows what represent valid properties or attributes.

but how VScode can recognize which node the “checked” refers to? Do you mean the answerE1.id in the javascript refers to the id attribute in HTML file?

No, it checks the JavaScript code. And it can figure some stuff out from the code, some stuff needs hints. But JavaScript has rules, it’s a computer language. So if you write a program that understands those rules, you can get it to check JS code. So if the program can figure out, or it is told, that some variable value should be a checked property, it knows that has to be true or false. Then it’ll keep following it through the program.

Which parts are the checked properties in the code above?

Well, if you mean in the screenshot, the bit coming up with the detailed information in a popup? I mean the whole thing is “checked”, but that bit has had a bit more information about it given to VSCode a it’s a bit more specific.

Did you research the HtmlInputElement on Mozilla’s Developer site, as I’d suggested? That explicitly tells you what properties are common to all inputs, which apply to a particular type of input, what methods are available, and so on.

The checked property applies to a particular type of input - but if a given HtmlInputElement on that NodeListOf (the DOM array of inputs) is of that particular type, then it has those additional properties.

And Vscode is smarter than me, I’d have to keep researching it.

https://devdocs.io/dom/htmlinputelement

I would like to know which one between “answerE1.checked” & “answer = answerE1.id” is a boolean? can a boolean be set as a if condition??

I’m slightly at a loss here, I’m not sure whether we’ve just complicated things more for you.

Do you you understand what types are available in JS? Like number, string, boolean, object etc? As in what these are?

A boolean is either true or false, it’s one of those two values. In the example, you shouldn’t really need hints to tell you which one is a boolean, though I do understand they would help you a lot here. Is something checked? Yes or no, true or false. Is something id? That doesn’t make sense, id is a string, an identifier you’ve specified (<input id="my-input" />)

Seems to me your confusion stems from this? First, did you look at the link i sent? It explicitly tells you which properties of HtmlInputElement are Boolean values, which are strings, and so on. You will notice that id isn’t in that list, because it isn’t a property of an HtmlInputElement, but of HtmlElememt (but all form inputs inherit from both).

But your question about using a Boolean as an if condition had me wondering, are you comfortable with the concept of an expression? Basically, anything that javascript has to evaluate would be an expression. A rule of thumb is, if it’s something you could use on the right side of an equal sign, it’s an expression.

That matters, because inside that if statement, the parentheses contain an expression. Javascript evaluates that expression, reducing it to an actual value, and then tries to force it to a true or false by very specific rules. For example, "Snowmonkey" would be considered truthy (it coerces to true), while "" (an empty string) would not.

If you look in the MDN, it nicely explains expressions and how they’re used.

Thank you, I guess I understand after looking at the link.

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