JavaScript is the most important language you need to learn as a frontend developer. Jupyter Notebooks is a convenient way to learn portions of the language without the overhead of creating a full Website. Jupyter Notebooks have ChatGPT plugins to assist with design and troubleshooting problems. This Notebook has colors on HTML pages that were designed with a dark mode background.
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.
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 console.log() 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 console.log(), element.txt() and alert().
The element.textContent 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.
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.
class="highlight">
1
2
3
4
5
6
7
8
9
10
11
%%jsconsole.log("Variable Definition");varmsg="Hello, World Again!";//UsemsgtooutputcodetoConsoleandJupyterNotebookconsole.log(msg);//rightclickbrowserselectInspect,thenselectConsoletoviewdocument.getElementById("output").textContent=msg;element.append(msg);//alert(msg);
class="highlight">
1
<IPython.core.display.Javascript object>
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
class="highlight">
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
%%jsconsole.log("Function Definition");/*Function:logIt*Parameter:output*Description:Theparameteris"output"toconsoleandjupyterpage*/functionlogIt(msg){console.log(msg);element.append(msg);document.getElementById("output").textContent=msg;//alert(output);}//sequenceofcodebuildlogItparameterusingconcatenationvarmsg="Hello, Students!"//replacescontentofvariablevarclassOf="Welcome CS class of 2023-2024."logIt(msg+""+classOf);//concatenationofstrings
class="highlight">
1
<IPython.core.display.Javascript object>
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.
%%jsconsole.log("Examine Data Types");//FunctiontoaddtypeoftooutputfunctiongetType(output){returntypeofoutput+": "+output;}//FunctiondefintionfunctionlogIt(msg){console.log(getType(msg));//logsstringconsole.info(msg);//logsobjectdocument.getElementById("output").textContent=msg;element.append(getType(msg)+"");//addstoJupyteroutput//alert(getType(msg));}//CommonTypeselement.append("Common Types ");logIt("Mr M");//StringlogIt(1997);//NumberlogIt(true);//Boolean//ObjectType,thisdefinitionisoftencalledaarrayorlistelement.append("Object Type, array ");varscores=[90,80,100];logIt(scores);//ComplexObject,thisdefinitionisoftencalledhash,map,hashmap,ordictionaryelement.append("Object Type, hash or dictionary ");varperson={//key:valuepairsseperatedbycomma"name":"Mr M","role":"Teacher"};logIt(person);logIt(JSON.stringify(person));//methodusedtoconvertthisobjectintoreadableformat
class="highlight">
1
<IPython.core.display.Javascript object>
Build a Person object, JSON, and show output
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.
This code extracts JSON text from HTML, that was placed in DOM in a previous JavaScript cell, then it parses text into a JavaScript object. In addition, there is a for loop that iterates over the extracted object generating formated rows and columns in an HTML table.
Table generation is broken into parts…
table data is obtained from a classroom array inside of the extracted object.
the JavaScript for loop allows the construction of a new row of data for each Person hash object inside of the the Array.
in the loop a table row <tr> ... </tr> is created for each Hash object in the Array.
in the loop table data, a table column, <td> ... </td> is created for name, ghID, classOf, and role within the Hash object.
class="highlight">
1
2
3
4
5
6
7
8
9
10
11
12
13
----------------
| HTML |
| DOM |
| data output | - ref: id="data", id="output"
----------------
⇓ ⇑
get set
----------------
| JavaScript | - get data:
| code | const jsonText = document.getElementById("data").innerHTML;
|getElementById| - set output:
---------------- document.getElementById("output").innerHTML = htmlOut;
%%jsconsole.log("Classroom Web Page");//extractJSONtextfromoutputelementinHTMLpageconstjsonText=document.getElementById("data").innerHTML;//convertJSONtexttoaJavaScriptObjecttoprocessconstclassroom=JSON.parse(jsonText).classroom;console.log(classroom);//makeanHTMLOutformatforprettydisplay/*Templateliterals (`),canmakeHTMLgenerationmoreconcise;*themapfunctionsgeneratesrowstringsandthejoinmethodcombinesthem;*thisreplaceslongeranduglyforloopandstringconcatenation.*/consthtmlOut=`<table><thead><tr><th>Name</th><th>GitHubID</th><th>ClassOf</th><th>Role</th></tr></thead><tbody>${classroom.map(row=>`<tr><td>${row.name}</td><td>${row.ghID}</td><td>${row.classOf}</td><td>${row.role}</td></tr>`).join('')}</tbody></table>`;//assign/sethtmlOuttooutputelementinHTMLpagedocument.getElementById("output").innerHTML=htmlOut;//showrawHTMLconsole.log(htmlOut);element.append(htmlOut);
class="highlight">
1
<IPython.core.display.Javascript object>
Hacks
Work with output and objects.
Adapt this tutorial to your own work and interests, how many steps do you understand?
Relate console output on last step to a previous hack
Explain, how console.log can help find errors in code?
Try out ChatGPT Jupyter features; though I prefer using Web and cut-copy-paste