Help with this code in Javascript (event function)

Hi i have got an issue with this code it is not getting executed. Here is the codepen. https://codepen.io/Rolf-Nilssen/pen/dyLZpGp

function apply (){
let firstName = prompt (“What is your first name?”);
let age = prompt(“How old are you?”);

let h1 = document.querySelector(“h1”);

if (age >= 18) {
let heading = document.querySelector(“h1”);
heading.innerHTML = (“Hi” + firstName + “! Welcome to Swedish Cars!”);
} else {
heading.innerHTML =(“Sorry” + firstName + “, you cannot drive a Volvo yet.”);
}
}
let contactButton = document.querySelector("button);
applyButton.addEventListener(“click”,apply);

can you describe what is happening and what should be happening instead?

Hi there!

Two issues:

  • The second quotation mark is missing on “button” in the last query selector.

  • You assign the query selector to the variable “contactButton”, but you append the event listener to “applyButton”, needs to be one name.

I fixed both it worked.

Thank you Daniel. I was not able to detect that on my own.

You did the right thing and showed your code to us, and that’s how it works on the job: You let other devs in your team review your code, because you sometimes get blind for your own mistakes.

Another tip:
Use “const” as your standard variable. The re-assignable “let” is best left to loops and other structures where reassigning it is part of the method.

Using “const” can avoid errors and confusion in large, professional code bases with many contributors.

How would i write the same event function with const instead of let? I wonder what that would look like

Just replace let with const.

let firstName → const firstName

Now you can be sure that no other contributor will use that variable name without throwing an error. At least it will be easier to find during tests.

1 Like

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