(Still updating this file…)
.md
files written in [m]ark[d]own)API
s
runtime
)Result:
I totally know JavaScript: performs like the best programming language ever
I thought Java was short for JavaScript: why do I get different random errors for the SAME LINE OF CODE!!!
This random behavior can and will build up certain complexities… in our case? Especially if using it in a project. A shared Group Project. With different files. And different styles.
No. We will use strict
and follow ES6
(what is this?)
FYI:
HTML: [H]yper [T]ext [M]arkup [L]anguage
CSS : [C]ascading [S]tyle [S]heets
So, usually you can think of HTML as content structure, CSS as content appearance, and JavaScript as content behaviour. But this is changing (confusion inevitable).
If we want anything to change on a webpage without reloading the entire page, we need JavaScript help me… that link is also useful in clarifying imperative
v declarative
programming… and it is PROBABLY USEFUL FOR UNDERSTANDING THE HOWS AND WHATS BEHIND YOUR BROWSER EXTENSION
Node.js
is the best! (this is debatable (not really) but it’s what we will use… because… it is what I use ^.^ (and it is powerful server-side))p5.js
(we use it)ml5.js
(you might use it)<script>
between tags </script>
<head>
here </head>
or <body>
here </body>
extension.js
<head>
usually here </head>
<script type="text/javascript">
// Your javaScript code
</script>
throwing
errors and catching
them)
JavaScript in <head>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function interact() {
document.getElementById("demo").innerHTML="Welcome to Building Interactive Systems";
}
</script>
</head>
<body>
<h2>JavaScript in Head</h2>
<p id="demo" style="color:green;">Is Interactive?</p>
<button type="button" onclick="interact()">Click it</button>
</body>
</html>
JavaScript in <body>
<!DOCTYPE html>
<html>
<center>
<body>
<h2>JavaScript in Body</h2>
<p id="demo">Is Interactive?</p>
<button type="button" onclick="interact()">Try it</button>
<script type="text/javascript">
function interact() {
document.getElementById("demo").innerHTML="Welcome to Building Interactive Systems";
}
</script>
</body>
</center>
</html>
JavaScript from External Files external.js
<!DOCTYPE html>
<html>
<center>
<body>
<h2>External JavaScript</h2>
<p id="demo">Is Interactive?</p>
<button type="button" onclick="interact()">Push it</button>;
<script type="text/javascript" src="external.js"></script>
</body>
</center>
</html>
Strict
mode can be enabled providing a set of restrictions that make your JavaScript code much more secure and helps you to maintain a high standard of coding. The JavaScript codes can now be optimized before execution by the engine.
Also known as strict mode pragma
, strict
has its own scope and can affect the whole file or individual methods
Something to note: our JSON
files are a type of re-strict
-ed form (of an ECMAScript literal. a what? a literal
refers to a value’s notation in code. We often see string literals
in the format: “this is a string”. Here, the literal
indicates that a string’s value is notated by double quotations " "
)
strict
?Just include the following where relevant (whole file? individual method?)
"use strict";
Auto-global variable declaration
what?
Remember me: if you mistakenly use a variable without its definition, JavaScript doesn’t throw an error instead it declares the variable in global scope which often leads to randomness and undesired outputs
Example:
"use strict"; // Turn on strict mode.
myVariable = 1;
Output:
Uncaught ReferenceError: myVariable is not defined
Using reserved keywords as variable names
what?
Remember me: JavaScript allows reserved keywords to be used as variable names! WHAT! Enable strict
if you need to control this nonsense.
Example:
"use strict"; // Turn on strict mode.
let eval = 5;
Output:
Uncaught SyntaxError: Unexpected eval or arguments in strict mode
Duplication of parameter names
what?
Remember me: JavaScript allows duplicate parameter names, we can prevent this using strict
Example:
"use strict"; // Turn on strict mode.
let eval = 5;
Output:
Uncaught SyntaxError: Unexpected eval of arguments in strict mode
Deletion of JavaScript elements
what?
Remember me: in strict mode scopes are static and don’t change over the lifetime. Deleting variables or functions is not allowed (but it is in regular mode)
Example:
"use strict"; // Turn on strict mode.
let myVariable = 1;
delete myVariable;
Output:
Uncaught SyntaxError: Delete of an unqualified identifier in strict mode
…(what is unqualified?)
Strict
Modelocal
v global
variables.
var
let
, or const
to define one (and you need to define them!)Uncaught ReferenceError: myVariable is not defined
var
Uncaught SyntaxError: Delete of an unqualified identifier in strict mode
keywords
A function is a set of statements that takes input(s), does some specific computation(s), and produces output.
All functions*:
function
funtion uniqueName
function uniqueName(param1, param2)
enclosed statements with curlies..: function uniqueName(param1, param2) { \\statements }
*All for our puposes at this time
function functionName(Parameter1, Parameter2, ..)
{
// Function body
}
Defining the Function
Before we can use a function, we have to… define it. All function definitions follow the same basic format. Remember the external.js
file? That file is just three lines, a function definition, like this one:
function calcAddition(number1, number2)
{
return number1 + number2;
}
Calling the Function with (optional) Parameters
Calling
a function means we want to use it (probably now-ish). If we defined the function with parameters, now is a good time to include those:
functionName(Value1, Value2, ..);
Returning Information
A function can (but is not required) to return some values using the keyword return
return value;
Object
is a unique entity that contains Property
and Method
Object
are propertiesObject
are methods
Method
in JavaScript
Property
of an Object
Value
is a Function
Class
psst: pretty much everything is an Object in JavaScript (yes, even functions, arrays, and strings!)
Object Literal
//Defining the object
let person = {
first_name: 'Git',
last_name: 'Hub',
//a useful method
getFunction : function(){
return (`The name of the person is ${person.first_name} ${person.last_name}`)
},
//we can have an object within an object
phone_number : {
mobile:'12345',
landline:'6789',
mobile2: 'ffgf'
}
}
console.log(person.getFunction());
console.log(person.phone_number.landline);
Output:
The name of the person is Git Hub
6789
Note:
${person.first_name}
phone_number.mobile
and phone_number.mobile2
are both accepted as numbers
and letters
Object Constructor
The this
.
//using a constructor
function person(first_name,last_name){
this.first_name = first_name;
this.last_name = last_name;
}
//creating new instances of person object
let person1 = new person('First','Last');
let person2 = new person('Git','Hub');
console.log(person1.first_name);
console.log(`${person2.first_name} ${person2.last_name}`);
Output:
First
Git Hub
Object.create() method
This creates a new object by using an existing object as the prototype of the newly created object.
// Object.create() example
// a simple object with some properties
const coder = {
isStudying : false,
printIntroduction : function(){
console.log(`My name is ${this.name}. Am I studying?: ${this.isStudying}.`)
}
}
// the Object.create() method
const me = Object.create(coder);
// "name" is a property set on "me", but not on "coder"
me.name = '1720';
// Inherited properties can be overwritten
me.isStudying = true;
me.printIntroduction();
Output:
My name is 1720. Am I studying?: true
IMPORTANT: in the example above you should have noticed that:
Object
instance, called coder
, has properties and methods isStudying
and printIntroduction
Object
instance, called me
coder
is the protoype we based our instance me
on)Object
instance a new property, called name
Object
instance (coder
) does not have a property name
me
does…)Object
instance (me
) as a prototype… we could make a new new Object
instance which would inherit the property name
(HEY! maybe you have noticed how useful console.log()
is?)
F12
might solve all problems?)Object
Class
can have many Objects
Class
is a templateIn other words, Templates are to Instances as Classes are to Objects.
classes
as special functionsWAIT. Unlike (most) OOP languages there are technically no classes in JavaScript (because… everything is an object).
INSTEAD we consider JavaScript to be a Prototype Based Object Oriented Language
Objects
The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance. –Mozilla Developer Network
The updated ES6
format for JavaScript implements a JavaScript version of classes
. Traditionally, classes
were simulated through Object
definitions. Let’s look at the different formats. Does ES6
make it easier to define and reuse an Object
?
ES6
// Defining class using es6
class Vehicle {
constructor(name, maker, engine) {
this.name = name;
this.maker = maker;
this.engine = engine;
}
getDetails(){
return (`The name of the bike is ${this.name}.`)
}
}
// Making object with the help of the constructor
let bike1 = new Vehicle('Hayabusa', 'Suzuki', '1340cc');
let bike2 = new Vehicle('Ninja', 'Kawasaki', '998cc');
console.log(bike1.name); // Hayabusa
console.log(bike2.maker); // Kawasaki
console.log(bike1.getDetails());
Output:
Hayabusa
Kawasaki
The name of the bike is Hayabusa.
Traditional
// Defining class in a Traditional Way
function Vehicle(name,maker,engine){
this.name = name,
this.maker = maker,
this.engine = engine
};
Vehicle.prototype.getDetails = function(){
console.log('The name of the bike is '+ this.name);
}
let bike1 = new Vehicle('Hayabusa','Suzuki','1340cc');
let bike2 = new Vehicle('Ninja','Kawasaki','998cc');
console.log(bike1.name);
console.log(bike2.maker);
console.log(bike1.getDetails());
Output:
Hayabusa
Kawasaki
The name of the bike is Hayabusa.
The process of wrapping property
and function
within a single unit is known as encapsulation
Example:
//an encapsulation example
class person{
constructor(name,id){
this.name = name;
this.id = id;
}
add_Address(add){
this.add = add;
}
getDetails(){
console.log(`Name is ${this.name}, Address is: ${this.add}`);
}
}
let person1 = new person('Git',21);
person1.add_Address('YorkU');
person1.getDetails();
Output:
Name is Git, Address is: YorkU
Alternatively, encapsulation
can also refer to restricting the scope of a variable within the Class
or Object
Example:
// Abstraction example
// we change the scope through the definition format of our function
function person(fname,lname){
let firstname = fname;
let lastname = lname;
// how to define a no access version
let getDetails_noaccess = function(){
return (`First name is: ${firstname} Last name is: ${lastname}`);
}
// how to define an accessible version
this.getDetails_access = function(){
return (`First name is: ${firstname}, Last name is: ${lastname}`);
}
}
let person1 = new person('NAME','LAST');
console.log(person1.firstname);
console.log(person1.getDetails_noaccess);
console.log(person1.getDetails_access());
Output:
undefined
undefined
First name is: NAME, Last name is: LAST
What happened?
property
person1.firstname and function
person1.getDetails_noaccessmethod
we can access through our Object
instance, person (person1.getDetails_access())property
and/or method
of an Object is being used by another Object.property
and method
) of one object can be reused by other Objects
.Example:
//Inheritance example
class person{
constructor(name){
this.name = name;
}
//method to return the string
toString(){
return (`Name of person: ${this.name}`);
}
}
//we use the super keyword to call the class constructor above
class student extends person{
constructor(name,id){
super(name);
this.id = id;
}
toString(){
return (`${super.toString()},Student ID: ${this.id}`);
}
}
let student1 = new student('NAME',22);
console.log(student1.toString());
Output:
Name of person: NAME, Student ID: 22
In the example above both Object
student and Object
person have the same Method
toString()
method overriding
method overriding
allows a Method
in a child (our student
) to have the same name as a Method
in its parent Class
(our person
)
keyword
called super to refer to the immediate parent class instance variablehttps://www.zdnet.com/article/the-fastest-websites-on-the-internet-today/