0% found this document useful (0 votes)
9 views7 pages

JavaScript Cheat Sheet Basics and Functions

The document is a comprehensive JavaScript cheat sheet covering various topics including loops, functions, data types, operators, events, arrays, and error handling. It provides syntax examples and explanations for each concept, making it a useful reference for both beginners and experienced developers. Additionally, it includes sections on JSON, promises, and regular expressions.

Uploaded by

hongngocbao123
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views7 pages

JavaScript Cheat Sheet Basics and Functions

The document is a comprehensive JavaScript cheat sheet covering various topics including loops, functions, data types, operators, events, arrays, and error handling. It provides syntax examples and explanations for each concept, making it a useful reference for both beginners and experienced developers. Additionally, it includes sections on JSON, promises, and regular expressions.

Uploaded by

hongngocbao123
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JS CheatSheet

Basics ➤

Loops ↶ On page script


<script type="text/javascript"> ...
</script>
For Loop
for (var i = 0; i < 10; i++) { Include external JS file
[Link](i + ": " + i*3 + "<br />"); <script src="[Link]"></script>
}
var sum = 0; Delay - 1 second timeout
for (var i = 0; i < [Link]; i++) {
setTimeout(function () {
sum + = a[i];
} // parsing an array
}, 1000);
html = "";
for (var i of custOrder) { Functions
html += "<li>" + i + "</li>";
function addNumbers(a, b) {
}
return a + b; ;
} While Loop
x = addNumbers(1, 2);
var i = 1; // initialize
while (i < 100) { // enters the
cycle Edit DOM element
i *= 2; // increment to [Link]("elementID").innerHTML
avo =
[Link](i + ", // output
");
} Output
[Link](a); // write to the
Do While Loop brows
var i = 1; // initialize [Link](a); // write to the
do { // enters cycle at HTML
i *= 2; // increment to alert(a); // output in an
avo alert confirm("Really?"); // hộp thoại có/không
[Link](i + ", // output trả về prompt("Your age?","0"); // hộp thoại
"); nhập liệu
} while (i < 100) // repeats cycle
if Comments
Break /* Multi
for (var i = 0; i < 10; i++) line
{ comment
if (i == 5) { break; } // stops and ex */
[Link](i + ", // last output // One line
");
}

Continue

If - Else ⇵
if ((age >= 14) && (age < 19)) { //
logica status = "Eligible."; //
execut
} else { // else b
status = "Not eligible."; // execut
}

Variables x Switch Statement


switch (new Date().getDay()) { // input is c
case 6: // if (day ==
var a; // variable
text = "Saturday";
var b = "init"; // string
break;
var c = "Hi" + " " + "Joe"; // = "Hi
case 0: // if (day ==
Joe" var d = 1 + 2 + "3"; // = "33"
text = "Sunday";
var e = [2,3,5,8]; // array
break;
var f = false; // boolean
default: // else...
var g = /()/; // RegEx
text = "Whatever";
var h = function(){}; // function object
}
const PI = 3.14; //
constant var a = 1, b = 2, c = a + b;
Data Types ℜ
var age = 18; // number
var name = "Jane"; // string
var name = {first:"Jane", last:"Doe"}; // object var truth = false;
Values //
boolea var sheets = ["HTML","CSS","JS"]; // array
false, true // boolean
var a; typeof a; //
18, 3.14, 0b10011, 0xF6, NaN //
undefi
number "flower", 'John' // string
var a = null; // value
undefined, null , Infinity //
special Objects
Operators var student = { // object name
a = b + c - d; // addition, substraction firstName:"Jane", // list of
a = b * (c / d); // multiplication, division proper lastName:"Doe",
x = 100 % 48; // modulo. 100 / 48 age:18,
remainder = a++; b--; // postfix height:170,
increment and decrem fullName : function() { // object functio
Bitwise operators return [Link] + " " +
[Link]
5 & 1 (0101 & }
& AND 0001) 1 (1)
};
| OR 5 | 1 (0101 | 0001) 5 (101)
~ 10 [Link] = 19; // setting value
NOT ~ 5 (~0101) student[age]++; // incrementing
(1010)
name = [Link](); // call object
^ XOR 5 ^ 1 (0101 ^ 0001) 4 functi
(100)
<< 10
left shift 5 << 1 (0101 << 1)
(1010)
>> right shift 5 >> 1 (0101 >> 1) 2 Strings ⊗
(10)
zero fill right 5 >>> 1 (0101 >>> var abc = "abcdefghijklmnopqrstuvwxyz";
>>> shift 1) 2 (10) var esc = 'I don\'t \n know'; // \n new line
Arithmetic var len = [Link]; // độ dài chuỗi
a * (b + c) // grouping [Link]("lmno"); // find chuỗi con
[Link] // member [Link]("lmno"); // lần xuất hiện cuối cùng
person[age] // member [Link](3, 6); // cắt bỏ def
!(a == b) // logical not [Link]("abc","123"); // find and thay thế
a != b // not equal [Link](); // chuyểnsang upp
typeof a // type (number, object, [Link](); // chuyển sang low
functi x << 2 x >> 3 // minary shifting [Link](" ", str2); // abc + " " + st
a = b // assignment [Link](2); // character at i
a == b // equals abc[2]; // unsafe, abc[2]
a != b // unequal [Link](2); // mã ký tự
a === b // strict equal [Link](","); // tách chuỗi
a !== b // strict unequal [Link](""); // tách chuỗi
a < b a > b // less and greater than [Link](16); // chuyển thành chuỗi
a <= b a >= b // less or equal, greater or
eq a += b // a = a + b (works with - *
%.
a a && b
and // logical
Events 🕖
var pi = 3.141; <button
[Link](0); // returns 3 onclick="myFunction();">
[Link](2); // returns 3.14 - for Click here
worki [Link](2) // returns 3.1 </button>
[Link](); // returns number
Number(true); // converts to number Mouse
Number(new Date()) // number of milliseconds onclick, oncontextmenu, ondblclick, onmousedown,
s parseInt("3 months"); // returns the first onmouseenter, onmouseleave, onmousemove,
number parseFloat("3.5 days"); // returns 3.5 onmouseover, onmouseout, onmouseup
Number.MAX_VALUE // largest possible JS numb
Number.MIN_VALUE // smallest possible JS num Keyboard
Number.NEGATIVE_INFINITY// -Infinity onkeydown, onkeypress, onkeyup
Number.POSITIVE_INFINITY// Infinity
Frame
Math.
onabort, onbeforeunload, onerror, onhashchange,
var pi = [Link]; // 3.141592653589793 onloa onpageshow, onpagehide, onresize, onscroll,
[Link](4.4); // = 4 - rounded onunload
[Link](4.5); // = 5
[Link](2,8); // = 256 - 2 to the power Form
o onblur, onchange, onfocus, onfocusin, onfocusout,
[Link](49); // = 7 - square root oninput, oninvalid, onreset, onsearch, onselect,
[Link](-3.14); // = 3.14 - absolute, onsubmi
posit
[Link](3.14); // = 4 - rounded up Drag
ondrag, ondragend, ondragenter, ondragleave,
ondragover, ondragstart, ondrop

Clipboard
oncopy, oncut, onpaste
[Link]([Link]); // OTHERS: Media
tan,atan,asin,ac
onabort, oncanplay, oncanplaythrough,
[Link](0, 3, -2, 2); // = -2 - the lowest ondurationchang onended, onerror, onloadeddata,
value
onloadedmetadata, onloadstart, onpause, onplay,
[Link](0, 3, -2, 2); // = 3 - the highest
onplaying, onprogress, onratechange, onseeked,
value
onseeking, onstalled, onsuspend, ontimeupdate,
[Link](1); // = 0 natural logarithm
onvolumechange, onwaiting
[Link](1); // = 2.7182pow(E,x)
[Link](); // random number between 0 Animation
[Link]([Link]() * 5) + 1; // random animationend, animationiteration, animationstart
integ
Miscellaneous
Dates 📆 transitionend, onmessage, onmousewheel,
ononline, onoffline, onpopstate, onshow,
Mon Feb 17 2020 13:42:03 GMT+0200 (Eastern onstorage, ontoggle, onwheel, ontouchcancel,
European ontouchend, ontouchmove, ontouchstart
Standard Time)
var d = new Date();
1581939723047 miliseconds passed since 1970
Number(d) Arrays ≡
Date("2017-06-23"); // date declara var dogs = ["Bulldog", "Beagle", "Labrador"];
Date("2017"); // is set to var dogs = new Array("Bulldog", "Beagle",
Ja "Labrad
Date("2017-06-23T12:00:00-09:45"); // date -
time alert(dogs[1]); // access value at
Date("June 23 2017"); // long date in dogs[0] = "Bull Terier"; // change the
fo
first i
Date("Jun 23 2017 07:45:00 GMT+0100 (Tokyo
Time)");
Get Times for (var i = 0; i < [Link]; i++) { // pa
[Link](dogs[i]);
var d = new Date();
}
a = [Link](); // getting the weekday
Methods
getDate(); // day as a number (1-31)
[Link](); // conver
getDay(); // weekday as a number (0-6)
[Link](" * "); // join:
getFullYear(); // four digit year (yyyy)
[Link](); // remove
getHours(); // hour (0-23)
[Link]("Chihuahua"); // add
getMilliseconds(); // milliseconds (0-999)
ne dogs[[Link]] = "Chihuahua"; // the
getMinutes(); // minutes (0-59)
sa [Link](); //
getMonth(); // month (0-11)
remove
getSeconds(); // seconds (0-59)
[Link]("Chihuahua"); // add ne
getTime(); // milliseconds since 1970
delete dogs[0]; // change
Setting part of a date [Link](2, 0, "Pug", "Boxer"); // add
el var animals = [Link](cats,birds); //
var d = new Date();
join t [Link](1,4); //
[Link]([Link]() + 7); // adds a week to a
elemen
dat
[Link](); // sort s
setDate(); // day as a number (1-31) [Link](); // sort s
setFullYear(); // year (optionally month and [Link](function(a, b){return a - b}); //
d numeri [Link](function(a, b){return b - a});
setHours(); // hour (0-23)
// numeri highest = x[0]; // first
setMilliseconds(); // milliseconds (0-999)
[Link](function(a, b){return 0.5 -
setMinutes(); // minutes (0-59) [Link]()}
setMonth(); // month (0-11)
setSeconds(); // seconds (0-59) concat, copyWithin, every, fill, filter, find,
setTime(); // milliseconds since 1970) findIndex, forEach, indexOf, isArray, join,
lastIndexOf, map, pop, push, reduce, reduceRight,
reverse, shift, slice, some, sort, splice, toString,
unshift, valueOf

Regular Expressions \n
var a = [Link](/CheatSheet/i);

Modifiers \d
i \s
g \b
m

Patterns
\
perform case-insensitive matching perform a global match Escape character
perform multiline matching find a digit
find a whitespace character
find match at beginning or end of a word
Errors ⚠ n+ contains at least one n
n*
contains zero or more occurrences of n
try { // block of code n?
to contains zero or one occurrences of n
^ undefinedFunction(); Start of string
}

JSON j
catch(err) { // block to handle
[Link]([Link]);
}
var str = '{"names":[' + //
Throw error
cr '{"first":"Hakuna","lastN":"Matata" },' +
throw "My message"; // throw a text '{"first":"Jane","lastN":"Doe" },' +
error '{"first":"Air","last":"Jordan" }]}';
Input validation obj = [Link](str); // pa
var x = [Link]("mynum").value; [Link]([Link][1].first); // ac
//
try { Send
if(x == "") throw "empty"; // var myObj = { "name":"Jane", "age":18,
if(isNaN(x)) throw "not a number"; "city":"Ch var myJSON = [Link](myObj);
x = Number(x); [Link] = "[Link]?x=" + myJSON;
if(x > 10) throw "too high";
} Storing and retrieving
catch(err) { // myObj = { "name":"Jane", "age":18,
[Link]("Input is " + err); // "city":"Chicag myJSON =
[Link](err); // [Link](myObj); /
} [Link]("testJSON", myJSON);
finally { text = [Link]("testJSON");
[Link]("</br />Done"); // / obj = [Link](text);
} [Link]([Link]);

Error name values


RangeError A number is "out of range"

Promises Þ
ReferenceError An illegal reference has occurred
SyntaxError A syntax error has occurred
TypeError A type error has occurred
function sum (a, b) {
URIError An encodeURI() error has occurred
return Promise(function (resolve, reject) {
setTimeout(function () {
if (typeof a !== "number" || typeof b !==
return reject(new TypeError("Inputs must
Useful Links ↵ }
resolve(a + b);
}, 1000);
});
}
var myPromise = sum(10, 5);
[Link](function (result) {
[Link](" 10 + 5: ", result);
return sum(null, "foo"); // Invali
}).then(function () { // Won't
}).catch(function (err) { // The ca
[Link](err); // => Ple
});

States
pending, fulfilled, rejected

Properties
[Link], [Link]

Methods
[Link](iterable), [Link](iterable),
[Link](reason), [Link](value)

HTML Cheat Sheet is using cookies. | Terms and Conditions, Privacy Policy
©2020 [Link]

You might also like