\documentclass[10pt,a4paper]{article} % Packages \usepackage{fancyhdr} % For header and footer \usepackage{multicol} % Allows multicols in tables \usepackage{tabularx} % Intelligent column widths \usepackage{tabulary} % Used in header and footer \usepackage{hhline} % Border under tables \usepackage{graphicx} % For images \usepackage{xcolor} % For hex colours %\usepackage[utf8x]{inputenc} % For unicode character support \usepackage[T1]{fontenc} % Without this we get weird character replacements \usepackage{colortbl} % For coloured tables \usepackage{setspace} % For line height \usepackage{lastpage} % Needed for total page number \usepackage{seqsplit} % Splits long words. %\usepackage{opensans} % Can't make this work so far. Shame. Would be lovely. \usepackage[normalem]{ulem} % For underlining links % Most of the following are not required for the majority % of cheat sheets but are needed for some symbol support. \usepackage{amsmath} % Symbols \usepackage{MnSymbol} % Symbols \usepackage{wasysym} % Symbols %\usepackage[english,german,french,spanish,italian]{babel} % Languages % Document Info \author{milad69\_1} \pdfinfo{ /Title (js.pdf) /Creator (Cheatography) /Author (milad69\_1) /Subject (JS Cheat Sheet) } % Lengths and widths \addtolength{\textwidth}{6cm} \addtolength{\textheight}{-1cm} \addtolength{\hoffset}{-3cm} \addtolength{\voffset}{-2cm} \setlength{\tabcolsep}{0.2cm} % Space between columns \setlength{\headsep}{-12pt} % Reduce space between header and content \setlength{\headheight}{85pt} % If less, LaTeX automatically increases it \renewcommand{\footrulewidth}{0pt} % Remove footer line \renewcommand{\headrulewidth}{0pt} % Remove header line \renewcommand{\seqinsert}{\ifmmode\allowbreak\else\-\fi} % Hyphens in seqsplit % This two commands together give roughly % the right line height in the tables \renewcommand{\arraystretch}{1.3} \onehalfspacing % Commands \newcommand{\SetRowColor}[1]{\noalign{\gdef\RowColorName{#1}}\rowcolor{\RowColorName}} % Shortcut for row colour \newcommand{\mymulticolumn}[3]{\multicolumn{#1}{>{\columncolor{\RowColorName}}#2}{#3}} % For coloured multi-cols \newcolumntype{x}[1]{>{\raggedright}p{#1}} % New column types for ragged-right paragraph columns \newcommand{\tn}{\tabularnewline} % Required as custom column type in use % Font and Colours \definecolor{HeadBackground}{HTML}{333333} \definecolor{FootBackground}{HTML}{666666} \definecolor{TextColor}{HTML}{333333} \definecolor{DarkBackground}{HTML}{2196A3} \definecolor{LightBackground}{HTML}{F1F8F9} \renewcommand{\familydefault}{\sfdefault} \color{TextColor} % Header and Footer \pagestyle{fancy} \fancyhead{} % Set header to blank \fancyfoot{} % Set footer to blank \fancyhead[L]{ \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{C} \SetRowColor{DarkBackground} \vspace{-7pt} {\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\noindent \hspace*{-6pt}\includegraphics[width=5.8cm]{/web/www.cheatography.com/public/images/cheatography_logo.pdf}} } \end{tabulary} \columnbreak \begin{tabulary}{11cm}{L} \vspace{-2pt}\large{\bf{\textcolor{DarkBackground}{\textrm{JS Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{milad69\_1} via \textcolor{DarkBackground}{\uline{cheatography.com/52248/cs/15235/}}} \end{tabulary} \end{multicols}} \fancyfoot[L]{ \footnotesize \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{LL} \SetRowColor{FootBackground} \mymulticolumn{2}{p{5.377cm}}{\bf\textcolor{white}{Cheatographer}} \\ \vspace{-2pt}milad69\_1 \\ \uline{cheatography.com/milad69-1} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Not Yet Published.\\ Updated 28th March, 2018.\\ Page {\thepage} of \pageref{LastPage}. \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Sponsor}} \\ \SetRowColor{white} \vspace{-5pt} %\includegraphics[width=48px,height=48px]{dave.jpeg} Measure your website readability!\\ www.readability-score.com \end{tabulary} \end{multicols}} \begin{document} \raggedright \raggedcolumns % Set font size to small. Switch to any value % from this page to resize cheat sheet text: % www.emerson.emory.edu/services/latex/latex_169.html \footnotesize % Small font. \begin{multicols*}{2} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Basics}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{{\bf{On page script:}} \newline \textless{}script type="text/javascript"\textgreater{} ... \textless{}/script\textgreater{} \newline \newline {\bf{Include External script:}} \newline \textless{}script src="filename.js"\textgreater{}\textless{}/script\textgreater{} \newline \newline {\bf{Deter}} \newline Use deter so that the JavaScript doesn't execute until after the DOM is loaded \newline \textless{}script src="script.js" defer\textgreater{}\textless{}/script\textgreater{} \newline \newline {\bf{Comments:}} \newline /{\emph{ Multi line \newline comment }}/ \newline // One line \newline {\bf{ Outputs:}} \newline console.log(a); // write to the browser console \newline document.write(a); // write to the HTML \newline alert(a); // output in an alert box \newline confirm("Really?"); // yes/no dialog, returns true/false depending on user click \newline prompt("Your age?","0"); // input dialog. Second argument is the initial value} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Data Types}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{var age = 18; // number \newline var name = "Jane"; // string \newline var name = \{first:"Jane", last:"Doe"\}; // object \newline var truth = false; // boolean \newline var sheets = {[}"HTML","CSS","JS"{]}; // array \newline var a; typeof a; // undefined \newline var a = null; // value null \newline Symbol type??? \newline \newline {\bf{ Objects:}} \newline var student = \{ // object name \newline firstName:"Jane", // list of properties and values \newline lastName:"Doe", \newline age:18, \newline height:170, \newline fullName : function() \{ // object function \newline return this.firstName + " " + this.lastName; \newline \} \newline \}; \newline \newline student.age = 19; // setting value (add a property) \newline student{[}age{]}++; // incrementing \newline delete student.age; // delete a property \newline name = student.fullName(); // call object function \newline iterating: \newline for (key in object)\{ \newline object{[}key{]}; \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Data Types evaluation}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{'' == '0' // false \newline '' == 0 // true \newline 0 == '0' // true \newline NaN == NaN // false \newline {[}''{]} == '' // true \newline false == undefined // false \newline false == null // false \newline null == undefined // true \newline \newline '' === '0' // false \newline '' === 0 // false \newline 0 === '0' // false \newline NaN == NaN // still weirdly false \newline {[}''{]} === '' // false \newline false === undefined // false \newline false === null // false \newline null === undefined // false} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Dom Elements}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{{\bf{Access an HTML element}} \newline document.querySelector('css selector'); \newline document.querySelectorAll('css selector'); \newline document.getElementById("elementID").innerHTML = "Hello World!"; \newline example: \newline let element = \seqsplit{document.querySelector('\#button');} \newline let allElements = \seqsplit{document.querySelectorAll('css} selector'); \newline let elems = \seqsplit{document.querySelectorAll('.quote}, .comment'); // that have a \newline "quote" class AND all elements that have a "comment" class. \newline \newline element.style.top = '20px'; \newline element.style. \newline \newline {\bf{Adding event listeners}} \newline Use dom function: \newline addEventListener(event name, function name); \newline \newline {\bf{Access attributes}} \newline you can't access the class attribute via object.class \newline const image = \seqsplit{document.querySelector('img');} \newline image.src ='somthing.jpg'; \newline but you can't access the class attribute via object.class \newline \newline {\bf{Access class attribute}} \newline classList.add and classList.remove: \newline const image = \seqsplit{document.querySelector('img');} \newline image.classList.add('active'); \newline image.classList.remove('hidden'); \newline \newline innerHTML: The raw HTML between the starting and ending tags of an element, as a string \newline textContent: The text content of a node and its descendants. (This property is inherited from Node) \newline \newline {\bf{ Create and remove elements }} \newline element = \seqsplit{document.createElement(tag} string) \newline element = \seqsplit{document.createElement('h1')} \newline containerElement.appendChild(element); \newline element.remove(); \newline \newline {\bf{Style}} \newline Every element has a style attribute which has higher precedence than any css file. \newline element.style.font = 'something' \newline To undo a style set via the style attribute, you can set it to the empty string, the element will be styled according to any rules in the CSS file \newline element.style.font = ''} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Conditionals}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{{\bf{if else}} \newline if ((age \textgreater{}= 14) \&\& (age \textless{} 19)) \{ // logical condition \newline status = "Eligible."; // executed if condition is true \newline \} else \{ // else block is optional \newline status = "Not eligible."; // executed if condition is false \newline \} \newline {\bf{Switch statement:}} \newline switch (new Date().getDay()) \{ // input is current day \newline case 6: // if (day == 6) \newline text = "Saturday"; \newline break; \newline case 0: // if (day == 0) \newline case 1: // if (day == 1) \newline text = "Sunday"; \newline break; \newline default: // else... \newline text = "Whatever"; \newline \} \newline \newline {\bf{? statements:}} \newline a = (condition) ? (cond\_true\_result) : (cond\_false\_result);} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Numbers and Math}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{var pi = 3.141; \newline pi.toFixed(0); // returns 3 \newline pi.toFixed(2); // returns 3.14 - for working with money \newline pi.toPrecision(2) // returns 3.1 \newline pi.valueOf(); // returns number \newline Number(true); // converts to number \newline Number(new Date()) // number of milliseconds since 1970 \newline parseInt("3 months"); // returns the first number: 3 \newline parseFloat("3.5 days"); // returns 3.5 \newline Number.MAX\_VALUE // largest possible JS number \newline Number.MIN\_VALUE // smallest possible JS number \newline Number.NEGATIVE\_INFINITY// -Infinity \newline Number.POSITIVE\_INFINITY// Infinity \newline \newline {\bf{Math}} \newline var pi = Math.PI; // 3.141592653589793 \newline Math.round(4.4); // = 4 - rounded \newline Math.round(4.5); // = 5 \newline Math.pow(2,8); // = 256 - 2 to the power of 8 \newline Math.sqrt(49); // = 7 - square root \newline Math.abs(-3.14); // = 3.14 - absolute, positive value \newline Math.ceil(3.14); // = 4 - rounded up \newline Math.floor(3.99); // = 3 - rounded down \newline Math.sin(0); // = 0 - sine \newline Math.cos(Math.PI); // OTHERS: tan,atan,asin,acos, \newline Math.min(0, 3, -2, 2); // = -2 - the lowest value \newline Math.max(0, 3, -2, 2); // = 3 - the highest value \newline Math.log(1); // = 0 natural logarithm \newline Math.exp(1); // = 2.7182pow(E,x) \newline Math.random(); // random number between 0 and 1 \newline Math.floor(Math.random() * 5) + 1; // random integer, from 1 to 5 \newline \newline {\bf{Constants:}} \newline E, PI, SQRT2, SQRT1\_2, LN2, LN10, LOG2E, Log10E} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{JSON}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{var str = '\{"names":{[}' + // crate JSON object \newline '\{"first":"Hakuna","lastN":"Matata" \},' + \newline '\{"first":"Jane","lastN":"Doe" \},' + \newline '\{"first":"Air","last":"Jordan" \}{]}\}'; \newline obj = JSON.parse(str); // parse \newline document.write(obj.names{[}1{]}.first); // access \newline \newline {\bf{Send:}} \newline var myObj = \{ "name":"Jane", "age":18, "city":"Chicago" \}; // create object \newline var myJSON = JSON.stringify(myObj); // stringify \newline window.location = "demo.php?x=" + myJSON; // send to php \newline \newline {\bf{Store:}} \newline myObj = \{ "name":"Jane", "age":18, "city":"Chicago" \}; \newline myJSON = JSON.stringify(myObj); // storing data \newline localStorage.setItem("testJSON", myJSON); \newline //// \newline text = \seqsplit{localStorage.getItem("testJSON");} // retrieving data \newline obj = JSON.parse(text); \newline document.write(obj.name);} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Errors}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{try \{ // block of code to try \newline undefinedFunction(); \newline \} \newline catch(err) \{ // block to handle errors \newline \seqsplit{console.log(err.message);} \newline \} \newline \newline {\bf{Throw Error}} \newline throw "My error message"; // throw a text \newline \newline {\bf{Input Validation}} \newline var x = \seqsplit{document.getElementById("mynum").value;} // get input value \newline try \{ \newline if(x == "") throw "empty"; // error cases \newline if(isNaN(x)) throw "not a number"; \newline x = Number(x); \newline if(x \textgreater{} 10) throw "too high"; \newline \} \newline catch(err) \{ // if there's an error \newline document.write("Input is " + err); // output error \newline console.error(err); // write the error in console \newline \} \newline finally \{ \newline document.write("\textless{}/br /\textgreater{}Done"); // executed regardless of the try / catch result \newline \} \newline \newline {\bf{Error name values}} \newline \newline RangeError A number is "out of range" \newline ReferenceError An illegal reference has occurred \newline SyntaxError A syntax error has occurred \newline TypeError A type error has occurred \newline URIError An encodeURI() error has occurred} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Cite}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Got from \seqsplit{http://htmlcheatsheet.com/js/} with customizations} \tn % Row Count 2 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Event types}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{{\bf{Mouse}} \newline onclick, oncontextmenu, ondblclick, onmousedown, onmouseenter, onmouseleave, onmousemove(only desktop), onmouseover, onmouseout, onmouseup \newline mouseEvent.clientX, mouseEvent.clientY: X|Y axis position relative to the left edge of the browser viewpoint \newline \newline {\bf{Touch}} \newline ontouchcancel, ontouchend, ontouchmove(only mobile), ontouchstart \newline \newline {\bf{PointerEvent}} \newline (not for all browser can be used with \{\{link="https://github.com/jquery/PEP"\}\} polyfill\{\{/link\}\}) available with the following script: \newline \textless{}script \seqsplit{src="https://code.jquery.com/pep/0.4.1/pep}.js"\textgreater{}\textless{}/script\textgreater{} \newline And we'll add need to add touch-action="none" to the area where we want PointerEvents to be recognized (telling the browser that we do not want the default touch behavior for children of this element). \newline \newline Works the same both on mobile and desktop \newline pointerdown, pointerup, pointermove(works both on mobile and desktop), pointercancel \newline \newline To listen to pointer events that occur when the pointer goes offscreen, call setPointerCapture on the target you want to keep tracking: \newline event.target.setPointerCapture(event.pointerId); \newline \newline {\bf{Keyword}} \newline onkeydown, onkeypress, onkeyup \newline keywordEvent.key: which key was pressed: \newline Escape, ArrowRight, ArrowLeft, ... \newline \newline \newline \newline {\bf{Frame}} \newline onabort, onbeforeunload, onerror, onhashchange, onload, onpageshow, onpagehide, onresize, onscroll, onunload \newline \newline {\bf{Form}} \newline onblur, onchange, onfocus, onfocusin, onfocusout, oninput, oninvalid, onreset, onsearch, onselect, onsubmit \newline \newline {\bf{Drag}} \newline ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop \newline \newline {\bf{Clipboard}} \newline oncopy, oncut, onpaste \newline \newline {\bf{Media}} \newline onabort, oncanplay, oncanplaythrough, ondurationchange, onended, onerror, onloadeddata, onloadedmetadata, onloadstart, onpause, onplay, onplaying, onprogress, onratechange, onseeked, onseeking, onstalled, onsuspend, ontimeupdate, onvolumechange, onwaiting \newline \newline {\bf{Animation}} \newline animationend, animationiteration, animationstart \newline \newline {\bf{Miscellaneous}} \newline transitionend, onmessage, onmousewheel, ononline, onoffline, onpopstate, onshow, onstorage, ontoggle, onwheel} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Working with Events}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{{\bf{Adding event listeners}} \newline Use dom function: \newline addEventListener(event name, function name); \newline \newline {\bf{ Access caller element inside callback}} \newline event.target; //the element that was clicked / \newline "dispatched the event" (might be a child of the target) \newline event.currentTarget; // the element that the original event handler was attached to) \newline \newline also 'this' refer to event in callback \newline \newline {\bf{Event propagation}} \newline If a child and a parent element exist that have different callbacks to events, and inner element is clicked, both events are called. This is called event bubbling. \newline \newline \textless{}div id="outer"\textgreater{} \newline Click me! \newline \textless{}div id="inner"\textgreater{} \newline No, Click me! \newline \textless{}/div\textgreater{} \newline \textless{}/div\textgreater{} \newline innerElem.addEventListener('click', innerCallback); \newline outerElem.addEventListener('click', oute/rCallback); \newline \newline if inner element is called, outer and inner callbacks will be fired. \newline \newline event.stopPropagation() method inside callback can prevent further propagation of event to outer callbacks. \newline \newline the propagation can go in opposite direction (called event capturing) by setting additional parameter for addEventListener. \newline event.addEventListener('click', onClick, \{ capture: true\} ); \newline \newline {\bf{prevent default}} \newline There's a default behavior for some events that can be prevented using preventDefault method. \newline function onCallback(event)\{ \newline event.preventDefault(); \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Random number}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Use Math.random: returns a random floating point number between {[}0, 1) \newline To get a random number in {[}0, maxNumber): \newline Math.floor(Math.random() * Max)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Data attributes}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{You can assign special data-* attributes to HTML elements to give associate additional data with the element \newline \textless{}tag data-your-name='your value"\textgreater{} \textless{}/tag\textgreater{} \newline to access in javascript: \newline tagElement.dataset.YourName \newline Dash-separated words turn to camel case and are returned as string} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Global functions}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{eval(); // executes a string as if it was script code \newline String(23); // return string from number \newline (23).toString(); // return string from number \newline Number("23"); // return number from string \newline decodeURI(enc); // decode URI. Result: "my page.asp" \newline encodeURI(uri); // encode URI. Result: "my\%page.asp" \newline decodeURIComponent(enc); // decode a URI component \newline encodeURIComponent(uri); // encode a URI component \newline isFinite(); // is variable a finite, legal number \newline isNaN(); // is variable an illegal number \newline parseFloat(); // returns floating point number of string \newline parseInt(); // parses a string and returns an integer} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Dates}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Thu Mar 22 2018 11:40:54 GMT+0430 (+0430) \newline \newline var d = new Date(); \newline \newline 1521702654616 miliseconds passed since 1970 \newline \newline Number(d) \newline \newline Date("2017-06-23"); // date declaration \newline Date("2017"); // is set to Jan 01 \newline Date("2017-06-23T12:00:00-09:45"); // date - time YYYY-MM-DDTHH:MM:SSZ \newline Date("June 23 2017"); // long date format \newline Date("Jun 23 2017 07:45:00 GMT+0100 (Tokyo Time)"); // time zone \newline \newline {\bf{Get Dates:}} \newline Thu Mar 22 2018 11:40:54 GMT+0430 (+0430) \newline \newline var d = new Date(); \newline \newline 1521702654616 miliseconds passed since 1970 \newline \newline Number(d) \newline \newline Date("2017-06-23"); // date declaration \newline Date("2017"); // is set to Jan 01 \newline Date("2017-06-23T12:00:00-09:45"); // date - time YYYY-MM-DDTHH:MM:SSZ \newline Date("June 23 2017"); // long date format \newline Date("Jun 23 2017 07:45:00 GMT+0100 (Tokyo Time)"); // time zone \newline \newline \newline {\bf{Setting part of a date:}} \newline var d = new Date(); \newline d.setDate(d.getDate() + 7); // adds a week to a date \newline \newline setDate(); // day as a number (1-31) \newline setFullYear(); // year (optionally month and day) \newline setHours(); // hour (0-23) \newline setMilliseconds(); // milliseconds (0-999) \newline setMinutes(); // minutes (0-59) \newline setMonth(); // month (0-11) \newline setSeconds(); // seconds (0-59) \newline setTime(); // milliseconds since 1970)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Regular Expressions}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Promises}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{An object used to manage asynchronous results. \newline has a then() method that lets you attach functions to execute onSuccess and onError callbacks. \newline Allows you to build chains of asynchronous results.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Local Storage}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Variables}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{var a; // Function scope variable \newline let al; // block scope variable \newline const ca; // block scope constant, cannot be changed. However, it doesn't provide true const correctness, so you can still modify the underlying object so: \newline const list = {[}1, 2, 3{]}; \newline list.push(4); // OK \newline \newline var b = "init"; // string \newline var c = "Hi" + " " + "Joe"; // = "Hi Joe" \newline var d = 1 + 2 + "3"; // = "33" \newline var e = {[}2,3,5,8{]}; // array \newline var f = false; // boolean \newline var g = /()/; // RegEx \newline var h = function()\{\}; // function object \newline const PI = 3.14; // constant \newline var a = 1, b = 2, c = a + b; // one line \newline let z = 'zzz'; // block scope local variable \newline \newline {\bf{Strict mode}} \newline "use strict"; // Use strict mode to write secure code \newline x = 1; // Throws an error because variable is not declared} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Operators}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{{\bf{Values}} \newline false, true // boolean \newline 18, 3.14, 0b10011, 0xF6, NaN // number \newline "flower", 'John' // string \newline undefined, null , Infinity // special \newline \newline {\bf{Operators}} \newline a = b + c - d; // addition, substraction \newline a = b {\emph{ (c / d); // multiplication, division \newline x = 100 \% 48; // modulo. 100 / 48 remainder = 4 \newline a++; b-{}-; // postfix increment and decrement \newline \newline {\bf{Bitwise operators}} \newline \& AND 5 \& 1 (0101 \& 0001) 1 (1) \newline | OR 5 | 1 (0101 | 0001) 5 (101) \newline \textasciitilde{} NOT \textasciitilde{} 5 (\textasciitilde{}0101) 10 (1010) \newline \textasciicircum{} XOR 5 \textasciicircum{} 1 (0101 \textasciicircum{} 0001) 4 (100) \newline \textless{}\textless{} left shift 5 \textless{}\textless{} 1 (0101 \textless{}\textless{} 1) 10 (1010) \newline \textgreater{}\textgreater{} right shift 5 \textgreater{}\textgreater{} 1 (0101 \textgreater{}\textgreater{} 1) 2 (10) \newline \textgreater{}\textgreater{}\textgreater{} zero fill right shift 5 \textgreater{}\textgreater{}\textgreater{} 1 (0101 \textgreater{}\textgreater{}\textgreater{} 1) 2 (10) \newline \newline {\bf{Asthmatics:}} \newline a }} (b + c) // grouping \newline person.age // member \newline person{[}age{]} // member \newline !(a == b) // logical not \newline a != b // not equal \newline typeof a // type (number, object, function...) \newline x \textless{}\textless{} 2 x \textgreater{}\textgreater{} 3 // minary shifting \newline a = b // assignment \newline a == b // equals \newline a != b // unequal \newline a === b // strict equal \newline a !== b // strict unequal \newline a \textless{} b a \textgreater{} b // less and greater than \newline a \textless{}= b a \textgreater{}= b // less or equal, greater or eq \newline a += b // a = a + b (works with - * \%...) \newline a \&\& b // logical and \newline a || b // logical or} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Strings}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{var abc = \seqsplit{"abcdefghijklmnopqrstuvwxyz";} \newline var esc = 'I don\textbackslash{}'t \textbackslash{}n know'; // \textbackslash{}n new line \newline var len = abc.length; // string length \newline abc.indexOf("lmno"); // find substring, -1 if doesn't contain \newline abc.lastIndexOf("lmno"); // last occurance \newline abc.slice(3, 6); // cuts out "def", negative values count from behind \newline abc.replace("abc","123"); // find and replace, takes regular expressions \newline abc.toUpperCase(); // convert to upper case \newline abc.toLowerCase(); // convert to lower case \newline abc.concat(" ", str2); // abc + " " + str2 \newline abc.charAt(2); // character at index: "c" \newline abc{[}2{]}; // unsafe, abc{[}2{]} = "C" doesn't work \newline abc.charCodeAt(2); // character code at index: "c" -\textgreater{} 99 \newline abc.split(","); // splitting a string on commas gives an array \newline abc.split(""); // splitting on characters \newline 128.toString(16); // number to hex(16), octal (8) or binary (2)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Functions}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{{\bf{Declaration}} \newline functions in JavaScript are "first-class" because they are treated like any other variable/object. \newline \newline function hello(input) \{ \newline // body \newline \} \newline \newline hello = (input) =\textgreater{} \{ \newline // body \newline \} \newline // you can omit \{\} if there is only one statement: \newline // you can omit () if there is only one argument \newline hello = input =\textgreater{} input + 1; \newline var hello = function hello(input) \{ // body \} \newline \newline {\bf{this scope inside functions}} \newline \newline \newline functions: \newline this is will be dynamically assigned to a different value depending on how the function is called (unless explicitly bound with bind) \newline - this in a constructor: refers to the new object being \newline created \newline - this outside a constructor: refers to a different value \newline depending on how the function is called \newline - In response to a DOM event, this is the element \newline that the event handler was tied to \newline - When called in a method, this is the object that \newline the method is called from \newline - bind: sets the value of this for a function so it does \newline not change depending on the context \newline \newline \newline \newline Arrow functions \{\{link="https://derickbailey.com/2015/09/28/do-es6-arrow-functions-really-solve-this-in-javascript/"\}\}link\{\{/link\}\}: \newline Arrow functions capture the this value of the enclosing context. \newline Arrow function syntax uses "lexical scoping". Lexical scoping is fancy way of saying it uses "this" from the surrounding codeā€¦ the code that contains the code in question. \newline Arrow functions do not have their own this. \newline arrow functions cannot be used as generators (yeild does not work unless for further nested function) \newline this.test = "attached to the module"; \newline \newline var foo = \{ \newline test: "attached to an object" \newline \}; \newline \newline foo.method = function(name, cb)\{ \newline this{[}name{]} = cb; \newline \}; \newline \newline foo.method("bar", () =\textgreater{} \{ \newline // not what you expected, maybe? \newline console.log(this.test); \newline \}); \newline \newline foo.bar(); // =\textgreater{} "attached to an object" but it was expected to be madule! \newline \newline As another example: \newline \newline var obj = \{ \newline i: 10, \newline b: () =\textgreater{} console.log(this.i, this), \newline c: function() \{ \newline console.log(this.i, this); \newline \} \newline \} \newline \newline obj.b(); // prints undefined, Window \{...\} (or the global object) \newline obj.c(); // prints 10, Object \{...\} \newline \newline \newline this inside object as function: \newline obj = \{ 'a': 12, f: function()\{ console.log(this.a)\}\}; obj.f() // =\textgreater{} 12 \newline this inside object as arrow function: \newline obj = \{ 'a': 12, f: () =\textgreater{} \{ console.log(this.a)\}\}; obj.f(); // =\textgreater{} undefined. \newline or: \newline a = 1; obj = \{ 'a': 12, f: () =\textgreater{} \{ console.log(this.a)\}\}; obj.f(); // =\textgreater{} 1 \newline \newline {\bf{ functional programming:}} \newline - First-class functions (functions as objects) \newline - Closures \newline - Anonymous functions / lambdas / function literals \newline - Currying \newline \newline {\bf{Hoisted declaration}} \newline Some function declaration are hoisted. definition gets moved to the top of the scope in which it's defined. So this works: \newline hello() \newline function hello() \{ // ,,, \} \newline \newline These kind of declaration are not hoisted: \newline \newline {\bf{closures}} \newline A function declared within a function is also known as a closure. Inner functions are called closures \newline \newline function outerFunc() \{ \newline function innerFunc() \{ \newline // closures \newline \} \newline \} \newline \newline Scope: \newline Functions declared with function (or var) have function scope \newline Functions declared with const or let have block scope \newline \newline {\bf{Access to outer function variables}} \newline closures have access to variables declared in outer function and those variables does not go away! (remains and can be even changed!!). It's like a function pointer but local variables of outer function remained and are not destroyed. \newline f = function outerFunction()\{ \newline let x = 1; \newline return function()\{ \newline x = x + 1; \newline console.log(x); \newline \} \newline \} \newline run = f(); \newline run(); // 2 \newline run(); // 3 \newline run(); // 4 \newline \newline {\bf{curryng}} \newline The idea of constructing a new function that is "partially instantiated" with arguments is called currying. \newline Constructing a new function that references part of the outer function's parameters is called currying. \newline for example when one function needs additional argument and we can't add another argument to it (it's not expected to have another one!), we can use currying. we can have a function that accepts that additional argument and have another function (a closure) which has expected arguments: \newline \newline we want a function with 2 arguments to have another argument: \newline somthing.add(twoArgumentFunc) \newline function makeTwoArgument(anotherArg)\{ \newline return function()\{ \newline // use anotherArg in here \newline // It's like having 3 arguments! \newline \} \newline \} \newline =\textgreater{} \seqsplit{somthing.add(makeTwoARgument(anotherArg));} \newline \newline {\bf{ Anonymous function }} \newline When we define a function without an identifier, we call it an anonymous function \newline \newline return function() \{ \newline //this is anonymous function \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Arrays}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{var dogs = {[}"Bulldog", "Beagle", "Labrador"{]}; \newline var dogs = new Array("Bulldog", "Beagle", "Labrador"); // declaration \newline \newline alert(dogs{[}1{]}); // access value at index, first item being {[}0{]} \newline dogs{[}0{]} = "Bull Terier"; // change the first item \newline \newline for (var i = 0; i \textless{} dogs.length; i++) \{ // parsing with array.length \newline console.log(dogs{[}i{]}); \newline \} \newline \newline {\bf{Methods:}} \newline dogs.toString(); // convert to string: results "Bulldog,Beagle,Labrador" \newline dogs.join(" {\emph{ "); // join: "Bulldog }} Beagle * Labrador" \newline dogs.pop(); // remove last element \newline dogs.push("Chihuahua"); // add new element to the end \newline dogs{[}dogs.length{]} = "Chihuahua"; // the same as push \newline dogs.shift(); // remove first element \newline dogs.unshift("Chihuahua"); // add new element to the beginning \newline delete dogs{[}0{]}; // change element to undefined (not recommended) \newline dogs.splice(2, 0, "Pug", "Boxer"); // add elements (where, how many to remove, element list) \newline var animals = dogs.concat(cats,birds); // join two arrays (dogs followed by cats and birds) \newline dogs.slice(1,4); // elements from {[}1{]} to {[}4-1{]} \newline dogs.sort(); // sort string alphabetically \newline dogs.reverse(); // sort string in descending order \newline x.sort(function(a, b)\{return a - b\}); // numeric sort \newline x.sort(function(a, b)\{return b - a\}); // numeric descending sort \newline highest = x{[}0{]}; // first item in sorted array is the lowest (or highest) value \newline x.sort(function(a, b)\{return 0.5 - Math.random()\}); // random order sort \newline splice // Add/remove element at index \newline list.splice(startIndex, deleteCount, item1, item2, ...) \newline list.splice(3, 1) //Remove one element at index 3: \newline list.splice(2, 0, element); //Add element at index 2: \newline \newline list.forEach(function): Executes the provided function once for each array element. \newline list.filter(function): Creates a new array with all elements that pass the test implemented by the provided function. \newline list.every(function) : Tests whether all elements in the array pass the test implemented by the provided function \newline \newline others: \newline concat, copyWithin, every, fill, filter, find, findIndex, forEach, indexOf, isArray, join, lastIndexOf, map, pop, push, reduce, reduceRight, reverse, shift, slice, some, sort, splice, toString, unshift, valueOf} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Loops}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{{\bf{ For Loops:}} \newline for (var i = 0; i \textless{} 10; i++) \{ \newline document.write(i + ": " + i{\emph{3 + "\textless{}br /\textgreater{}"); \newline \} \newline var sum = 0; \newline for (var i = 0; i \textless{} a.length; i++) \{ \newline sum + = a{[}i{]}; \newline \} // parsing an array \newline \newline {\bf{ For each}} \newline for ( var i in something)\{ \newline console.log(something{[}i{]}); \newline \} \newline \newline {\bf{ While Loops:}} \newline var i = 1; // initialize \newline while (i \textless{} 100) \{ // enters the cycle if statement is true \newline i }}= 2; // increment to avoid infinite loop \newline document.write(i + ", "); // output \newline \} \newline \newline \newline {\bf{ Do While Loops:}} \newline var i = 1; // initialize \newline do \{ // enters cycle at least once \newline i *= 2; // increment to avoid infinite loop \newline document.write(i + ", "); // output \newline \} while (i \textless{} 100) // repeats cycle if statement is true at the end \newline \newline \newline {\bf{ Break:}} \newline for (var i = 0; i \textless{} 10; i++) \{ \newline if (i == 5) \{ break; \} // stops and exits the cycle \newline document.write(i + ", "); // last output number is 4 \newline \} \newline \newline \newline {\bf{ Continue:}} \newline for (var i = 0; i \textless{} 10; i++) \{ \newline if (i == 5) \{ continue; \} // skips the rest of the cycle \newline document.write(i + ", "); // skips 5 \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Classes}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{{\bf{Definition}} \newline class ClassName\{ \newline constructor()\{ //it's optional \newline // define public fields by setting this.fieldName \newline // in constructor or any method \newline this.fieldName = value; \newline \newline \} \newline \newline methodName()\{ //don't need to use function keyword \newline //all methods are public - no private method yet \newline // convention: \_ before the name means private \newline \} \newline \newline methodTwo()\{ \newline //always refer to other methods or fields in class with this \newline this.methodName(); \newline \newline \} \newline \} \newline \newline \newline {\bf{Element as a class}} \newline Use class that gets Container element as input for constructor \newline {\bf{Definition}} \newline class ClassName\{ \newline constructor(containerElement)\{ \newline this.containerElem = containerElement; \newline \newline //Create element: \newline this.image = \seqsplit{document.createElement('img');} \newline this.image.src = 'image.jpg'; \newline \seqsplit{this.image.addEventListener('click'}, this.\_clickElement) \newline \newline \} \newline \newline \_clickElement(event)\{ \newline // do some thing \newline \} \newline \} \newline \newline {\bf{Binding this }} \newline This in here refers to the element that the event handler was attached to! \newline to make this always refer to the instance object for a method in the class we use bind \newline for above example: \newline \newline first bind this in the constructor: \newline constructor(containerElement)\{ \newline // always bind event listeners in the constructor \newline this.\_clickElement = \seqsplit{this.\_clickElement.bind(this);} \newline \} \newline then use this as expected: \newline clickElement(event)\{ \newline // now this refer to the class object not event element! \newline this.image.src = 'image2.jpg'; \newline \} \newline \newline another solution was to access the element with event.currentTarget \newline {\bf{Instantiation}} \newline const x = new SomeClass(); \newline const y = new SomeClass(); \newline y.someMethod();} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Custom events}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{You can listen to and dispatch (fire) Custom Events. \newline const event = new \seqsplit{CustomEvent(eventNameString}, \seqsplit{optionalParameterObject);} \newline element.addEventListener(eventNameString); \newline element.dispatchEvent(eventNameString); \newline CustomEvent can only be listened to /dispatched on HTML elements, and not to arbitrary class instances. \newline \newline {\bf{Communicating between element}} \newline You can add custom event on the document and dispatch that event inside different element. \newline document.addEventListerner( ... \newline document.dispatchEvent(... \newline \newline to add additional information about the event you can pass parameter to the custom event: \newline onClick(event) \{ \newline const eventInfo = \{ \newline buttonName = this.text; \newline \} \newline document.dispatchEvent( new CustomEvent('bclicked', \{ detail: eventinfo\}); \newline \newline \} \newline \newline onCustomEven(event) \{ \newline event.detail.buttonName; // can access info \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Template literals}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{Template literals allow you to embed expressions in \newline JavaScript strings \newline const port = 80; \newline console.log(`Server is listening on port: \$\{port\}`);} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{async/await}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{8.4cm}}{\bf\textcolor{white}{Fetch}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{8.4cm}}{The API to use to load external resources (text, JSON, etc) in the browser (like XHR but easier to use) \newline - It has only one function: fetch \newline - takes string path to the resource as argument \newline - return a promise \newline Fetch api: \newline \newline function onSuccess(response) \{ \newline ... \newline \} \newline function onFail(response) \{ \newline ... \newline \} \newline fetch('images.txt').then(onSuccess, onFail); \newline or \newline const promise = fetch('images.txt'); \newline promise.then(onSuccess, onFail);} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} % That's all folks \end{multicols*} \end{document}