js
#define js: \
I------------------------------------------------------------------------------------------------------\
I------------------------------------------------------------------------------------------------------\
I------------------------------------------------------------------------------------------------------\
I /$$$$$ /$$$$$$ /$$ /$$ \
I |__ $$ /$$__ $$ |__/ | $$ \
I | $$ /$$$$$$ /$$ /$$ /$$$$$$ | $$ \__/ /$$$$$$$ /$$$$$$ /$$ /$$$$$$ /$$$$$$ \
I | $$ |____ $$| $$ /$$/|____ $$| $$$$$$ /$$_____/ /$$__ $$| $$ /$$__ $$|_ $$_/ \
I /$$ | $$ /$$$$$$$ \ $$/$$/ /$$$$$$$ \____ $$| $$ | $$ \__/| $$| $$ \ $$ | $$ \
I | $$ | $$ /$$__ $$ \ $$$/ /$$__ $$ /$$ \ $$| $$ | $$ | $$| $$ | $$ | $$ /$$ \
I | $$$$$$/| $$$$$$$ \ $/ | $$$$$$$| $$$$$$/| $$$$$$$| $$ | $$| $$$$$$$/ | $$$$/ \
I \______/ \_______/ \_/ \_______/ \______/ \_______/|__/ |__/| $$____/ \___/ \
I | $$ \
I (((javascript || java script))) | $$ \
I |__/ \
I------------------------------------------------------------------------------------------------------\
I------------------------------------------------------------------------------------------------------\
I------------------------------------------------------------------------------------------------------I
"C"
Eloquent JavaScript (3rd edition) by Marijn Haverbeke
• modern web browsers are glorified JavaScript interpreters,
ie. its sent as plain text and ran user-side
• tries to mimic Java, meaning its similar to C
• semi-colons are allowed, but no way necessary; however they are recommended for readability
• camelCase is the standard (see AT "/Theory/Naming/camelCase")
• runs natively in web browsers
• incredibly robust infrastructure
• an amalgamation of ideas, philosophies and visions
• bad type system
FILES: FILES:
.js : javascript source file
.min.js : minified javascript source file
.mjs : ECMAScript module
COMMENTING:
• C style
Literals:
• C style
/<...>/<flags> : regex literal
VARIABLES: VARIABLES:
var [name] : declares a gf-scooped variable named [name]
let [name] : declares a b-scooped variable named [name]
const [name] : declares a b-scooped const variable; must be assigned imidiatly; cannot be reassigned
gf-scoope:
• "Global or Function SCOOPED"
• exists globally or inside a function
b-scoope:
• "Block SCOOPED"
• exists only inside the nearest curly braces ("{}"), C style
• case sensitive naming
— mostly C style:
• assignment
Data_types:
• automatic type conversions
• declaration -but not assignments, even if they are chained together-
are always moved to the top of the scoope by the JS engine
console.log(msg); //undefined, but not undeclared
var msg = "weird shit";
// ==
var msg;
console.log(msg);
msg = "weird shit";
null : nullptr
undefined : held by all variables not assigned a value
• null and undefined are evaluated equal
— Bools:
• false/true
— Numbers:
• holds ints or floats
• C style
— Symbols:
• returned by the Symbol() function
• a unique value
— Objects:
• a data group
• holds key-value pairs
• uses json syntax (see AT /JSON)
• members can be accessed with dot notation { Vera.Hight }
— Arrays:
[[element1](, [...])] : silently returns array
{ let myArray = [1, 2, 3]; }
• more like a tuple
— Stacks:
• also tuple-ish
• FIFO data structure
— Queues:
• reversed, more reality rooted sides ( the end is the First-In )
— Functions:
• refers to a function (see BELOW)
— Element:
• represents a DOM element (see AT ?!)
Special_values:
Infinity : infinity
— Infinity : negative infinity
Nan : Not a Number
OPERATORS: OPERATORS:
C_style:
=
+
++
+=
-
--
-=
*
*=
/
/=
%
%=
&&
||
|=
!
^
^=
==
!=
>
>=
<
<=
>>
<<
Logical:
=== : strict equals to comperason operator; does no type conversion
let a = 10;
let b = "10";
console.log( a == b ); // true
console.log( a === b ); // false
Artimetric:
— [...] : returns [...] with the logically corresponding sign
+[...] : returns [...] with the logically corresponding sign
let a = 10;
let b = -10;
let sa = -a; // -10
let sb = -b; // 10
let ra = +a; // 10
let rb = +b; // -10
Bitwise:
&= : bitwise and assignment
Keyword:
typeof [...] : returns type of [...]; ?!
[...] instanceof [type] : returns whether [...] is of type [type]
LOGIC: LOGIC:
if
?:
else
switch case
• C style
LOOPS: LOOPS:
C_style:
for
while
do while
break
continue
For_in:
for(<var> in <enumarable>){ <...> }
• iterate over the properties of <object> with the value of <var>
• arrays will enum to objects with the array indexes as their properties
// Iterating over an objects properties
var language = {
name: "Javascript",
tier: "C-",
year_of_origin: 1995
};
for(var i in language){
console.log(i);
}
// output:
name
tier
year_of_origin
// Using for-in on an array
var languages = ['JavaScript', 'Python', 'C++', 'Go', 'Rust'];
for(var i in languages){
console.log(i);
}
// output:
0
1
2
3
4
for_of:
for(<var> of <iteratable>){ <...> }
• iterate over the values of <iteratable> with the value of <var>
// Iterating an array
var languages = ['JavaScript', 'Python', 'C++', 'Go', 'Rust'];
for(var i of languages){
console.log(i);
}
// output:
JavaScript
Python
C++
Go
Rust
// Mistaking an object as an iteratable
var language = {
name: "Javascript",
tier: "C-",
year_of_origin: 1995
};
for(var i of language){
console.log(i);
}
// output:
Uncaught TypeError: language is not iterable
FUNCTIONS: FUNCTIONS:
function [name]([args]){ [...](return [...]) } : declares function
[name]([args]) : calls function
• every function returns Undefined unless specified otherwise
• every function has an internal (public) array, named "arguments";
it holds unnamed arguments
function log() {
for(let i = 0; i < arguments.length; i++){
console.log(arguments[i]);
}
}
• function declarations are always moved to the top of the code by the JavaScript engine,
therefor they can be called before they are (visibly/humanly) declared
Anon:
function(){ [...](, return [...]) } : silently creates a Function (variable)
• "anonymous function"
• by surrounding them with parenthasies they can be called imidiately
(function(){
console.log(10);
})(); // -> 10 printed
Short_hand:
<head> => <body>
• "arrow function"/"lambda"
<head>
([var]+) : syntax for anon function taking N arguments
[var] : short hand syntax for anon function taking 1 arguments
() : short hand syntax for anon function taking 0 arguments
<body>
{...} : full, normal body;
<value> : a single value which is returned
// NOTE: object creation notation clobbers with shorthand lambda bodies,
// they must be parenthesized
i => { value : i } // PARSE ERROR
i => ({ value : i }) // totally fine
Generators:
function* [name](){ [...] } : defines generator
[name]() : contructs a generator object
• generators are functions which execute in steps, return-ing a value at the end of each
• return behaves as regular inside a generator
• the keyword yield signals the end of a step; uppon encountering it execution stops and a value is yielded back
• yield can take up a value passed uppon execution continuation (see BELOW)
Member_functions:
next(([val])) : starts/continue-s execution;
returns an object:
.value - yield-ed/return-ed value
.done - whether the generator has return-ed
by passing an argument ([val]) sets the value of the yield expression
VARIABLE_MEMBERS: VARIABLE_MEMBERS:
valueOf() : returns primitive underleing value
[Bool]:
.toString() : returns [Bool] converted to string ("true"/"false")
[Number]:
.toString((<int> = 10)) : returns [Number] converted to string, in base <int>
.toLocaleString((<int> = 10)) : returns [Number] converted to locale specific string, in base <int>
.toFixed(<int>) : returns [Number] converted to string, rounded/chopped (implementation dependent) to <int> decimal places
.toExponential() : returns [Number] converted to string, in exponential notation
.toPrecision((<int>)) : returns [Number] converted to string, ?!
<string>:
.length : length/size; can be reassigned to chop off closing elements
[<int>] : returns <int>th char; 0 indexed
.charAt(<int>) : returns <int>th char; 0 indexed
.toLowerCase() : returns <string> converted to lower case
.toUpperCase() : returns <string> converted to upper case
.concat(<string>) : returns <string> with <string> concatonated to it
.substr([int1], [int2]) : returns [int2] chars staring from index [int1]
.substring([int1], [int2]) : returns chars from index [int1] till index [int2] exclusive
.indexOf(<string>(, <int>)) : searcehes for <string> in <string> starting from index <int>;
returns the starting index
.lastIndexOf(<string>(, <int>)) : reverse searcehes for <string> in <string> starting from index <int>;
returns the starting index
.trim() : returns <string> with leading and trailing white spaces removed
.trimStart() : returns <string> with leading white spaces removed
.trimEnd() : returns <string> with trailing white spaces removed
.replace([string1], [string2]) : returns <string> with all instances of [string1] with [string2]
.includes(<string>(, <int>)) : returns whether <string> contains <string>, starts searching from <int>
[Array]:
.length : highest index + 1; can be reassigned to chop off closing elements
[<int>] : returns <int>th char; 0 indexed
.push([...]) : appends [...] to the end of [Array]
.indexOf([...](, <int>)) : searcehes for [...] in [Array] starting from index <int>;
.isArray([...]) : returns whether [Array] contains [...]
[Stack]:
.push([...]) : pushes [...] to the top of the stack
.pop([...]) : pops and returns the top of the stack
[Queue]:
.push([...]) : pushes [...] to the back of the queue
.shift() : pops and returns the front element of the queue
.peek() : returns the front element of the queue
[Element]:
.remove() : delete-s *this node
.revomeChild() : delete-s all child nodes of *this
.innerHTML : variable representing the visible text of *this (feel free to reassign it)
.addElementListener([event], [func]) : listens for [even] on *this and calls [func] func when it happens
BUILTIN_FUNCTIONS: BUILTIN_FUNCTIONS:
alert(<string>) : throw-s a massive, annoying and invasive error popup
setTimeout([func], [size_t]) : waits [size_t] miliseconds before calling [func]
requestAnimationFrame([callback]) : calls [callback] the next time whenever the screen is ready to be rendered;
a timestamp is passed to [callback] so it can determine the state of the animation;
[callback] should call requestAnimationFrame(this) (recursively) to get a smooth animation
GLOBALS: GLOBALS:
Data_storing:
Cookies:
Storage:
• min. 2 MB allowed
• this data is not sent to sites on each request
• allows key/value pairs (refered to as a pair from now on) to be saved
• pair can only consist of strings ( auto conversion is still a thing)
localStorage:
• persists between requests
sessionStorage:
• persists between browsers sessions (closing && starting)
Shared_members:_
setItem([string1], [string2]) : stores a pair
getItem(<string>) : returns value by key look up
removeItem(<string>) : delete-s pair by key look up
clear() : delete-s all members
key(<int>) : returns key of pair at index <int>
length : number of stored items
Browser:
console:
• the little tab under the dev tools
.log([...]) : print [...] to the console
.table([...])
.trace()
document:
• the whole bloody page
manuvering:
getElementById(<string>) : returns reference to first element with id=<string>
getElementClassName(<string>) : returns an array like object with references to elements with class=<string>
getElementTagName(<string>) : returns an array like object with references to elements with tag=<string>
querySelector(<string>) : returns first element matching CSS selector <string> or NULL
querySelectorAll(<string>) : returns NodeList of elements matching CSS selector <string>
OBJECTS: OBJECTS:
• javascript is NOT object oriented; do not believe anyone who tells you otherwise
— it has class-es, but you should not use them they are cancer
• an object is considert to be an instance of a class only if it was constructed using that particular class-es constructor
• any object parsed from JSON will be a plain Object
• Objects act like dynamic associative arrays, for this reason the behaviour of instanceof is non-consistent and non-sensical
ASYNC: ASYNC:
• other sources will try to sell you that javascript is single threaded,
which could technically be true, but is not true in practice for any implementation
• whats more important is that: javascript has a concurrency model based on even loops
class Promise([function])
• an object symbolizing the execute of a function
• reading the state of a promise can indicate the status of its execution
• [function] starts async execution immediately uppon construction
Member_functions:
resolve([object])
all()
then([function]) : sets callback to be executed when promise has return-ed successfully
catch([function]) : sets callback to be executed when promise failed
reject() : returns failed promise
EVENTS: EVENTS:
• javascript is a misunderstood language;
because it has C style syntax people think it should be written as C,
while in reality javascript was supposed to be event oriented;
by the seems of it, current standart writers are confused too
• javascript is so misunderstood that over the years even the devs making it got confused;
now its a ruined incomprehensible mess that belongs to hell
• do not attempt to treat javascript as it were not event oriented and
do not indulge yourself with the lie that OOP has not partially replaced its
event orientedness,
because you're going to shoot yourself in the foot (see AT "./Observers")
class Event
• propagates upwards
• after the most specific elements event fired,
the event travels upwards calling all listeners in the way
// in the example bellow, both handlers are called
// IF innerDiv is clicked
<div id=outerDiv onclick="myHandlerFucktion1"> // called second
<div id=innerDiv onclick="myHandlerFucktion1"> // called first
</div>
</div>
// ----
div {
width: 50%;
height: 50%;
border: solid black 3px;
}
— the handler chain is the order by which
the handlers of a single element are fired:
most specific -> least specific -> action -> default
Member_function:
preventDefault() : do not call browser defined event handler
stopPropagation() : do not propagate upwards
Member_variables:
target : the source element which fired *this
○ types
animationend
transitionend
click
message
mouseover
mouseout
mousedown
mouseup
mousemove
Keydown
focus
submit
blur
change
load
unload
resize
Relevant_language_elements:
[element].addEventListener([type], [func], [bool]) : when [type] is fired [func] will be called;
if bool is true the event takes precendence over the elements childrens
akin listenners and will not be called on upwards propagation
[element].removeEventListener([type], [listener], bool)
string element.on[Type] : script to be ran when [type] is fired;
if a single function is set parenthases can be ommited;
[type]s first letter is capitalized
{ myElement.onClick = () => { console.log("msg") }; }
Observers:
— problem statement:
• browsers attempt to optimize
— lets suppose we have the following code:
<div id=myDiv style="width: 100px; height: 100px; background: green;">
</div>
let hMyDiv = document.getElementById('a'); // Handle for myDiv (our single tag)
function reeeeeeSize(){
hMyDiv.style.width = Math.floor(Math.random() * 1000) + 100 + "px"; // Resize myDivs width randomly
}
while(true){ // Repeatedly resize
reeeeeeSize(hMyDiv);
}
• the browser thinks: hm, i have no reason to render all these rapid changes,
the user only needs the end result anyways
• following this logic NO CHANGES ARE VISUALLY RENDERED
UNTIL THERE ARE SYNCRONOUS SCRIPTS EXECUTING
• result in the above example to never render
— consequences:
1. Animations cannot be programmed using the Main thread performing iteration
2. Querying rendered positions is border line useless
— example for the second point (modified from the previous):
<div id=myDiv style="width: 100px; height: 100px; background: green;">
</div>
// JavaScript
let hMyDiv = document.getElementById('a'); // Handle for myDiv (our single tag)
function reeeeeeSize(){
hMyDiv.style.width = Math.floor(Math.random() * 1000) + 100 + "px"; // Resize myDivs width randomly
}
reeeeeeSize(); // Resize
console.log(hMyDiv.getBoundingClientRect().width); // Query size
• when we query the width, the return-ed value corresponds to the divs size before it was altered
• observers are the OO solution to an event driven problem in an event oriented language
• an observer waits/monitors for some kind of change and executes a callback uppon encountering it
• out of pure retardation observers are implemented as class-es instead of being integrated into the language
// depricated
Variable_observer:
>used for monitoring the changes of an object |such as value changes|
[var].observe||
class Observer([callback])
Member_Functions:
observe([target], [options])
class MutationObserver()
Workers:
class Worker([path]) : creates worker executing script at [path]
• true multithreading threading
• worker scopes are separeted from the main thread (and eachother)
• to transfer data to/from a worker so called messages must be used
• interchangung messages is done by a set of functions and callback; see BELOW
Member_variables:
onmessage : callback function to be executed when the worker calls the global posMessage()
Member_Functions:
postMessage([val]) : sends a message to *this with [val]; inturn the workers internal onmessage callback is fired
terminate() : kills *this
Globals_inside_worker_namespace:
• become available inside the script *this executes
onmessage : callback function to be executed when *this.postMessage() is called
postMessage([val]) : sends message outwards; calls *this.onmessage
• the way the worker and main threads message related functions/variables are named makes describing the process confusing;
the example below should clarify
// Forwarding a message to a worker
// Main thread
const w = new Worker("myWorker.js");
w.postMessage("Good morning Sirs!");
// myWorker.js
onmessage = (msg) => {
console.log("Message from main thread: " + msg.data);
};
// Receiving a message from a worker
// Main thread
const w = new Worker("myWorker.js");
w.onmessage = (msg) => {
console.log("Message from worker thread: " + msg.data);
};
// myWorker.js
setTimeout(
(msg) => {
postMessage("Please do the needful and dont redeem!");
},
3000
);
/* NOTE: the reason we set a time out (ie. wait 3000 miliseconds) is that so
* we can set the onmessage handler before the message is posted;
* normally a the worker would be created, the handler set,
* a message sent to it and one received back, but that would overcomplicate the example
*/
MISC_KEYWORDS: MISC_KEYWORDS:
debugger : functions as a stand-alone instruction; if a debugger is available it functions as a breakpoint (auto called)
Library_recommendations:
— "highlight.js" code highlighter:
https://highlightjs.org/
— "tocbot" table of contents generator
• fills up an element with links to sections
• the table of contents will smooth-scroll to the selected section
• section positions and names are deducted from headings
• if you want the behaviour, but your page structure is not heading oriented,
you can scatter "visibility: hidden" 'phantom' headings
RELATED_PROGRAMS:
• see all AT "/Programs"
Browsers:
Explorer/Edge
Chrome
Brave
Firefox
Firefox-developer-edition
rhino : interactive javascript interpreter developed by Mozilla
node.js : see BELOW
node
#define node
nodejs
#define nodejs
node
#define node.js::
• non-browser js runtime environment
• if you ever wanted to write HTML/CSS/Javascript for the desktop,
this is your place to be
Programs:
node
npm <verb> : package manager for node
install <package>
start
npx <program> : used for executing node programs