JavaScript Review

  1. JS in HTML. Including JavaScript in HTML with script element, with either src attribute or JS code.
    <script src="scripts/site.js" ></script>
    or
    <script>
    /* JS code here */
    console.log('hello from JS!');
    </script>
  2. Variables. Declare variables with let and sometimes const.
    Though you will see the older var, but avoid that.
    You may also see const which declares a constant (a variable that won't be changed).
    let courseName = 'CSCI E-12',
      courseTerm = 'Fall 2021',
      courseInstructor = 'David' ;
  3. Console is your friend. Your browser developer tools will be critical to use, and especially the "Console". Log to the console in JS with
    console.log('hello there!');
  4. When is the code executed?script in head or right before the body close tag.
    But it is good practice to rely on specific events, especially the DOMContentLoaded event!

    The .addEventListener method takes two arguments. The first is the event name as a string, and the second is the function to execute when that event happens.

    window.addEventListener('DOMContentLoaded', function(){
        /* here's where JS goes for when DOM is loaded */
        console.log('the DOM has been loaded and parsed!');
    });
  5. Events - load (and DOMContentLoaded), click, focus, blur, submit, mouseover, mouseout, keypress.
    HTML attributes are available, but don't use these. Add event listeners through JavaScript!
  6. Functions. Functions can be named, and they can also be anonymous (unnamed) when setting event handlers. Functions can have arguements.

    Named function that accepts an argument:

    function square(x) {
      let numberSquared = x*x;
      return numberSquared;
    }

    Anonymous functions — function() {} — are often used in setting event listeners

    window.addEventListener('DOMContentLoaded', function(){
    /* here's where JS goes for when DOM is loaded */
    console.log('the DOM has been loaded and parsed!');
    });
  7. DOM Methods can be used to access the DOM as well as manipulate it! Some common DOM methods are getElementById, getElementsByTagName, createElement, createTextNode, appendChild, and there are others!