JavaScript Writeup
What is Javascript used for?
- What is Javascript?
- Console.log output
- Variables
- Functions
- Dynamically and loosely typed language (string, number)
- Building a function class
What is Javascript?
Javascript is a fronend programming language that drives the web and internet. Every interaction on a website could be traced back to javascript and its functionalities.
Resources:
W3Schools
feecodecamp.org
javascript30.com
Console.log output
Console.log
is similar to the print()
function in python. However, running this command does not alter the content of the webpgae in anyway. The output of this command actually outputs to a terminal "Console" on the webpage. This could be useful for debugging or reviewing our code.
console.log("Hello World!")
var msg = "Hello World!";
console.log(msg);
function logIt(ipt) {
console.log(ipt)
}
logIt("Hello World");
logIt("Foo Bar!")
logIt(1337)
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
Building a function class
The this
keyword refers to the function itself, similar to self
in python. The variables defined in this way are isolated within their own scope.
Moreover, the JSON string created in the javascript file could be used as a message to communicate between frontend and backend. The JSON is a way to serialize data to transfer it over a network. Meaning we could use JSON to communicate between javascript programs and python programs.
// 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);
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());