Javascript Cheat Sheet
Comments: /*Multiline *. //One Line
Functions:
function sum(a,b){
return a+b;
}
Edit DOM:
document.getElementID("elementID").innerHTML = "HELLO HELLO " ;
For Loop:
for(let i=0; i< thing.length; i++){}
While Loop:
while (i< thing.length){}
Do-While Loop:
do{
} while(condition) * performs action then checkes conditional *
Switch Statements:
switch(condition) {
case 1:
text = "First Option";
break;
case 2:
text = "Second Option";
break;
default:
text = "Default value if none of cases are hit";
Objects:
let student = {
f_name: "Tej"
l_name: "Charfi"
age: 22
height: 387
fullName : function() {
return this.firstName + " " + this.lastName;
}
};name = student.fullName();
String Manipulation:
\n = new Line .length //string length .indexOf("") //finds substring, set to -1 if not found .lastIndexOf("") //finds last substring occurance of .slice(num, num) // takes range .replace("arg 1", "arg 2") //replaces arg 1 with arg 2 .charAt(x) //characters at index x
Events
<button onclick="function();">
Click here
</button>
Mouse:
onclick, oncontextmenu, ondblclick, onmousedown, onmouseenter, onmouseleave, onmousemove, onmouseover, onmouseout, onmouseup
Keyboard:
onkeydown, onkeypress, onkeyup
Frame:
onabort, onbeforeunload, onerror, onhashchange, onload, onpageshow, onpagehide, onresize, onscroll, onunload
Form:
onblur, onchange, onfocus, onfocusin, onfocusout, oninput, oninvalid, onreset, onsearch, onselect, onsubmit
Drag:
ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop
Clipboard:
oncopy, oncut, onpaste
Media:
onabort, oncanplay, oncanplaythrough, ondurationchange, onended, onerror, onloadeddata, onloadedmetadata, onloadstart, onpause, onplay, onplaying, onprogress, onratechange, onseeked, onseeking, onstalled, onsuspend, ontimeupdate, onvolumechange, onwaiting
Animation:
animationend, animationiteration, animationstart
Misc:
transitionend, onmessage, onmousewheel, ononline, onoffline, onpopstate, onshow, onstorage, ontoggle, onwheel, ontouchcancel, ontouchend, ontouchmove, ontouchstart
Math
- .MAX_VALUE //largest possible number in JS
- /MIN_VALUE // smalles possible number in JS
- .NEGATIVE_INFINITY / .POSITIVE_INFINITY // -Infiniti and +Infinity
- .pow(x,2) //x²
- .sqrt(num)
- .abs(x) //absolute value
- .ceil // round up
- .floor //round down
- .sin / .cos / .log
Dates
var d = new Date();
a = d.getDay(); // getting the weekday
getDate(); // day as a number (1-31)
getDay(); // weekday as a number (0-6)
getFullYear(); // four digit year (yyyy)
getHours(); // hour (0-23)
getMilliseconds(); // milliseconds (0-999)
getMinutes(); // minutes (0-59)
getMonth(); // month (0-11)
getSeconds(); // seconds (0-59)
getTime(); // milliseconds since 1970
Global Functions
eval(); // executes a string as if it was script code
String(23); // return string from number
(23).toString(); // return string from number
Number("23"); // return number from string
decodeURI(enc); // decode URI. Result: "my page.asp"
encodeURI(uri); // encode URI. Result: "my%page.asp"
decodeURIComponent(enc); // decode a URI component
encodeURIComponent(uri); // encode a URI component
isFinite(); // is variable a finite, legal number
isNaN(); // is variable an illegal number
parseFloat(); // returns floating point number of string
parseInt(); // parses a string and returns an integer
Error Handling
try { // block of code to try
undefinedFunction();
}
catch(err) { // handle error
console.log(err.message);
}
Input Validation
var x = document.getElementById("mynum").value; // get input value
try {
if(x == "") throw "empty"; // error cases
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x > 10) throw "too high";
}
catch(err) { // if there's an error
document.write("Input is " + err); // output error
console.error(err); // write the error in console
}
finally {
document.write("</br />Done"); // executed regardless of the try / catch result
}
Error Name Reference:
RangeError: A number is “out of range”
ReferenceError: An illegal reference has occurred
SyntaxError: A syntax error has occurred
TypeError: A type error has occurred
URIError: An encodeURI() error has occurred