3.5 Exercise
Hello
Zen and the art of Coding
Please email hello@zenandtheartofcoding.info for a password

Exercise - add a function

  • lets add that addTwoNums() from the previous section to our code
  • if you are deep diving with me and not just skimming this, there are actually a couple ways to see this function in action:
function addTwoNums(num1, num2) {
  return num1 + num2;
}
  • again, standard JS naming convention is camelCase for the name and its good practice to add those semi-colons ;

  • first:

    • in a browser, on any page (even the one you're reading this on), open up your developer tools to the JavaScript console and copy and paste the function in and hit enter

    • then call the function with the two numbers you want to add like this

      addTwoNums(2, 2);
      • before you even hit enter you might see the number 4, but hit enter to execute and get your return
  • we can also add this function to our script for a-dope-site

    • open up script.js in your dope site folder in VS Code and type or paste the function in that file, you can stick it right on the end if you want like this:
script.js
console.log("JavaScript is connected!");
 
document.addEventListener("DOMContentLoaded", function () {
  document.querySelector("h1").addEventListener("click", function () {
    this.textContent = "whoooaaaaa 🤯!";
    this.style.color = "#ECC246";
    this.style.fontSize = "3em";
  });
 
  document.querySelector("p").addEventListener("click", function () {
    this.textContent = "And now the paragraph is different! 🌈";
    this.style.color = "#D522DC";
    this.style.fontStyle = "italic";
    this.style.fontSize = "2em";
  });
});
 
function addTwoNums(num1, num2) {
  return num1 + num2;
}
  • hit save, open the index.html file in a browser (if its still open, refresh the page) and open up the JS console
  • now, the function is hard coded to the script and can be called the same as above in the console:
addTwoNums(2, 2);
  • or you can call the function in the script and console.log() out your return yourself:
  • remember when we said we can call functions inside of other functions, now you are going to call your function inside of the console.log() function
  • add this line right under your function:
script.js
console.log("JavaScript is connected!");
 
document.addEventListener("DOMContentLoaded", function () {
  document.querySelector("h1").addEventListener("click", function () {
    this.textContent = "whoooaaaaa 🤯!";
    this.style.color = "#ECC246";
    this.style.fontSize = "3em";
  });
 
  document.querySelector("p").addEventListener("click", function () {
    this.textContent = "And now the paragraph is different! 🌈";
    this.style.color = "#D522DC";
    this.style.fontStyle = "italic";
    this.style.fontSize = "2em";
  });
});
 
function addTwoNums(num1, num2) {
  return num1 + num2;
}
console.log(addTwoNums(2, 2));
  • save & refresh the page again to see 4 already there in the JS console