(Still updating this file...)
- JavaScript is a lightweight, cross-platform, and interpreted scripting language.
- lightweight: low memory usage
- cross-platform: can run on multiple frameworks, operating systems, machine architecture1.
- interpreted: debugging at run-time, can be modified while running, code is evaluated line-by-line
- scripting: no scope, connects one language to another
- scripting languages are a subset of programming languages (all scripting languages are programming languages but not all programming languages are scripting languages)
- markup languages are presentational and a different kind of language (such as HTML, CSS, and our
.md
files written in [m]ark[d]own)
- It is well-known for the development of web pages... but many non-browser environments also use it.
- Get used to the word(s)
API
s- [A]pplication [P]rogramming [I]nterface
- EECS 1720 anyone?: Building Interactive Systems
- Get used to the word(s)
- JavaScript is a dynamic language.
- So? Each Javascript component is dynamic all the way from individual variables to the code itself.
- WOW. With the help of JavaScript, you can:
- Create variables on-the-go (during
runtime
) - Change their data-type
- Create new functions
- Replace existing logic
- Create variables on-the-go (during
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
- server side: allows interacting
- client side: how we interact with
- from client to server:
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))
- from client to server:
- what else?
- art:
p5.js
(we use it) - machine learning:
ml5.js
(you might use it)
- art:
- internal JavaScript: into the html
<script>
between tags</script>
<head>
here</head>
or<body>
here</body>
- external JavaScript: link to a separate file as an
extension.js
<head>
usually here</head>
<script type="text/javascript">
// Your javaScript code
</script>
- Dynamically typed
- accepts different data types over time
- Case sensitive format
- CASe SeNSitivE != case sensitive
- Lightweight
- ? used everywhere a.k.a JavaScript is the support for all browsers
- Event handling (includes
throwing
errors andcatching
them)- We could summarise a website as: a series of handled events, anticipated or not.
- Can we make only HTML websites? (yes but...)
- Interpreter centered
- We can get output without using the compiler
-
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>
- Cached JavaScript files can speed up page loading. Want to know more?2
- what exactly is website speed?
- So? Load these and decide (hint: open b after a... is a still loading?):
- Separate HTML and JavaScript code
- So? Easier to read and maintain
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 " "
)
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?)
-
Useful when dealing with
local
vglobal
variables.- Why? In JavaScript objects are variables: requires the keyword
,var
let
, orconst
to define one (and you need to define them!) - Recall:
Uncaught ReferenceError: myVariable is not defined
is outdated but you may still use it or come across itvar
- Why? In JavaScript objects are variables: requires the keyword
-
Useful when handling deletions.
- Why? JavaScript provides the functionality where you can define a property of an object as deletable.
- So? This qualifies the property to be deleted in strict mode
- Recall:
Uncaught SyntaxError: Delete of an unqualified identifier in strict mode
-
Enforcing reserved
keywords
A function is a set of statements that takes input(s), does some specific computation(s), and produces output.
All functions*:
-
start with the keyword:
function
-
followed by a uniquely chosen name:
funtion uniqueName
-
list of parameters:
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
- basic syntax statment:
return value;
- basic syntax statment:
- Object
- Classes
- Encapsulation
- Inheritence
- An
Object
is a unique entity that containsProperty
andMethod
- The characteristics of an
Object
are properties - The actions of an
Object
are methods- NOTE: A
Method
in JavaScript- is a
Property
of anObject
- whose
Value
is aFunction
- whose
- is a
- NOTE: A
- An Object is an instance of a
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:
- The returned value 'Git' comes from returning
${person.first_name}
phone_number.mobile
andphone_number.mobile2
are both accepted asnumbers
andletters
- The returned value 'Git' comes from returning
-
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:
- our existing
Object
instance, calledcoder
, has properties and methodsisStudying
andprintIntroduction
- these are inherited by our new
Object
instance, calledme
- (
coder
is the protoype we based our instanceme
on)
- (
- we then give our new
Object
instance a new property, calledname
- our prototype
Object
instance (coder
) does not have a propertyname
- (but our new instance
me
does...) - if we could use our new
Object
instance (me
) as a prototype... we could make a new newObject
instance which would inherit the propertyname
- (but our new instance
(HEY! maybe you have noticed how useful console.log()
is?)
- (Maybe you also noticed how
F12
might solve all problems?)
- Classes are like the blueprint of an
Object
- A
Class
can have many Objects- Why? Because a
Class
is a template
- Why? Because a
- Objects are instances of the class
- ? They are the implementation
In other words, Templates are to Instances as Classes are to Objects.
- You can also think of
classes
as special functions
WAIT. 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
- behaviours are defined using a constructor function
- behaviours are reused by reusing existing
Objects
- this is called inheritence
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?
- we try to access
property
person1.firstname andfunction
person1.getDetails_noaccess - because we changed how we defined the function, we have restricted the function's scope
- we get a return of undefined
- even though we know there is a
method
we can access through ourObject
instance, person (person1.getDetails_access())
- even though we know there is a
- we get a return of undefined
- Concept: some, one, or all
property
and/ormethod
of an Object is being used by another Object. - Unlike (most) OOP languages where classes inherit classes, in JavaScript an Object inherits Object
- certain features (
property
andmethod
) of one object can be reused by otherObjects
.
- certain features (
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()
- this is called
method overriding
method overriding
allows aMethod
in a child (ourstudent
) to have the same name as aMethod
in its parentClass
(ourperson
)- we use a
keyword
called super to refer to the immediate parent class instance variable
- we use a
Thanks to gfg for the helpful JavaScript information
Also thanks to this Mike for general HTML, CSS, JS, HTML-in-JS, JS-in-HTML, and other things you'll probably want to read
https://www.zdnet.com/article/the-fastest-websites-on-the-internet-today/