You are on page 1of 19

BASIC OF JS

variable declaration is done using:


- var -> function scope
- let -> block scope
- const -> block scope with efficiency compared to let

useful built-in function:


setInterval(function, interval in ms); -> end with clearInterval(); setTi-
meout(function, time in ms);
constructor Date -> whose object has several functions: getTime(),
etc

there are primitive data types in js:


- number (which is double-precission 64 bits, floating point numbers)
- string
- boolean
- undefined
- null
- Symbol (from ES6) --similar to Enums in java (check it out!)

other types are:


-object
-function
-array

js is a loose-typed language. there is no restriction on what type of data


can be held by a variable. When you declare a variable but not yet define
the value, js automatically asign a special type of value into it: undefined.

null and undefined have semantic difference. undefined means unset and
null means nothing.

Variables in js can be interrogated, means you can ask for the type of its
current value using typeof operator like this:

var matangduang=true;

typeof matangduang;
boolean

you need to note that typeof operator will return "object" on variable of type
null. This is a known bug and you can't do anything on it.

In js there is something called type coercion. It is what js engine do when


you try to do an operation on several variables or values with different
types thus it needs to convert one value to match the other one. this type
coercion also happens on operator "==". so if you run:

10 == "10"

it will return true. If you need to compare if two values are the same both in
values and its type, use "===" instead. the later operator doesn't do type
coercion. It is recommended on everyday use. In comparing objects, ===
will return true only if both variables refer to the same object in memory.

in addition of this coercion, every type of data has its own coresponding
boolean value, or called truthy values:
in number, only zero is false,
in string, only empty string is false,
both undefined and null are false,
no object is false,
no function is false,
no array is false.

//OBJECT ====> read on note about object and prototype.

//check out string interpolation

//WRAPPER OBJECTS
4 primitive types in js have their respective equivalent wrapper object:

- String, Boolean, Number, Object

This is what makes expression like "string".length valid

when such operation is invoked, the primitive is taken and being converted
to it's equivalent object for the operation only
//ARRAY
you can create an array inline:

var a=[0,1,2,3];

and access its items using it's index:

a[0];
a[1];

accessing item with index out of bound returns undefined.


adding array item:

a.[4]=4;
-> [0,1,2,3,4]

but the best way to modify an array is using pop, push, unshift and shift. ac-
cessing array length is done using length property.
an array is actually an object. it has a dunder proto property. As an object,
you can also add a property with name of a string like:

a.name="matangduang";

the property will be added, but it wont affect the length of the array and it
won't be considered as the array item.

Array has several built-in properties which contains functions:


pop
push
unshif
shift
foreach
Foreach is a function that takes a function as a parameter. It passes 3 ar-
guments to the function:
-the current item
-the index of the item
-the array itself

-----------------------------------
///Functions in JS:
1. Function declaration
2. Function expression
3. Arrow notation

default parameter in function:


ex:
function matangduang(a=1,b){
...
}

//rest parameter and arguments


1. rest arguments(spread):
let b=[...str];
let b=[0,...str,1]; //to merge iterables
matangduang(a,c,...b);//where b is an iterable

spread works only on iterables, another way that works on iterables


and array-like obj is Array.from
2. rest parameter:
function mtdg(a, ...b){
for(c of b){do_something};
}
OBJECT AND PROTOTYPE

Object is a bunch of key-value pairs.


Creating object, you can:
1. using inline notation like this

let myObj={};
myObj.foo="value";

and adding properties directly like this

let myObj={

"foo":"value"; //note the quotes and colon.


}

you can delete a property from an object using delete operator

2. by using a function, which is saver and tidier.

function createObj(a,b,c){
let obj={};
obj.a=a;
obj.b=b;
obj.c=c;
return obj;
}

and calling the function like: let obj=createObj(a,b,c);

3. by using a constructor, which is a tiddier modified function


function Obj(a,b,c){ //note the capital
this.a=a;
this.b=b;
this.c=c;
}

and calling this constructor like: let obj=new Obj(a,b,c);

Accessing obj values can be done by using dot notation or bracket nota-
tion.
myObj.foo;
myObj["foo"];
bracket notation can be used when the property is
not a valid identifier, or when the property name is dynamic.

//Ways to call a function:


1. call the function as is
2. as a property of an object
3. as a constructor
4. using the default property every function object has:call. example:
foo.call(<object whose "this" you want to bind>)

Everytime you call a function, there are default arguments used implicitly:
arguments and this.
According to the way you call the function, this refers to:
1. the global object (Window)
2. the object containing
3. the newly created object
4. the object used as argument.

the arguments thing is an object. It contains all the arguments the user in-
put, even those that the function doesn't ask for. the arguments thing has a
property called length.

Function in js is very flexible. if you call a function that require 2 parameters


but only provide one, the one that is omitted will get value undefined.
However, if you give an extra argument than the function asks for, it will be
abandoned.

Every function in js returns a value. Even a function that has no explicit re-
turn statement return a value, that is, undefined

There are two ways to create functions: finction declaration and function
expression

//PROTOTYPE

Unlike Java which use class as a blueprint in creating objects, javascript


has a prototype concept. In class concept, every objects created from a
function has a copy of function object of a property, but in concept of class,
there's onluy one copy of method and the objects derivated "knows" it. In
fact, in javascript, an object doesn't have a method. It only has properties,
but these properties may have values primitives, other object or a function.

everytime you create a function, like this:


function cool(){}
javascript will create two objects: the function itself (cool), and the proto-
type. You can access the prototype by using the property of the function:
cool.prototype. It happens in every function declaration, even if the function
doesn't create object. In the other side, the prototype has a property called
constructor which points to the function object.

Everytime you create object from a function using "new" keyword, your new
object will have a property called __proto__ (dunder-proto) which refers to
the prototype object of the function creating the object.

Anyway, even though you can access dunder-proto from the object, it is
more recommended to use prototype property instead.

When you're asking for a property from an object, the js engine first look for
it in the object itself. If it doesn't find it, then it will look for it in the prototype.
Anyway, if there are property with the same names in both prototype and
the object, the one that will show of will be the one in the object.
The advantage of using prototype is, you can define a property that will
share across all the objects derived from the function. The changes on the
prototype on runtime will also applied to the objects created, even to those
that was created before the changes happen. Using prototype, there will
only one copy of property but all the objects derived can access it.

//Object Function
If you create an object simply by typing:

var a={};

the object will still have a __proto__ property, which in turn if you access
this:

a.__proto__.constructor

, will return this: Objdect().

Basically, if you creating object in the way above, is just the same as this:
var a= new Object();

Object function is one of global functions.

Prototyepe is actually an object. And as one, it also has a __proto__ prop-


erty, which in turn refers to the Object's prototype(of the Object function).
Thus, it means that the prototype that automatically generated when you
create a function object is created by using "new Object()" expression.

As the result, when js engine looks for a property that is not present in the
object, it will look for it in the prototype, and if it still doesn't find it, it will in
turn look for it in the prototype of the prototype -- the Object's prototype.
That means, if you put a property in the Object's prototype, it will be availa-
ble to every objects in your system, which is generally not a good idea.

For your information, the hierarchy of prototypes is not endless. The Ob-
ject's prototype also has a __proto__ property but it points to null.
//INHERITANCE

In JS you can also apply inheritance and even multiple inheritances using
prototype. Look at this example:

first we create a function to create an object:

funtion a(name){ this.name=name};


var objA= new a("chris");

js engine will create a prototype of a, which can be accessed using the pro-
totype property. and you can add a property like this:
a.prototype.getName=function(){return this.name;};

Then you create another function to create another object:

function b(name){this.name=name};
var objB=new b("Sam");

Then, if you want b to inherits the property that a inherits, you can change
the __proto__ reference of the b's prototype to points to a's prototype.
Thus:

objB.__proto__.__proto__=a.prototype;

And now, you can call:


objB.getName();
which will return "Sam";
ADVANCED JS

Javascript is one of languages that implement functional programming.

in functional programming, functions are first-class functions -- means they


can be treated as an object.

In js, you can add properties like on objects to functions, pass them to vari-
ables or assign them as parameters to other functions (callbacks).

Higher order functions are the functions that operate on other functions, ei-
ther takes them as arguments (input) or returns them as output.

Examples of built-in higher-order-functions:

Array.prototype.map(function(item,index,array)) -> returns a new ar-


ray of values of the function callback on every elements of the array.

Array.prototype.filter(function_test([item,index,array])) -> returns a


new array consisting the item that pass (return true) on the callback
example: arr.filter((item)=>item>10);
Array.prototype.reduce(f([item,index,array]),accumulator)
-> if accumulator is given a value, item starts at index 0,
-> if accumulator is not provided, the first item became the ac-
cumulator and iteration starts at in dex 1.

another for loop for array:


for(let item of items){...}

//CLASS
is another way to create object other than using constructor function. exam-
ple:
class Banana{
constructor(){
this.a=...
}

//methods:
doSomething(){
...
}
}
the methods, anyway, will belong to the prototype instead of the object it-
self.
you can create a property to belong to the class itself(not the object nor the
prototype) by using static keyword.

//ASYNCHRONOUS
Asynchronous means that everything can happens independently in the
main program flow.
Asynchronous in JS is meant like, for example, in the queue of people lin-
ing for ordering food, the line is just one and everyone get a chance for or-
dering their food according their position in the queue. Anyway, the order of
people in the queue isn't always the same with the order they get the food
served. thus in JS, asynchronous means that the tasks are executed ac-
cording the queue, but there's a gap between the current task with the next,
and that gap is what this asynchronous about. It really different from two
task executed concurrently(paralel).

Asynchronous in JS is evolving in the order:

1.CALLBACK
Callback is one way among others used to handle async code, NOT
to define them. example:
addEventListener(event,callback), setTimeout(callback,1000s);

2.PROMISE
promises in JS are objects, created with constructor Promise() that
takes a function as an argument, we call it x, and x has two parameter:
- resolve
- reject

syntax:
promise=new promise(funcyion(resolve,reject){
...statements;

<if> resolve(<return a value);


<else>reject(<return some info>);
})
.then(<do something with value from resolve, can return a promise ar
something else>)
.[then(..)]
.catch(<do something with error from above code>);
example:
------------------------------
"use strict";

//creating promise to load an image


let promise=new Promise(function(resolve,reject){

let img=new Image();

img.src="https://www.purina.es/gato/purina-
one/sites/g/files/mcldtz1856/files/2018-06/Como_sa-
ber_si_un_gato_tiene_fiebre%281%29_0.jpg"; //some pic out there

img.onload=resolve(img); //if the image has loaded, then


resolve the promise
img.onerror=reject(new Error("can't load image"));//if the
promise fails
});

promise
.then(val=>{console.log(val);return val})//if the promise re-
solved, then show the image on console
.catch(error=>{
console.log("failed",error);//if the promise got rejected,
show what happened
})
.then(val=>console.log(val.height));

console.log(promise);
--------------------------------

3. ASYNC/AWAIT
It isbasically a syntax sugar coating "promise".
Syntax:
var a= async (arg){
try{
doSomething=await f(arg);
}
catch(new Error){
...
}
}

a(arg)
.then(f(val));
async function using await keyword in itself and it returns a promise.
To use the value inside the promise, use .then like example above.

DOM

js DOM
- is a child of Window object

- every node has a type: element/attribute/text/document

- nodes collection has a type: nodelist or HTMLCollection

- functions: getElementById, getElementsByTagName, getElementsBy-


ClassName, querySelector, querySelectorAll

- querySelector and querySelectorAll use css selector in quotes as param-


eter

- you can change the root node from document to other variable

- dom manipulations are element manipulation and node manipulation

- element manipulations examples: innerHTML, style, setAttribute (can be


used to add or change attributes), className, classList, classList includes
add, remove, item, contains, toggle

- node manipulations include: document.createElement, document.create-


TextNode, node.appendChild, node.insertBefore, parentNode.removeChild,
parentNode.replaceChild, node.after, node.before, node.insertAdja-
centHTML("position","<p>blablabla</p")
position can be: beforebegin, afterbegin, beforeend, afterend.

- handling events in js uses 2 ways: as a handler or use method addEven-


tListener("event",function(e))

- as handler you can add the function as attribute or add them in the object
model
some propertties of window object: innerWidth, is the width of the page.

some events on range type input: input and change. input will show the
changes in realtime.

some mouseEvent properties: pageX, clientX

some mouse events: mouseover, mouseenter, mouseleave, mousemove

- DOM traversing methods: parentNode, parentElementNode, next/pre-


viousSibling, next/previousElementSibling, children

- in every event object, you can call one of its method:preventDefault(), to


prevent the browser doing its default action on the event.

- event bubbling means that an event happening on one node will also ap-
ply on the element enclosing it and so forth. thus an event invoking one ele-
ments handler will also invoke the handler of elements enclosing it. to pre-
vent this, use a method in the EVENT OBJECT: stopPropagation().

- Or you can make use of this event bubbling, by specify the event handler
on the container element and then using e.target property to check on the
specific element the event is working on.

MODULE
Module is a way to split up your js code into several pieces

It is supported by most recent browsers.

Modules are saved in either js or mjs extension. mjs is not widely supported
by
browser though in practice, it has advantages.

The use of modules lays on export and import statement


///export
syntax:
export const pi=Math.PI;
export function matangduang(){donothing();};

you can put this export statement right before the item you would to export.

or the more convenient way is to put an export syntax at the end of your
module
to export all the items it contains in this form:
export {item1,item2,item3};

the items you can export, however, must be top-level items.

///default export
you can add default keyword on the export statement:
export default const banana=2;

this indicates that the item is by default exported from the module, also
means that importing it doesn't need to use same name as it is exported.

it can also be applied on anonymous functions

only one default export is allowed per module

///import
must be done on top of the js files
example:
import {item1,item2,item3} from "./path/to/file.js";

//on your HTML


in the script tag, you must include attribute type="module" -- you must not
add this
in regular js script.

the attribute is added in the tag with the top level js script.

the attribute can also be applied on the internal script if the script uses im-
port
statement.

///avoiding name conflicts


- use keyword `as` on export/import statement. eg:
import{a as b, c as d} from "./file.js";
- import as module object. eg:
import * as Name from "./file.js";

///modules aggregation
you can make a module from submodules

submodules can be placed in a folder, with export statement

the module then import from submodules, then export them e.g:
export {submodule_name} from "./submodule.js";

the import statement in the main js will be like:


import {submodule} from "./module.js";

///importing modules dynamically


recent version of js allow to load a module at a point in time using import()
funcyion

import function returns a promise

import("./module.js").then(
(Module)=>do something;
)

///NOTES
you can test your page ONLY in servers. file// protocol wont work.

modules are in strict mode automatically

no need to use defer attribute on the script tag


the scope of imported module is single script, not global. so you can't ac-
cess it
in the js console.

best practice is to create a class in a module, then export it

You might also like