JavaScript references

JavaScript is the most important language you need to learn as a frontend developer. It's a great first language for web developers to learn.

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("Hello, World!");
Hello, World!

console.log output showing use of variable

This second example is a sequence of code, two or more lines forms a sequence. This example defines a variable, then outputs the msg to terminal.

  • The variable "var msg =" is used to capture the data
  • The console.log(msg) outputs to console
var msg = "Hello, World!";
console.log(msg);
Hello, World!

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);
Hello, World!

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!");
logIt(2022)
Reuse of logIT
Hello, Students!
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 types in JavaScript")
logItType("hello"); // String
logItType(2020);    // Number
logItType([1, 2, 3]);  // Object is generic for this Array, which similar to Python List
Looking at dynamic nature of types in JavaScript
string ; hello
number ; 2020
object ; [ 1, 2, 3 ]

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
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
Person.prototype.toJSON = function() {
    const obj = {name: this.name, ghID: this.ghID, classOf: this.classOf, role: this.role};
    const json = JSON.stringify(obj);  // json/string is useful when passing data on internet
    return json;
}

// make a new Person and assign to variable teacher
var teacher = new Person("Mr M", "jm1021", 1977);  // object type is easy to work with in JavaScript
logItType(teacher);  // before role
logItType(teacher.toJSON());  // ok to do this even though role is not yet defined

// output of Object and JSON/string associated with Teacher
teacher.setRole("Teacher");   // set the role
logItType(teacher); 
logItType(teacher.toJSON());
object ; Person { name: 'Mr M', ghID: 'jm1021', classOf: 1977, role: '' }
string ; {"name":"Mr M","ghID":"jm1021","classOf":1977,"role":""}
object ; Person { name: 'Mr M', ghID: 'jm1021', classOf: 1977, role: 'Teacher' }
string ; {"name":"Mr M","ghID":"jm1021","classOf":1977,"role":"Teacher"}

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("Anthony", "tonyhieu", 2022),
    new Person("Bria", "B-G101", 2023),
    new Person("Allie", "xiaoa0", 2023),
    new Person("Tigran", "Tigran7", 2023),
    new Person("Rebecca", "Rebecca-123", 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
object ; [ Person { name: 'Mr M', ghID: 'jm1021', classOf: 1977, role: 'Teacher' },
  Person {
    name: 'Anthony',
    ghID: 'tonyhieu',
    classOf: 2022,
    role: 'Student' },
  Person { name: 'Bria', ghID: 'B-G101', classOf: 2023, role: 'Student' },
  Person { name: 'Allie', ghID: 'xiaoa0', classOf: 2023, role: 'Student' },
  Person {
    name: 'Tigran',
    ghID: 'Tigran7',
    classOf: 2023,
    role: 'Student' },
  Person {
    name: 'Rebecca',
    ghID: 'Rebecca-123',
    classOf: 2023,
    role: 'Student' } ]
string ; Mr M
string ; {"name":"Mr M","ghID":"jm1021","classOf":1977,"role":"Teacher"}
object ; { name: 'Mr M', ghID: 'jm1021', classOf: 1977, role: 'Teacher' }

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 index in the Array.
    • Return part create 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

Reference

// define an HTML conversion "method" associated with Classroom
Classroom.prototype._toHtml = function() {
  // HTML Style is build using inline structure
  var style = (
    "display:inline-block;" +
    "border: 2px solid grey;" +
    "box-shadow: 0.8em 0.4em 0.4em grey;"
  );

  // HTML Body of Table is build as a series of concatenations (+=)
  var body = "";
  // Heading for Array Columns
  body += "<tr>";
  body += "<th><mark>" + "Name" + "</mark></th>";
  body += "<th><mark>" + "GitHub ID" + "</mark></th>";
  body += "<th><mark>" + "Class Of" + "</mark></th>";
  body += "<th><mark>" + "Role" + "</mark></th>";
  body += "</tr>";
  // Data of Array, iterate through each row of compsci.classroom 
  for (var row in compsci.classroom) {
    // tr for each row, a new line
    body += "<tr>";
    // td for each column of data
    body += "<td>" + compsci.classroom[row].name + "</td>";
    body += "<td>" + compsci.classroom[row].ghID + "</td>";
    body += "<td>" + compsci.classroom[row].classOf + "</td>";
    body += "<td>" + compsci.classroom[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());
</table></div> </div> </div> </div> </div> </div>

Timer

There are ways to setup a delay.

Reference

$$.async();

console.log("Hello, World!");

var action = {
    $$: $$,
    console: console,
};

setTimeout(function() {
    $$.clear(0);    // clear output cell
    action.$$.sendResult("Goodbye!");
}, 2000);  // 2 second timer
'Goodbye!'

Hacks

Objective of JavaScript is to produce frontend code. Working in Jupyter Notebooks could help in the process of visualizing design with short and interactive feedback. However, my hope is that you move to Fastpages and play with Frontend code in that environment and do the REAL thing. Here is my suggestion.

Design UI screens that are prototypes for your project. Design at least one screen with data from a structure (like Person data above), that is used to dynamically create HTML. As an alternative to HTML text method above, look at Jokes post and usage createElement...

About Us DN Market Place Prototype

// define a function to hold data for a Person
console.log("DN Market Place About Us Page Prototype");
function Person(name,role) {
  this.name = name;
  this.role = 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
Person.prototype.toJSON = function() {
  const obj = {name: this.name, ghID: this.ghID, classOf: this.classOf, role: this.role};
  const json = JSON.stringify(obj);  // json/string is useful when passing data on internet
  return json;
}

// make a new Person and assign to variable teacher
var teacher = new Person("Mr M", "Teacher");  // object type is easy to work with in JavaScript
// logItType(teacher);  // before role
// logItType(teacher.toJSON());  // ok to do this even though role is not yet defined

// // output of Object and JSON/string associated with Teacher
// //teacher.setRole("Teacher");   // set the role
// logItType(teacher); 
// logItType(teacher.toJSON());  
// define a student Array of Person(s)
var students = [ 
  new Person("Pranavi", "Scrum Master"),
  new Person("Meena", "Backend Developer"),
  new Person("Madhumita", "Frontend Developer"),
  new Person("Shraddha", "DevOps Manager"),
];

// 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 => { 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

// define an HTML conversion "method" associated with Classroom
Classroom.prototype._toHtml = function() {
    // HTML Style is build using inline structure
    var style = (
      "display:inline-block;" +
      "border: 2px solid grey;" +
      "box-shadow: 0.8em 0.4em 0.4em grey;"
    );
  
    // HTML Body of Table is build as a series of concatenations (+=)
    var body = "";
    // Heading for Array Columns
    body += "<tr>";
    body += "<th><mark>" + "Name" + "</mark></th>";
    // body += "<th><mark>" + "GitHub ID" + "</mark></th>";
    // body += "<th><mark>" + "Class Of" + "</mark></th>";
    body += "<th><mark>" + "Role" + "</mark></th>";
    body += "</tr>";
    // Data of Array, iterate through each row of compsci.classroom 
    for (var row in compsci.classroom) {
      // tr for each row, a new line
      body += "<tr>";
      // td for each column of data
      body += "<td>" + compsci.classroom[row].name + "</td>";
      // body += "<td>" + compsci.classroom[row].ghID + "</td>";
      // body += "<td>" + compsci.classroom[row].classOf + "</td>";
      body += "<td>" + compsci.classroom[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());
DN Market Place About Us Page Prototype
Name GitHub ID Class Of Role
Mr M jm1021 1977 Teacher
Anthony tonyhieu 2022 Student
Bria B-G101 2023 Student
Allie xiaoa0 2023 Student
Tigran Tigran7 2023 Student
Rebecca Rebecca-123 2023 Student
</table></div> </div> </div> </div> </div> </div>

DN Marketplace Data Prototype

//const resultCont = document.getElementById("result");
function item(name,seller,price,condition) {
  this.name = name;
  this.seller = seller;
  this.price = price;
  this.condition = condition;
}


// define a JSON conversion "method" associated with Person
Item.prototype.toJSON = function() {
  const obj = {name: this.name, price: this.price, seller: this.seller};
  const json = JSON.stringify(obj);  // json/string is useful when passing data on internet
  return json;
}

var data = [
  new item("AP Physics C Barons Prep Book", "Meena A", "20", "Slightly used"),
  new item("Calculus Tutoring", "Bob the Builder", "100", "N/A"),
];

function format(item){ // 1 teacher, many student
  // start Classroom with Teacher
  //teacher.setRole("Teacher");
  this.item = item;
  this.classroom = [teacher];
  // build json/string format of Classroom
  this.json = [];
  this.format.forEach(item => this.json.push(item.toJSON()));
}


// //build data table
// for (const row of data) {
//     // tr for each row
//     const tr = document.createElement("tr");
//     // td for each column
//     const name = document.createElement("td");
//     const seller = document.createElement("td");
//     const price = document.createElement("td");
//     const condition = document.createElement("td");
//     // data is specific to the API
//     name.innerHTML = row.name;
//     seller.innerHTML = row.seller; 
//     price.innerHTML = row.price; 
//     condition.innerHTML = condition.price; 
//     // this build td's into tr
//     tr.appendChild(name);
//     tr.appendChild(seller);
//     tr.appendChild(price);
//     tr.appendChild(condition);
//     // add HTML to container
//     resultContainer.appendChild(tr);
// }








console.log("DN Market Place Item Info Prototype");


function Item(name,seller,price,condition) {
this.name = name;
this.seller = seller;
this.price = price;
this.condition = condition;
}


Item.prototype.toJSON = function() {
const obj = {name: this.name, price: this.price, seller: this.seller};
const json = JSON.stringify(obj);  // json/string is useful when passing data on internet
return json;
}


var firstItem = new Item("Scientific Calculator", "Kebabob", "10", "Brand new");  // object type is easy to work with in JavaScript

var theItems = [ 
new Item("AP Physics C Barons Prep Book", "Meena A", "20", "Slightly used"),
new Item("Calculus Tutoring", "Bob the Builder", "100", "N/A"),
];

function Marketplace(firstItem, theItems){ 
this.firstItem = firstItem;
this.marketplace = [firstItem];
this.theItems = theItems;
this.theItems.forEach(theItem => { this.marketplace.push(theItem); });
this.json = [];
this.marketplace.forEach(item => this.json.push(item.toJSON()));
}

// make a del norte marketplace 
dnMarket = new Marketplace(firstItem, theItems);
Marketplace.prototype._toHtml = function() {
  // HTML Style is build using inline structure
  var style = (
    "display:inline-block;" +
    "border: 2px solid grey;" +
    "box-shadow: 0.8em 0.4em 0.4em grey;"
  );

  // HTML Body of Table is build as a series of concatenations (+=)
  var body = "";
  // Heading for Array Columns
  body += "<tr>";
  body += "<th><mark>" + "Name" + "</mark></th>";

  body += "<th><mark>" + "Seller" + "</mark></th>";
  body += "<th><mark>" + "Price" + "</mark></th>";
  body += "<th><mark>" + "Condition" + "</mark></th>";
  body += "</tr>";

  for (var row in dnMarket.marketplace) {
    // tr for each row, a new line
    body += "<tr>";
    // td for each column of data
    body += "<td>" + dnMarket.marketplace[row].name + "</td>";
    body += "<td>" + dnMarket.marketplace[row].seller + "</td>";
    body += "<td>" + dnMarket.marketplace[row].price + "</td>";
    body += "<td>" + dnMarket.marketplace[row].condition + "</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(dnMarket._toHtml());
DN Market Place Item Info Prototype
Name Role
Mr M Teacher
Pranavi Scrum Master
Meena Backend Developer
Madhumita Frontend Developer
Shraddha DevOps Manager
</table></div> </div> </div> </div> </div> </div> </div>
Name Seller Price Condition
Scientific Calculator Kebabob 10 Brand new
AP Physics C Barons Prep Book Meena A 20 Slightly used
Calculus Tutoring Bob the Builder 100 N/A