Javascript: Web Development

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

CHEAT SHEET

JAVASCRIPT WEB DEVELOPMENT


Created by @Manz ( https://twitter.com/Manz ) https://lenguajejs.com/

n Number() = 42 s String() = 'text' a Array() = [1, 2, 3]


PROPERTIES PROPERTIES PROPERTIES

n .POSITIVE_INFINITY +∞ equivalent n .length string size n .length number of elements


n .NEGATIVE_INFINITY -∞ equivalent METHODS METHODS
n .MAX_VALUE largest positive value s .charAt(index) char at position [i] b .isArray(obj) check if obj is array
n .MIN_VALUE smallest positive value n .charCodeAt(index) unicode at pos. b .includes(obj, from) include element?
n .EPSILON diff between 1 & smallest >1 n .codePointAt(index) cp at position n .indexOf(obj, from) find elem. index
n .NaN not-a-number value s .fromCharCode(n1, n2...) code to char n .lastIndexOf(obj, from) find from end
METHODS s .fromCodePoint(n1, n2...) cp to char s .join(sep) join elements w/separator
s .toExponential(dec) exp. notation s .concat(str1, str2...) combine text + a .slice(ini, end) return array portion
s .toFixed(dec) fixed-point notation b .startsWith(str, size) check beginning a .concat(obj1, obj2...) return joined array
s .toPrecision(p) change precision a .flat(depth) return flat array at n depth
b .endsWith(str, size) check ending
b .isFinite(n) check if number is finite b .includes(str, from) include substring?
MODIFY SOURCE ARRAY METHODS

b .isInteger(n) check if number is int. a .copyWithin(pos, ini, end) copy elems


n .indexOf(str, from) find substr index
b .isNaN(n) check if number is NaN a .fill(obj, ini, end) fill array with obj
n .lastIndexOf(str, from) find from end
n .parseInt(s, radix) string to integer n a .reverse() reverse array & return it
.search(regex) search & return index
n .parseFloat(s, radix) string to float a .sort(cf(a,b)) sort array (unicode sort)
n .localeCompare(str, locale, options)
a .splice(ini, del, o1, o2...) del&add elem
a .match(regex) matches against string
r Regexp() ITERATION METHODS
= /.+/ig a .matchAll(regex) return iterator w/all
ai .entries() iterate key/value pair array
PROPERTIES s .normalize(form) unicode normalize
n .lastIndex index to start global regexp s ai .keys() iterate only keys array
.padEnd(len, pad) add end padding
s .flags active flags of current regexp s ai .values() iterate only values array
.padStart(len, pad) add start padding
b .global flag g (search all matches) s .repeat(n) repeat string n times CALLBACK FOR EACH METHODS
b .ignoreCase flag i (match lower/upper) s .replace(str|regex, newstr|func) b .every(cb(e,i,a), arg) test until false
b .multiline flag m (match multiple lines) s .slice(ini, end) str between ini/end b .some(cb(e,i,a), arg) test until true
b .sticky flag y (search from lastIndex) s a .map(cb(e,i,a), arg) make array
.substr(ini, len) substr of len length
b .unicode flag u (enable unicode feat.) a .filter(cb(e,i,a), arg) make array w/true
s .substring(ini, end) substr fragment
s .source current regexp (w/o slashs) o
a .split(sep|regex, limit) divide string .find(cb(e,i,a), arg) return elem w/true
METHODS
s .toLowerCase() string to lowercase n .findIndex(cb(e,i,a), arg) return index
a .exec(str) exec search for a match
s .toUpperCase() string to uppercase a .flatMap(cb(e,i,a), arg) map + flat(1)
b .test(str) check if regexp match w/str
s .trim() remove space from begin/end .forEach(cb(e,i,a), arg) exec for each
CLASSES
s .trimEnd() remove space from end o .reduce(cb(p,e,i,a), arg) accumulative
. any character \t tabulator o .reduceRight(cb(p,e,i,a), arg) from end
s .trimStart() remove space from begin
\d digit [0-9] \r carriage return
\D no digit [^0-9] \n line feed s .raw`` template strings with ${vars} ADD/REMOVE METHODS

\w any alphanumeric char [A-Za-z0-9_] o .pop() remove & return last element
d Date()
\W no alphanumeric char [^A-Za-z0-9_] n .push(o1, o2...) add elem & return length
METHODS
\s any space char (space, tab, enter...) o .shift() remove & return first element
\S no space char (space, tab, enter...) n .UTC(y, m, d, h, i, s, ms) timestamp n .unshift(o1, o2...) add elem & return len
\xN char with code N [\b] backspace n .now() timestamp of current time
\uN char with unicode N \0 NUL char n .parse(str) convert str to timestamp UNSHIFT
[1,2,3]
PUSH

CHARACTER SETS OR ALTERNATION n .setTime(ts) set UNIX timestamp SHIFT POP

[abc] match any character set n .getTime() return UNIX timestamp f Function() = function(a, b) { ... }
[^abc] match any char. set not enclosed UNIT GETTERS / SETTERS (ALSO .getUTC*() / .setUTC*() )
PROPERTIES

a|b match a or b n .get / .setFullYear(y, m, d) (yyyy) o .length return number of arguments


BOUNDARIES n .get / .setMonth(m, d) (0-11) s .name return name of function
^ begin of input $ end of input n .get / .setDate(d) (1-31) o .prototype prototype object
\b zero-width word boundary n .get / .setHours(h, m, s, ms) (0-23) METHODS

\B zero-width non-word boundary n .get / .setMinutes(m, s, ms) (0-59) o .call(newthis, arg1, arg2...) change this
GROUPING n .get / .setSeconds(s, ms) (0-59) o .apply(newthis, arg1) with args array
(x) capture group (?:x) no capture group n .get / .setMilliseconds(ms) (0-999) o .bind(newthis, arg1, arg2...) bound func
\n reference to group n captured n .getDay() return day of week (0-6)
QUANTIFIERS LOCALE & TIMEZONE METHODS
n number d date
x* preceding x 0 or more times {0,} n .getTimezoneOffset() offset in mins n NaN (not-a-number) r regular expresion
x+ preceding x 1 or more times {1,} s .toLocaleDateString(locale, options) s string f function
x? preceding x 0 or 1 times {0,1} s .toLocaleTimeString(locale, options) b boolean (true/false) o object
x{n} n ocurrences of x s .toLocaleString(locale, options) a array undefined
x{n,} at least n ocurrences of x s .toUTCString() return UTC date available on ECMAScript 2015 or higher
x{n,m} between n & m ocurrences of x s .toDateString() return American date n static (ex: Math.random())
ASSERTIONS s .toTimeString() return American time n non-static (ex: new Date().getDate())
x(?=y) x (only if x is followed by y) s .toISOString() return ISO8601 date
argument required
x(?!y) x (only if x is not followed by y) s .toJSON() return date ready for JSON
argument optional
CHEAT SHEET

JAVASCRIPT WEB DEVELOPMENT


Created by @Manz ( https://twitter.com/Manz ) https://lenguajejs.com/

Math o Object() = {key: value, key2: value2} s Set() WeakSet only obj as items
PROPERTIES PROPERTIES PROPERTIES

n .E Euler's constant o .constructor return ref. to object func. n .size return number of items
n .LN2 natural logarithm of 2 METHODS METHODS
n .LN10 natural logarithm of 10 o .assign(dst, src1, src2...) copy values s .add(item) add item to set ws
n .LOG2E base 2 logarithm of E o .create(proto, prop) create obj w/prop b .has(item) check if item exists ws
n .LOG10E base 10 logarithm of E o .defineProperties(obj, prop) b .delete(item) del item & return if del ws
n .PI ratio circumference/diameter o .defineProperty(obj, prop, desc) .clear() remove all items from set
n .SQRT1_2 square root of 1/2 o .freeze(obj) avoid properties changes ITERATION METHODS
n .SQRT2 square root of 2 o .getOwnPropertyDescriptor(obj, prop) si .entries() iterate items
METHODS
a .getOwnPropertyNames(obj) si .values() iterate only value of items
a .getOwnPropertySymbols(obj)
n .abs(x) absolute value o .getPrototypeOf(obj) return prototype
CALLBACK FOR EACH METHODS

n .cbrt(x) cube root b .is(val1, val2) check if are same value .forEach(cb(e,i,a), arg) exec for each
n .clz32(x) return leading zero bits (32) b .isExtensible(obj) check if can add prop
n .exp(x) return ex m Map() WeakMap only obj as keys
b .isFrozen(obj) check if obj is frozen
n .expm1(x) return ex-1 b .isSealed(obj) check if obj is sealed
PROPERTIES

n .hypot(x1, x2...) length of hypotenuse n .size return number of elements


a .keys(obj) return only keys of object
n .imul(a, b) signed multiply o .preventExtensions(obj) avoid extend METHODS

n .log(x) natural logarithm (base e) o .seal(obj) prop are non-configurable m .set(key, value) add pair key=value wm
n .log1p(x) natural logarithm (1+x) o .setPrototypeOf(obj, prot) change prot o .get(key) return value of key wm
n .log10(x) base 10 logarithm INSTANCE METHODS b .has(key) check if key exist wm
n .log2(x) base 2 logarithm b .hasOwnProperty(prop) check if exist b .delete(key) del elem. & return if ok wm
n .max(x1, x2...) return max number b .isPrototypeOf(obj) test in another obj .clear() remove all elements from map
n .min(x1, x2...) return min number b .propertyIsEnumerable(prop) ITERATION METHODS
n .pow(base, exp) return baseexp ** s .toString() return equivalent string mi .entries() iterate elements
n .random() float random number [0,1) s .toLocaleString() return locale version mi .keys() iterate only keys
n .sign(x) return sign of number o .valueOf() return primitive value mi .values() iterate only values
n .sqrt(x) square root of number CALLBACK FOR EACH METHODS
ROUND METHODS p Promise() async / await async functions
.forEach(cb(e,i,a), arg) exec for each
METHODS
n .ceil(x) superior round (smallest)
n .floor(x) inferior round (largest) p .all(obj) return promise g Generator() = function* () { ... }
n .fround(x) nearest single precision p .catch(onRejected(s)) = .then(undef,s) METHODS
n .round(x) round (nearest integer) p .finally(onFinish()) exec callback always o .next(value) return obj w/{value,done}
n .trunc(x) remove fractional digits p .then(onFulfilled(v), onRejected(s)) o .return(value) return value & true done
TRIGONOMETRIC METHODS HYPERBOLIC METHODS p .race(obj) return greedy promise (res/rej) .throw(except) throw an error
n .acos(x) arccosine n .acosh(x) p .resolve(obj) return resolved promise
n .asin(x) arcsine n .asinh(x) p .reject(reason) return rejected promise globals includes isFinite, isNaN, parseInt & parseFloat

n .atan(x) arctangent n .atanh(x)


p .allSettled(obj) return all fullfill/reject METHODS

n .cos(x) cosine n .cosh(x) p Proxy() Reflect same methods (not func) o eval(str) evaluate javascript code
n .sin(x) sine n .sinh(x) METHODS s encodeURIComponent(URI) = to %3D
n .tan(x) tangent n .tanh(x) s decodeURIComponent(URI) %3D to =
o .apply(obj, arg, arglist) trap function call
n .atan2(x, y) arctangent of quotient x/y o .construct(obj, arglist) trap new oper
Others
o .defineProperty(obj, prop, desc)
BigInt() = 9007199254740992n VARIABLE / CONSTANT DECLARATIONS
o .deleteProperty(obj, prop) trap delete
ES Modules modules o .enumerate(obj) trap for...in var deprecated variable let block scope
METHODS o .get(obj, prop, rec) trap get property const declare constant (read-only)
OPERATORS
import {m1, m2 as name} from "./file.js" o .getOwnPropertyDescriptor(obj, prop)
import obj from "./file.js" default import o .getPrototypeOf(obj) ?? nullish coalescing operator
export {m1, m2} export objs as modules o .has(obj, prop) trap in operator ?. optional chaining
p import("./file.js") dynamic import o .ownKeys(obj) FAST TIPS

o .preventExtensions(obj) func(a=1) default parameter value


JSON json file manipulation o .set(obj, prop, value) trap set property func(...a) rest argument (spread operator)
METHODS o .setPrototypeOf(obj, proto) (a) => { ... } function fat arrow (w/o this)
n .parse(str, tf(k,v)) parse string to object `string ${a}` template with variables
n .stringify(obj, repf|wl, sp) convert to str Symbol()
0bn binary (2) number n to decimal
PROPERTIES
0on octal (8) number n to decimal
e Error() s .iterator specifies default iterator 0xn hexadecimal (16) number n to decimal
PROPERTIES s .match specifies match of regexp
for (i in array) { ... } iterate array, i = index
s .name return name of error s .species specifies constructor function
for (e of array) { ... } iterate array, e = value
s .message return description of error METHODS
class B extends A () { } class sugar syntax
EvalError(), InternalError(), RangeError(), URIError(),
s .for(key) search existing symbols
ReferenceError(), SyntaxError(), TypeError() s .keyFor(sym) return key from global reg
CHEAT SHEET

JAVASCRIPT WEB DEVELOPMENT


Created by @Manz ( https://twitter.com/Manz ) https://lenguajejs.com/

window = Browser global object screen = info about screen / resolution performance = info about performance
PROPERTIES PROPERTIES PROPERTIES

b .closed check if window is closed n .availTop top-from space available o .navigation info about redir/type nav.
n .devicePixelRatio ratio vertical size pix n .availLeft left-from space available o .timing info about latency-load perf.
b .fullScreen check if window is fullscreen n .availWidth width space available METHODS
n .innerWidth width size (incl. scrollbar) n .availHeight height space available n .now() high precision timestamp
n .innerHeight height size (incl. scrollbar) n .width screen width resolution
n .outerWidth width size (incl. browser) n .height screen height resolution navigator = info about browser
n .outerHeight height size (incl. browser) n .colorDepth screen color depth (bits) PROPERTIES

n .length number of frames n .pixelDepth screen pixel depth (bits) b .cookieEnabled browser cookies on?
s .name inner name of window METHODS n .doNotTrack DNT privacy enabled?
s .status bottom statusbar text b .lockOrientation(mode|modearray) o .geolocation user-info geolocation
API/OBJECTS PROPERTIES b .unlockOrientation() remove locks s .language language in browser
o .applicationCache offline resources API n .maxTouchPoints max on device
o .console console browser API console = unofficial console browser API b .onLine browser work in online mode?
o .crypto cryptographic API METHODS s .userAgent identify browser of user
o .history session page history API .assert(cond, str1|obj1...) set a assert METHODS

o .location information about URL API .count(str) count (show number times) n .vibrate(n|pattern) use device vibration
o .localStorage storage for site domain .dir(obj) show object (expanded debug)
o .sessionStorage storage until closed .group() open new message group location = info about current URL
o .navigator information about browser .groupCollapsed() open new group coll. PROPERTIES

o .performance data about performance .groupEnd() close previous group s .href full document url
SCREEN PROPERTIES .table(array|obj, colnames) show table s .protocol https://www.emezeta.com/
.trace() show code trace s .username https://user:pass@www
o .screen information about screen
.timeStamp(str) put time on timeline s .password https://user:pass@www
n .screenX horizontal pos browser/screen
s .host https://emezeta.com:81/
n .screenY vertical pos browser/screen PERFORMANCE METHODS
s .hostname https://emezeta.com:81/
n .pageXOffset horizontal pixels scrolled .profile(name) start performance profile
s .port https://emezeta.com:81/
n .pageYOffset vertical pixels scrolled .profileEnd(name) stop perf. profile
s .pathname http://emezeta.com/42/
WINDOW PROPERTIES .time(name) start performance timer
s .hash http://emezeta.com/#contacto
o .opener window that opened this window .timeEnd(name) stop perf. timer
s .search http://google.com/?q=emezeta
o .parent parent of current window/frame LOG LEVEL METHODS
o .searchParams search params object
o .self this window (equal to .window) .log(str1|obj1...) output message s .origin source origin of document url
o .top top window of current win/frame .info(str1|obj1...) output information
METHODS .warn(str1|obj1...) output warning onClick="..." (HTML) .onclick = (JS func) 'click' (Listener)
s .btoa(str) encode string to base64 .error(str1|obj1...) output error e events (only popular events)
s .atob(str) decode base64 string to text MOUSE EVENTS
.focus() request send window to front window = global interaction func. e e
.onClick .onDblClick
.blur() remove focus from window METHODS
e .onMouseDown e .onMouseUp
USER INTERACTION METHODS
o .getSelection(id) return Selection object e .onMouseEnter e .onMouseLeave
.postMessage(msg, dst, transf) send .alert(str) show message (ok button) e .onMouseMove e .onMouseOver
o .open(url, name, options) open popup s .prompt(str, def) ask answer to user e e
.onMouseOut .onWheel
.stop() stop window loading b .confirm(str) show message (ok, cancel) KEYBOARD EVENTS
b .find(str, case, back, wrap, word, fr, d) e .onKeyDown e .onKeyUp
.print() open print document window history = page history on tab e .onKeyPress
PROPERTIES
ANIMATION METHODS LOAD/OBJECT EVENTS
n .requestAnimationFrame(cb(n)) n .length number of pages in historytab
e .onDOMContentLoaded e .onLoad
n .state return state top history stack
.cancelAnimationFrame(reqID) e .onAbort e .onError
METHODS
TIMER METHODS e .onResize e .onScroll
n .setTimeout(f(a...), ms, a...) delay&run .back() go prev page (same as .go(-1)) e .onBeforeUnload e .onUnload
.clearTimeout(id) remove timeout .forward() go next page (same as .go(1)) FORM/FIELDS EVENTS

n .setInterval(f(a...), ms, a...) run every


.go(n) go n page (positive or negative) e .onBlur e .onFocus
.pushState(obj, title, url) insert state e .onChange e .onInput
.clearInterval(id) remove interval .replaceState(obj, title, url) repl. state e .onInvalid e .onSelect
SCREEN METHODS
e .onReset e .onSubmit
.scrollBy(x, y) scroll x,y pixels (relative) storage localStorage / sessionStorage ANIMATION/TRANSITION EVENTS
.scrollTo(x, y) scroll x,y pixels (absolute) PROPERTIES e .onDragEnter e .onDragLeave
.moveBy(x, y) move window by x,y (rel) n .length number of items in storage e .onDragStart e .onDragEnd
.moveTo(x, y) move window to x,y (abs) METHODS e .onDragOver e .onDrag e .onDrop
.resizeBy(x, y) resize win by x,y (rel) s .key(n) return key name on position n ANIMATION/TRANSITION EVENTS
.resizeTo(w, h) resize win to WxX (abs) s .getItem(key) return value of item key e .onAnimationStart e .onAnimationEnd
STYLESHEET METHODS
.setItem(key, value) set or update key e .onAnimationIteration e .transitionEnd
o .getComputedStyle(elem, pseudelem) .removeItem(key) delete item with key
a .matchMedia(mediaq) match CSSMQ .clear() delete all items for current site
CHEAT SHEET

JAVASCRIPT WEB DEVELOPMENT


Created by @Manz ( https://twitter.com/Manz ) https://lenguajejs.com/

document = Document object e Element() = Element object a Attr() = Attribute object


PROPERTIES PROPERTIES PROPERTIES

s .characterSet document charset s .accessKey if exist, shortcut key s .name name of element attribute
s .compatMode quirks or standard mode o .attributes array of Attr objects s .value value of element attribute
s .cookie return all cookies doc string o .classList DOMTokenList of classes
s .designMode return design mode status s .className classes list to string t DOMTokenList() = List of classes
s .dir return direction text: "rtl" or "ltr" s .id id string of element PROPERTIES

s .doctype return document type (DTD) s .name name string of element n .length number of items
s .domain return document domain s .tagName HTML tag of element METHODS
s .documentURI return document URL POSITION, SIZE AND SCROLL PROPERTIES b .contains(item) check if item exists
s .lastModified return date/time modific. n .clientTop top border width element .add(item) add item to list
s .origin return document's origin n .clientLeft left border width element s .item(n) return item number n
s .readyState return current load status n .clientWidth inner width element .remove(item) del item from list
s .referrer return previous page (referrer) n .clientHeight inner height element b .toggle(item) del item if exist, add else
s .title return document title n .scrollTop top-position in document
s .URL return HTML document URL n .scrollLeft left-position in document n Node() = Minor element (elem. or text)
o .location information about URL n .scrollWidth width of element PROPERTIES
ELEMENTS PROPERTIES n .scrollHeight height of element s .baseURI absolute base URL of node
o .activeElement focused element GET/SET HTML CODE PROPERTIES s .namespaceURI namespace of node
o .body return body element s .innerHTML get/set HTML inside elem s .nodeName name of node
o .currentScript return active script s .outerHTML get/set HTML (incl. elem) s .nodeType 1=element, 2=text, 9=doc
o .defaultView return window element METHODS
s .nodeValue value of node
o .documentElement first element (root) s .prefix namespace prefix of node
o .head return head element
o .closest(selec) closest ancestor s
a .textContent text of node and children
o .scrollingElement first scrollable elem. .getElementsByClassName(class)
NAVIGATION PROPERTIES
a .getElementsByTagName(tag)
DOCUMENT ARRAY PROPERTIES
o .querySelector(selec) return first elem o .childNodes children nodes collection
a .anchors array of images elements a .querySelectorAll(selec) return elems o .firstChild first children (include text)
a .applets array of applets elements b .matches(selec) match with this elem? o .lastChild last children (include text)
a .embeds array of embeds elements .insertAdjacentHTML(posstr, html) o .nextSibling immediate next node
a .forms array of forms elements ATTRIBUTE METHODS
o .previousSibling immediate prev node
a .images array of images elements o .parentElement immediate parent elem
b .hasAttributes() exists attributes?
a .links array of links elements o .parentNode immediate parent node
b .hasAttribute(name) exist attribute?
a .plugins array of plugins elements o .ownerDocument return document
s .getAttribute(name) return value
a .scripts array of scripts elements METHODS
STYLESHEET PROPERTIES
.removeAttribute(name) del attribute
.setAttribute(name, value) set attrib. o .appendChild(node) add node to end
a .styleSheets array of style files elem o .cloneNode(child) duplicate node
CLIENTRECT (POSITION AND SIZES) METHODS
o .preferredStyleSheetSet preferred css o .compareDocumentPosition(node)
o .selectedStyleSheetSet selected css o .getBoundingClientRect() return pos.
b .contains(node) node is descendant?
a .getClientRects() return pos/size array
METHODS b .hasChildNodes() node has childs?
o .adoptNode(node) adopt from ext doc o .insertBefore(newnode, node)
e Event() = Event on action
o .createAttribute(name) create Attr obj b .isDefaultNamespace(nsURI)
PROPERTIES
o .createDocumentFragment() b .isEqualNode(node) check if are equal
o .createElement(tag) create Element obj b .bubbles true=bubble, false=captures s .lookupNamespaceURI() ret namesp.
o .createEvent(type) create Event object b .cancelable event is cancelable? s .lookupPrefix() return prefix for a ns
o .createRange() create Range object o .currentTarget current element .normalize() normalize-form children
o .createTextNode(text) create TextNode b .defaultPrevented preventDefault() call o .removeChild(node) del node & return
o .enableStyleSheetsForSet(name) n .detail additional event info o .replaceChild(newnode, oldnode)
o .importNode(node, desc) import copy n .eventPhase current stage (0-3)
o .getElementById(id) find elem with id b .isTrusted user action or dispatched c ChildNode()
a .getElementsByName(name) w/ name o .target reference to dispatched object METHODS

o .getSelection(id) return Selection object n .timeStamp time when was created o .remove() remove specified node
s .type type of event
r ClientRect() = Coords of element METHODS
p ParentNode()
PROPERTIES
PROPERTIES
.preventDefault() cancel event
n .top top coord of surrounding rect .stopImmediatePropagation() n .childElementCount number of children
n .right right coord of surrounding rect .stopPropagation() prevent being called o .children children elements
n .bottom bottom coord of surrounding r. o .firstElementChild first children elem.
n .left left coord of surrounding rect o .lastElementChild last children elem.
t EventTarget (use over elements)
n .width width coord of surrounding rect
METHODS n NonDocumentTypeChildNode()
n .height height coord of surrounding r.
.addEventListener(ev, cb(ev), capt) PROPERTIES

.removeEventListener(ev, cb(ev), capt) o .nextElementSibling next element


b .dispatchEvent(ev) o .previousElementSibling prev element

You might also like