JS Notes
JS Notes
JS Notes
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.
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.
//WRAPPER OBJECTS
4 primitive types in js have their respective equivalent wrapper object:
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];
a[0];
a[1];
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.
-----------------------------------
///Functions in JS:
1. Function declaration
2. Function expression
3. Arrow notation
let myObj={};
myObj.foo="value";
let myObj={
function createObj(a,b,c){
let obj={};
obj.a=a;
obj.b=b;
obj.c=c;
return obj;
}
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.
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.
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
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
Basically, if you creating object in the way above, is just the same as this:
var a= new Object();
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:
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;};
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;
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.
//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).
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;
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
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
- you can change the root node from document to other variable
- 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.
- 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
Modules are saved in either js or mjs extension. mjs is not widely supported
by
browser though in practice, it has advantages.
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};
///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.
///import
must be done on top of the js files
example:
import {item1,item2,item3} from "./path/to/file.js";
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.
///modules aggregation
you can make a module from submodules
the module then import from submodules, then export them e.g:
export {submodule_name} from "./submodule.js";
import("./module.js").then(
(Module)=>do something;
)
///NOTES
you can test your page ONLY in servers. file// protocol wont work.