JavaScript and Jupyter references

JavaScript is the most important language you need to learn as a frontend developer. Jupyter Notebooks is a convenient way to learn the language without the overhead of creating a full Website. Jupyter Notebooks had ChatGPT plugins to assist with design and troubleshooting problems. This Notebook has colors on HTML pages that were designed with a dark mode background.

output using HTML and CSS

Multiple cells are used to setup HTML in this lesson. Many of the JavaScript cells will use the output tag(s) to write into the HTML that has been setup.

  • %%html is used to setup HTML code block
  • "style" tag enables visuals customization
  • "div" tag is setup to receive data
%%html
<html>
    <head>
        <style>
            #output {
                background-color: #ff66fd;
                color: #123169;
                padding: 10px;
                border: 3px solid #000;
            }
        </style>
    </head>
    <body>
        <div id="output">
            Hello!
        </div>
    </body>
</html>
Hello!

output explored

There are several ways to ouput the classic introduction message: "Hello, World!"

  • Before you go further, open Console on your Browser. JavaScript developer leaves Console open all the time!!!
  • The function element.append() outputs to Console, this is often used for inspection or debugging.
  • "Hello, World" is a String literal. This is the referred to as Static text, as it does not change. Developer call this a hard coded string.
  • "Hello, World" literal is a parameter to element.append(), element.txt() and alert().
  • The element.txt function is part of Jupyter Notebook %%js magic. This is convenient for Notebook and testing.
  • The alert command outputs the parameter to a dialog box, so you can see it in this Jupyter notebook. The alert commands are shown, but are commented out as the stop run all execution of the notebook.
  • Note, in a Web Application Debugging: An alert is often used for less savy Developers. Console is used by more savy developers; console often requires setting up a lot of outputs. Source level debugging is the most powerful solution for debugging and does not require alert or console commands.
%%js // required to allow cell to be JavaScript enabled
element.append("hello");

// Browser Console output; debugging or tracing
element.append("I  love mr mortensen");
element.append("CSP is godo class");

// Document Object Model (DOM) output; output to HTML, CSS which is standard for a Web Page
// <mark>select element method</mark>: DOM native JavaScript get, document.getElementByID
document.getElementById("output").textContent = "MONKEY MONKEY";
// <mark>jQuery CSS-style method</mark>: Tag for DOM selector, $('#output')
$('#output').append('<br><b>MONKEY AGAIN!');  // br is break or new line, b is bold

// Jupyter built in magic element for testing and convenience of development
element.text("HAHAHAHEEHEEHHEEHEEEAAAA"); // element is output option as part of %%js magic
element.append('<br><b>BROoo!!!');

//alert("Hello, World!");

multiple outputs using one variable

This second example is a new sequence of code, two or more lines of code forms a sequence. This example defines a variable, thank goodness!!! In the previous example we were typing the string "Hello, World" over and over. Observe with the variable msg="Hello, World!"; we type the string once and now use msg over and over.

  • The variable "var msg =" is used to capture the data
  • The console.log(msg) outputs to console, be sure to Inspect it!
  • The element.text() is part of Jupyter Notebooks and displays as output blow the code on this page. Until we build up some more interesting data for Web Site, we will not use be using the Python HTML, CSS technique.
  • The alert(msg) works the same as previous, but as the other commands uses msg as parameter.
%%js
console.log("Variable Definition");

var msg = "I love definig variables";

// Use msg to output code to Console and Jupyter Notebook
console.log(msg);  //right click browser select Inspect, then select Console to view
element.text(msg);
//alert(msg);

output showing use of a function

This example passes the defined variable "msg" to the newly defined "function logIt(output)".

  • There are multiple steps in this code..
    • The "definition of the function": "function logIt(output) {}" and everything between curly braces is the definitions of the function. Passing a parameter is required when you call this function.
    • The "call to the function:"logIt(msg)" is the call to the function, this actually runs the function. The variable "msg" is used a parameter when calling the logIt function.
  • Showing reuse of function...
    • There are two calls to the logIt function
    • This is called Prodedural Abstraction, a term that means reusing the same code
%%js
console.log("Function Definition");

/*
* @param {number} num1 - The first number to multiply.
* @param {number} num2 - The second number to multiply.
* @returns {number} The product of num1 and num2.
*/
function multiplyNumbers(num1, num2) {
 // Check if either num1 or num2 is not a number
 if (typeof num1 !== 'number' || typeof num2 !== 'number') {
   throw new Error('Both inputs must be numbers');
 }

 // Perform the multiplication
 const product = num1 * num2;

 // Return the result
 return product;
}

const result = multiplyNumbers(5, 3);
element.append(result); // Output: 15

output showing Loosely typed data

JavaScript is a loosely typed language, meaning you don't have to specify what type of information will be stored in a variable in advance.

  • To define a variable you prefix the name with var or const. The variable type is determined by JavaScript at runtime.
  • Python and many interpretive languages are loosely typed like JavaScript. This is considered programmer friendly.
  • Java which is a compiled language is strongly typed, thus you will see terms like String, Integer, Double, and Object in the source code.
  • In JavaScript, the typeof keyword returns the type of the variable. Become familiar with type as it is valuable in conversation and knowing type help you understand how to modify data. Each variable type will have built in methods to manage content within the data type.
%%js
console.log("Examine Data Types");

/**
 * Displays the value and type of a variable.
 * @param {*} variable - The variable to display.
 */
function displayVariable(variable) {
    // Determine the type of the variable
    const type = typeof variable;
  
    // Display the value and type of the variable
    element.append('Value:', variable);
    element.append('Type:', type);
  
    // Change behavior based on the type
    switch (type) {
      case 'number':
        element.append('This is a number.');
        // Additional actions specific to number type can be added here
        break;
  
      case 'string':
        element.append('This is a string.');
        // Additional actions specific to string type can be added here
        break;
  
      case 'boolean':
        element.append('This is a boolean.');
        // Additional actions specific to boolean type can be added here
        break;
  
      case 'object':
        if (Array.isArray(variable)) {
          element.append('This is an array.');
          // Additional actions specific to array type can be added here
        } else if (variable === null) {
          element.append('This is null.');
          // Additional actions specific to null type can be added here
        } else {
          element.append('This is an object.');
          // Additional actions specific to object type can be added here
        }
        break;
  
      case 'undefined':
        element.append('This is undefined.');
        // Additional actions specific to undefined type can be added here
        break;
  
      case 'function':
        element.append('This is a function.');
        // Additional actions specific to function type can be added here
        break;
  
      default:
        element.append('Unknown type.');
        // Additional actions for unknown types can be added here
        break;
    }
  }
  
  const num = 42;
displayVariable(num);

const str = 'Hello, world!';
displayVariable(str);

const bool = true;
displayVariable(bool);

const arr = [1, 2, 3];
displayVariable(arr);

const obj = { name: 'John', age: 25 };
displayVariable(obj);

const undef = undefined;
displayVariable(undef);

const func = function () {
  console.log('Hello from a function!');
};
displayVariable(func);

Build a Person object and JSON

JavaScript and other languages have special properties and syntax to store and represent data. In fact, a class in JavaScript is a special function.

  • Definition of class allows for a collection of data, the "class Person" allows programmer to retain name, github id, and class of a Person.
  • Instance of a class, the "const teacher = new Person("Mr M", "jm1021", 1977)" makes an object "teacher" which is an object representation of "class Person".
  • Setting and Getting properties After creating teacher and student objects, observe that properties can be changed/muted or extracted/accessed.
%%html
<!-- load jQuery and tablesorter scripts -->
<html>
    <head>
        <!-- load jQuery and tablesorter scripts -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/js/jquery.tablesorter.min.js"></script>
        <style>
            /* CSS-style selector maps to table id or other id's in HTML */
            #jsonTable, #flaskTable {
                background-color: #353b45;
                padding: 10px;
                border: 3px solid #ccc;
                box-shadow: 0.8em 0.4em 0.4em grey;
                color: #fff;
            }
        </style>
    </head>

    <body>
        <!-- Table for writing and extracting jsonText -->
        <table id="jsonTable">
            <thead>
                <tr>
                    <th>Classroom JSON Data</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td id="jsonText">{
                        "players": [
                          {
                            "name": "Roger Federer",
                            "country": "Switzerland",
                            "rank": 8,
                            "age": 40,
                            "titles": [
                              "20 Grand Slam titles",
                              "103 ATP singles titles"
                            ]
                          },
                          {
                            "name": "Rafael Nadal",
                            "country": "Spain",
                            "rank": 3,
                            "age": 35,
                            "titles": [
                              "20 Grand Slam titles",
                              "88 ATP singles titles"
                            ]
                          },
                          {
                            "name": "Novak Djokovic",
                            "country": "Serbia",
                            "rank": 1,
                            "age": 34,
                            "titles": [
                              "20 Grand Slam titles",
                              "85 ATP singles titles"
                            ]
                          }
                        ]
                      }
                      </td>
                </tr>
            </tbody>
        </table>

    </body>
</html>
Classroom JSON Data
{ "players": [ { "name": "Roger Federer", "country": "Switzerland", "rank": 8, "age": 40, "titles": [ "20 Grand Slam titles", "103 ATP singles titles" ] }, { "name": "Rafael Nadal", "country": "Spain", "rank": 3, "age": 35, "titles": [ "20 Grand Slam titles", "88 ATP singles titles" ] }, { "name": "Novak Djokovic", "country": "Serbia", "rank": 1, "age": 34, "titles": [ "20 Grand Slam titles", "85 ATP singles titles" ] } ] }
%%js
class Player {
  constructor(name, country, rank, age, titles) {
    this.name = name;
    this.country = country;
    this.rank = rank;
    this.age = age;
    this.titles = titles;
  }

  getJSON() {
    const obj = {
      name: this.name,
      country: this.country,
      rank: this.rank,
      age: this.age,
      titles: this.titles
    };
    const json = JSON.stringify(obj);
    return json;
  }

  logIt() {
    console.info(this);
    element.append(this.getJSON());
  }
}

// Example usage:
const playerData = {
  name: "Roger Federer",
  country: "Switzerland",
  rank: 8,
  age: 40,
  titles: [
    "20 Grand Slam titles",
    "103 ATP singles titles"
  ]
};

const player = new Player(
  playerData.name,
  playerData.country,
  playerData.rank,
  playerData.age,
  playerData.titles
);

player.logIt();
%%html
<head>
    <!-- load jQuery and DataTables syle and scripts -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css">
    <script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
</head>
<table id="flaskTable" class="table" style="width:100%">
    <thead id="flaskHead">
    </thead>
    <tbody id="flaskBody"></tbody>
</table>

<script>
  $(document).ready(() => {
// Example data
const players = [
  new Player("Roger Federer", "Switzerland", 8, 40, ["20 Grand Slam titles", "103 ATP singles titles"]),
  new Player("Rafael Nadal", "Spain", 3, 35, ["20 Grand Slam titles", "88 ATP singles titles"]),
  new Player("Novak Djokovic", "Serbia", 1, 34, ["20 Grand Slam titles", "85 ATP singles titles"])
];

// Get the table body element
const tableBody = document.getElementById("flaskBody");

// Function to populate the table
function populateTable(data) {
  // Clear any existing rows
  tableBody.innerHTML = "";

  // Create a row for each player
  data.forEach(player => {
    const row = document.createElement("tr");
    row.innerHTML = `<td>${player.name}</td><td>${player.country}</td><td>${player.rank}</td><td>${player.age}</td>`;
    tableBody.appendChild(row);
  });
}

// Call the function with the player data to populate the table
populateTable(players);
})
</script>

Hacks

One key to these hacks is to build confidence with me going into final grade, I would like to see each student adapt this frontend work in their final project. Second key is the finished work can serve as review for the course, notes for the future in relationship to frontend.

  • Adapt this tutorial to your own work
  • Consider what you need to work on to be stronger developer
  • Show something creative or unique, no cloning
  • Be ready to talk to Teacher for 5 to 10 minutes. Individually!!!
  • Show in Jupyter Notebook during discussion, show Theme and ChatGPT
  • Have a runtime final in GithHub Pages (or Fastpage)