Tri 1 Week 5 - Javascript Tutorial & Practice
Quick launch into Variables, Functions, Arrays, IJavaScript HTML, using Jupyter Notebooks
- console.log output
- console.log output showing use of variable
- console.log output showing use of a function
- Showing reuse of a function
- Dynamic or Loosely typed language (string, number)
- Build a Person Function/Class object and JSON
- Build a Classroom Array/List of Persons and JSON
- IJavaScript and Table formatting using toHTML method
console.log output
Output to console using the classic programming introduction using a "Hello, World!" message.
- The command or function is console.log()
- "Hello, World" is a String literal. This is the referred to as Static text, as it does not change.
- "Hello, World" is a parameter to the console.log command.
- The console.log command outputs the parameter to the console, so you can see it in this Jupyter document.
- Note, in a Web Application, console.log is used for debugging and is not visible from the browser via HTML. It is used behind the scenes, when using Inspect->Console from the browser.
console.log("Good afternoon, World!");
//python equivalent = print("insert text here")
// console log helps us debug our pages
//python equivalent: msg = "Goodnight, World!";
var msg = "kachow"; //remember to put semicolons!
console.log(msg);
console.log output showing use of a function
This example passes the previously defined variable "msg" to the newly defined "function logIt(output)".
- There are two steps in the code, the definition of the function and the call to the function.
- "function logIt(output) {}" and everything between curly braces is the definitions of the function.
- "logIt(msg)" is the call to the function, this actually activates the function. If you remove this line you will not receive any output to console.
- Since the variable "msg" was defined in previous cell, it is used a parameter when calling the logMessage function.
function logIt(output) {
console.log(output);
}
logIt(msg); //message becomes the output of the function
//in jupyter notebooks, you don't need to re-define the variable, because we ran the cells above that already have the variable "msg" defined
Showing reuse of a function
Now that a function is defined, it can be called from any of the subsequent cell in the Jupyter notebook. A function/method, is a process of creating a procedural abstraction. This a programming practice to promote reuse versus coding the same thing over and over.
- First call sends a different string message
- Second call sends a number
console.log("Reuse of logIT")
logIt("Hello, Students!"); //defining logIt
logIt(2022)
Dynamic or Loosely typed language (string, number)
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. The variable type is determined at runtime. This is similar to Python and most interpretive languages. Java which is a compiled language is strongly typed, thus you will see string, integer, double, and object in the source code. In JavaScript, the "typeof" keyword returns the type.
function logItType(output) {
console.log(typeof output, ";", output);
}
console.log("Looking at dynamic nature of output types in JavaScript") //calling all the logIt types
logItType("hello"); // String
logItType(2020); // Number
logItType([1, 2, 3]); // List -- called an "object" in the output -- Object is generic for this Array, which similar to Python List
// there are different names for the types of print outputs, like string, number, and object
Build a Person Function/Class object and JSON
JavaScript functions have special properties and syntax is shown in many ways. In fact, a Class in JavaScript is a special function. Jupyter Notebooks seems to be more friendly to "function" definitions versus "Class", thus this lesson uses "function" and "prototype" versus "Class".
- Definition of function allows for a collection of data, the "function Person" allows programmer to retain name, github id, and class of designation.
- Definition of a prototype allow for the definition of a method associated with the function , the "Person.prototype.toJSON" allows the collection of data to be expressed in a json/string versus JavaScript object.
- Instance of a function, the "var teacher = new Person("Mr M", "jm1021", 1977)" line makes a variable "teacher" which is an object representation of "function Person".
// define a function to hold data for a Person
// critical part of every programming language is data
function Person(name, ghID, classOf) {
this.name = name;
this.ghID = ghID;
this.classOf = classOf;
this.role = "";
}
// define a setter for role in Person data
Person.prototype.setRole = function(role) {
this.role = role;
}
// define a JSON conversion "method" associated with Person
// starting a function called .toJSON
// JSON is a way for us to share data
Person.prototype.toJSON = function() {
const obj = {name: this.name, ghID: this.ghID, classOf: this.classOf, role: this.role};
const json = JSON.stringify(obj);
return json;
}
// make a new Person and assign to variable teacher
var teacher = new Person("Mrs. Derksen", "none", 1990);
teacher.setRole("Teacher");
// output of converting the Object and JSON/string associated with Teacher
logItType(teacher); // object type is easy to work with in JavaScript
logItType(teacher.toJSON()); // json/string is useful when passing data on internet; data shows up as text on the internet
Build a Classroom Array/List of Persons and JSON
Many key elements are shown again. New elements include...
- Building an Array, "var students" is an array of many persons
- Building a Classroom, this show forEach iteration through an array and .push adding to an array. These are key concepts in all programming languages.
// define a student Array of Person(s)
var students = [
new Person("Shreya", "rey444", 2023),
new Person("Jiya", "jiya-sav", 2023),
new Person("Sanika", "sanikasha", 2023),
new Person("Noor", "Nope1013", 2023),
new Person("Vaishavi", "vaishavi-chan", 2023),
new Person("Rahul", "protein-shake", 2023),
new Person("Sohni", "ok i pull up", 2023)
];
// define a classroom and build Classroom objects and json
function Classroom(teacher, students){ // 1 teacher, many student
// start Classroom with Teacher
teacher.setRole("Teacher");
this.teacher = teacher;
this.classroom = [teacher];
// add each Student to Classroom
this.students = students;
this.students.forEach(student => { student.setRole("Student"); this.classroom.push(student); });
// build json/string format of Classroom
this.json = [];
this.classroom.forEach(person => this.json.push(person.toJSON()));
}
// make a CompSci classroom from formerly defined teacher and students
compsci = new Classroom(teacher, students);
// output of Objects and JSON in CompSci classroom
logItType(compsci.classroom); // constructed classroom object
logItType(compsci.classroom[0].name); // abstract 1st objects name
logItType(compsci.json[0]); // show json conversion of 1st object to string
logItType(JSON.parse(compsci.json[0])); // show JSON.parse inverse of JSON.stringify
IJavaScript and Table formatting using toHTML method
This example builds a Classroom method _toHTML which is passed to the IJavaScript interpreter $$.html which renders output similarly to a real website.
- JavaScript in the _toHTML method is broken into three parts...
- Style part is building CSS inline formatting
- Body part is constructing the Table Rows (tr), Table Headings (th), and Table Data (td). The table data is obtained from a Classroom object. The JavaScript for loop allows the construction of a new row of data for each person object in the Array.
- Return part creates the HTML fragment for rendering
- The last line in the example $$.html is IJavaScript HTML interpreter and by passing the parameter of the _toHTML method it obtains HTML to render
// define an HTML conversion "method" associated with Classroom
// converting the javascript data to HTML for organization is at end, using "$$.html is IJavaScript HTML interpreter"
Classroom.prototype._toHtml = function() {
// HTML Style is build using inline structure
// defining variable "style"
var style = (
"display:inline-block;" +
"background:MediumPurple;" + // to change the color, search up "HTML color codes" and type the name of the color you want
"border: 8px black;" +
"fontcolor: black" +
"box-shadow: 0.5em 0.5em 0.4em grey;"
);
// HTML Body of Table is build as a series of concatenations (+=)
// concatenations = adding/building stuff
var body = ""; // using "" to define the variable allows us to have multiple outputs for the variable
// Heading for Array Columns
body += "<tr>"; // tr = table rows
body += "<th><mark style='color: black; background-color:pink'>" + "Name" + "</mark></th>"; // th = table headings
body += "<th><mark style='color: black; background-color:pink'>" + "GitHub ID" + "</mark></th>";
body += "<th><mark style='color: black; background-color:pink'>" + "Class Of" + "</mark></th>";
body += "<th><mark style='color: black; background-color:pink'>" + "Role" + "</mark></th>";
body += "</tr>";
// Data of Array, iterate through each row of compsci.classroom
for (var row of compsci.classroom) {
// tr for each row, a new line
body += "<tr>";
// td for each column of data
body += "<td>" + row.name + "</td>"; // td = table data
body += "<td>" + row.ghID + "</td>";
body += "<td>" + row.classOf + "</td>";
body += "<td>" + row.role + "</td>";
// tr to end line
body += "<tr>";
}
// Build and HTML fragment of div, table, table body
return (
"<div style='" + style + "'>" +
"<table>" +
body +
"</table>" +
"</div>"
);
};
// IJavaScript HTML processor receive parameter of defined HTML fragment
$$.html(compsci._toHtml());