Skip to content Skip to sidebar Skip to footer

What Is The Best "practice" Or Form Of Code In Javascript (example)

I am currently doing CS50. And i feel a little lost with javascript, i don't know the best way to do things or to write 'correct code'. I feel that in C and in Python, the lines to

Solution 1:

Just to show you the beauty of a language as JavaScript - here's two possible approaches (out of many, really), one simple, and the other a little bit more advanced with dynamic templates generation - all out of some data model predefined in code:

1. Simpler solution:

Use data-* attribute on your parent element to store the correct answer string.

Simply place your buttons into HTML and assign the correct answer value into the parent element data-answer attribute:

const ELS_answer = document.querySelectorAll("[data-answer]");

ELS_answer.forEach(EL => {

  // Assign click handler to parent element with data-answer attributeEL.addEventListener("click", (ev) => {

    // Get the data attribute of the parent elementconst correct = ev.currentTarget.dataset.answer;

    // Get the text of the clicked buttonconst answer = ev.target.closest("button").textContent;

    // Check if correctif (answer === correct) {
      alert("CORRECT! (PS: make button green here!)");
    } else {
      alert("Not correct :(");
    }
  });
  
});
<divdata-answer="Five"><h3>What goes after "Four"?</h3><buttontype="button">One</button><buttontype="button">Five</button><buttontype="button">Nine</button></div><divdata-answer="nice"><h3>This site is pretty ____</h3><buttontype="button">nice</button><buttontype="button">boring</button><buttontype="button">sweet</button></div><divdata-answer="8"><h3>How many bits are in a single byte?</h3><buttontype="button">4</button><buttontype="button">8</button><buttontype="button">16</button></div>

As you can see above, you're not polluting your JavaScript code logic with strings, and that code can work for an infinite number of trivia ("Multiple choice") questions and buttons.

2. Advanced solution

Keep in mind - data!

So how would you structure your data for the Part 1 (and even Part 2"Free response") of the CS50 Lab? You have multiple buttons (therefore think of it as an Array) and you have only one correct answer. And you also have types (currently two: Multiple choices and Free Response) therefore type, question, answers, correct can all be properties of each Object item inside the trivia Array.

Such can be modelled like:

const trivia = [

  { 
    // `type` will help you create specific HTML Elements markup (template)type: "multiple",
    // The question that goes into H3question: "What is the first word of the well known typesetting text?",
    // Loop this Array values to generate your buttons!answers: ["Ipsum", "Lorem", "Amet", "Sit", "Dolor"],
    // Here you can store the correct answercorrect: "Lorem",
  },
  
  {
    type: "free",
    question: "What is the best community driven website for developers?",  
    answers: [], // will be populated by user!correct: "Stack Overflow",
  },

];

given the above you can iterate your trivia Array and generate HTML.

If the currently iterating trivia item type is "multiple" - generate <h3> and your buttons. If the currently iterating trivia item type is "free" - generate <h3>, an <input type="text">, and a button.

// Trivia HTML templates functions:const templates = {
  multiple(data) { /* GENETATE THE "MULTIPLE" TEMPLATE and append to DOM */ }, 
  free(data)     { /* GENETATE THE "FREE" TEMPLATE and append to DOM */ },
  // In the future you can add more template types here
};

// Iterate your trivia objects and generate HTML 
trivia.forEach((data) => {
  templates[data.type](data); // call a specific template generator!
});

Given the above you can have as many trivia questions as you like. And in the future you can expand the above data for other interesting types.

To generate your buttons all you need to do is iterate the data.answers like:

const trivia = [
  { 
    type:     "multiple",
    question: "What is the first word of the well known typesetting text?",
    answers:  ["Ipsum", "Lorem", "Amet", "Sit", "Dolor"],
    correct:  "Lorem",
  },
  {
    type:     "free",
    question: "What is the best community driven website for developers?",  
    answers:  [],
    correct:  "Stack Overflow",
  },
];

// Utility functions// Create a new Element tag with properties:constnewEL = (tag, props) => Object.assign(document.createElement(tag), props);

// Trivia HTML templates:const templates = {

  multiple(data) {
  
    // Create the HeadingconstH3 = newEL("h3", {textContent: data.question});
    
    // Create the ButtonsconstBUTTONS = data.answers.reduce((DF, answer) => {
      // Create a single buttonconstBUTTON = newEL("button", {
        type:"button",
        textContent: answer,
        onclick() {
          // check if answer is correctif (data.correct === this.textContent) {
            alert("CORRECT! PS: style your button green here");
          } else {
            alert("Not norrect");
          }
        }
      });
      DF.append(BUTTON); // Append every button to the DocumentFragmentreturnDF;         // Return the DocumentFragment
    }, newDocumentFragment());
    
    // Finally, append everything to a specific DOM Element parentdocument.querySelector("#multiple").append(H3, BUTTONS);
  },
  
  free(data) {
    // TODO!// Similar as the above one// You can do it!!!
  }
};

// Iterate your trivia objects and generate HTML templates
trivia.forEach((data) => templates[data.type](data));
<divid="multiple"></div>

Regarding security / hacks

You're not in the phase to worry about security at this stage, for this Lab task. But it's nice you have that always in mind because it's extremely important!

Since the code (HTML, JS, Network requests, etc) that arrives to the browser can be spoofed or reverse-engeneered (like in the above Example 1. has the answers hardcoded in HTML; and Example 2. has them right in JS), in order to not allow a user to see the correct answers the proper approach would be to have the correct answers stored somewhere on your server (not visible to the user). Send the user selected answer to the server and check on server-side the correctness. Than the server should only respond to the browser with a response (i.e: "correct" / "wrong") so that the user interface can advance to the next question or give a final overall score. Even than, the server should never trust the user! Therefore you should implement a sort of user session using browser+backend technologies like i.e: a session cookie, and check if the data that arrives from the user matches the state in the database for that specific user (current question, correct questions count, timestamp, etc etc). Not a topic or problem that has to be solved at this stage in the CS50 Lab. But if you want - nobody stops you to explore and implement a more robust and secure solution on your own!

Solution 2:

Well, there are many wrongs in your code. However, you are on the correct track!

Something to keep in mind :

  • You can declare your functions outside the page load event.
  • When adding an event listener then you have to pass the function, not call it.

Try this :

//The load event is fired when the whole page has loadedwindow.addEventListener("load", function() {

    //Get all buttons in the pagelet buttons = document.querySelectorAll('button');

    //Set a click event listener for each button//When the event occurs then it calls the checkAnswer event handler callback and passes the event to it//Notice that the callback function is passed and not directly called with "()"!
    buttons.forEach(b => b.addEventListener("click", checkAnswer));
});

//Check answer functionfunctioncheckAnswer(event) { // <- here we get the event and use it//Get the presses buttonvar buttonPressed = event.target;

    //Check the content of the buttonif (buttonPressed.innerHTML == 'Uruguay') {
        //Change background to green
        buttonPressed.style.background = "green";
    } else {
        //Change background to red
        buttonPressed.style.background = "red";
    }
}

Edit :

Regarding the security aspect. In both codes provided (your's and your friend's), the user can manipulate the data in the HTML and get the correct answer. Such checks have to be server-sided where you tell your server to check the value sent by the user (the value of the clicked button) if it's correct or not. And then based on the server's answer you proceed on displaying if the chosen button/answer is correct or not.

Post a Comment for "What Is The Best "practice" Or Form Of Code In Javascript (example)"