Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
66 views

JavaScript (JS) Cheat Sheet Online

This document provides a summary of JavaScript basics including: - How to include JavaScript code in HTML documents using <script> tags for inline or external JS files. - Common JavaScript functions like setTimeout() for delays, prompt() for input dialogs, and alert() for message boxes. - How to select and modify DOM elements using getElementById() and innerHTML. - Outputting values using console.log(), document.write(), and alert(). - JavaScript variables, data types, operators, and literals for numbers, strings, arrays, booleans, regular expressions, functions, and constants. - Common loops like for, while, do-while and flow control statements like

Uploaded by

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

JavaScript (JS) Cheat Sheet Online

This document provides a summary of JavaScript basics including: - How to include JavaScript code in HTML documents using <script> tags for inline or external JS files. - Common JavaScript functions like setTimeout() for delays, prompt() for input dialogs, and alert() for message boxes. - How to select and modify DOM elements using getElementById() and innerHTML. - Outputting values using console.log(), document.write(), and alert(). - JavaScript variables, data types, operators, and literals for numbers, strings, arrays, booleans, regular expressions, functions, and constants. - Common loops like for, while, do-while and flow control statements like

Uploaded by

rajikare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

12/5/23, 4:03 PM JavaScript (JS) Cheat Sheet Online

Hide comments

JS CheatSheet
Basics ➤ Loops ↶

Ads 📣 On page script


<script type="text/javascript"> ...
For Loop
for (var i = 0; i < 10; i++) {
</script> document.write(i + ": " + i*3 + "<br
}
Include external JS file var sum = 0;
<script src="filename.js"></script> for (var i = 0; i < a.length; i++) {
sum + = a[i];
Delay - 1 second timeout } // parsing an array
html = "";
setTimeout(function () {
for (var i of custOrder) {
}, 1000); html += "<li>" + i + "</li>";
}
Functions
While Loop
function addNumbers(a, b) {
var i = 1; // i
return a + b; ;
} while (i < 100) { // e
x = addNumbers(1, 2); i *= 2; // incre
document.write(i + ", "); // output
}
Edit DOM element
document.getElementById("elementID").innerHTML = "Hello World!";
Do While Loop
var i = 1; // i

If - Else ⇵ Output
console.log(a); // write to the browser console
do {
i *= 2;
// e
// incre
document.write(i + ", "); // output
if ((age >= 14) && (age < 19)) { // logical condition document.write(a); // write to the HTML
} while (i < 100) // r
status = "Eligible."; // executed if condition isalert(a);
true // output in an alert box
} else { confirm("Really?");
// else block is optional // yes/no dialog, returns true/false depending
prompt("Your age?","0"); // Break
input dialog. Second argument is the initia
status = "Not eligible."; // executed if condition is false
for (var i = 0; i < 10; i++) {
} Comments if (i == 5) { break; } // st
Switch Statement /* Multi line document.write(i + ", "); // l
comment */ }
switch (new Date().getDay()) { // input is current day
// One line
case 6: // if (day == 6) Continue
text = "Saturday";
for (var i = 0; i < 10; i++) {
break;
if (i == 5) { continue; } // s
case 0: // if (day == 0) Variables x document.write(i + ", "); // s
text = "Sunday";
}
break; var a; // variable
default: // else... var b = "init"; // string

📣
text = "Whatever"; var c = "Hi" + " " + "Joe"; // = "Hi Joe"
} var d = 1 + 2 + "3"; // = "33"
var e = [2,3,5,8]; // array
Ads
var f = false; // boolean
var g = /()/; // RegEx
Data Types ℜ var h = function(){}; // function object
const PI = 3.14; // constant
var age = 18; // number var a = 1, b = 2, c = a + b; // one line
var name = "Jane"; // string let z = 'zzz'; // block scope local variable
var name = {first:"Jane", last:"Doe"}; // object
var truth = false; // boolean Strict mode
var sheets = ["HTML","CSS","JS"]; // array "use strict"; // Use strict mode to write secure code
var a; typeof a; // undefined x = 1; // Throws an error because variable is not declared
var a = null; // value null
Values
Objects false, true // boolean
var student = { // object name 18, 3.14, 0b10011, 0xF6, NaN // number
firstName:"Jane", // list of properties and values "flower", 'John' // string
lastName:"Doe", undefined, null , Infinity // special
age:18,
height:170, Operators
fullName : function() { // object function a = b + c - d; // addition, substraction
return this.firstName + " " + this.lastName; a = b * (c / d); // multiplication, division
} x = 100 % 48; // modulo. 100 / 48 remainder = 4
}; a++; b--; // postfix increment and decrement
student.age = 19; // setting value
student[age]++; // incrementing Bitwise operators
name = student.fullName(); // call object function & AND 5 & 1 (0101 & 0001) 1 (1)
| OR 5 | 1 (0101 | 0001) 5 (101)
~ NOT ~ 5 (~0101) 10 (1010)
^ XOR 5 ^ 1 (0101 ^ 0001) 4 (100)
Strings ⊗ << left shift 5 << 1 (0101 << 1) 10 (1010)
>> right shift 5 >> 1 (0101 >> 1) 2 (10)
var abc = "abcdefghijklmnopqrstuvwxyz";
>>> zero fill right shift 5 >>> 1 (0101 >>> 1) 2 (10)
var esc = 'I don\'t \n know'; // \n new line
var len = abc.length; // string length
Arithmetic
abc.indexOf("lmno"); // find substring, -1 if doesn't contain
a * (b + c) // grouping
abc.lastIndexOf("lmno"); // last occurance
abc.slice(3, 6); person.age
// cuts out "def", negative values count f // member
person[age] // member
abc.replace("abc","123"); // find and replace, takes regular express
!(a == b) // logical not
abc.toUpperCase(); // convert to upper case
abc.toLowerCase(); // convert to lower case a != b // not equal
typeof a // type (number, object, function...)

🕖
abc.concat(" ", str2); // abc + " " + str2
x << 2 x >> 3 // minary shifting
abc.charAt(2); // character at index: "c"
abc[2]; // unsafe, abc[2] = "C" doesn'ta work
= b // assignment Events
// character code at index: "c"a ->
== 99
b // equals
abc.charCodeAt(2);
// splitting a string on commasa gives
!= b an a // unequal <button onclick="myFunction();">
abc.split(",");
abc.split(""); // splitting on characters a === b // strict equal Click here
// number to hex(16), octal (8)a or
!==binary
b // strict unequal </button>
128.toString(16);
a < b a > b // less and greater than
a <= b a >= b // less or equal, greater or eq Mouse

https://htmlcheatsheet.com/js/ 1/3
12/5/23, 4:03 PM JavaScript (JS) Cheat Sheet Online
a += b // a = a + b (works with - * %...) onclick, oncontextmenu, ondblclick, onmo
Numbers and Math ∑ a && b // logical and onmousemove, onmouseover, onmouseo
var pi = 3.141; a || b // logical or
Keyboard

📆
pi.toFixed(0); // returns 3
onkeydown, onkeypress, onkeyup
pi.toFixed(2); // returns 3.14 - for working with money
pi.toPrecision(2) // returns 3.1 Dates Frame
pi.valueOf(); // returns number
onabort, onbeforeunload, onerror, onhash
Number(true); // converts to number Tue Dec 05 2023 15:59:49 GMT+0530 (India Standard Time)
onpagehide, onresize, onscroll, onunload
Number(new Date()) // number of milliseconds since 1970 var d = new Date();
parseInt("3 months"); // returns the first number: 3 1701772189991 miliseconds passed since 1970 Form
parseFloat("3.5 days"); // returns 3.5 Number(d) onblur, onchange, onfocus, onfocusin, onf
Number.MAX_VALUE // largest possible JS number onsearch, onselect, onsubmit
Date("2017-06-23"); // date declaration
Number.MIN_VALUE // smallest possible JS number
Date("2017"); // is set to Jan 01
Number.NEGATIVE_INFINITY// -Infinity Drag
Number.POSITIVE_INFINITY// Infinity Date("2017-06-23T12:00:00-09:45"); // date - time YYYY-MM-DDTHH:MM:SSZ
Date("June 23 2017"); // long date format
ondrag, ondragend, ondragenter, ondragle
Math. Date("Jun 23 2017 07:45:00 GMT+0100 (Tokyo Time)"); // time zone
Clipboard
var pi = Math.PI; // 3.141592653589793 oncopy, oncut, onpaste
Get Times
Math.round(4.4); // = 4 - rounded
var d = new Date(); Media
Math.round(4.5); // = 5
Math.pow(2,8); // = 256 - 2 to the power of 8 a = d.getDay(); // getting the weekday
onabort, oncanplay, oncanplaythrough, on
Math.sqrt(49); // = 7 - square root onloadeddata, onloadedmetadata, onload
getDate(); // day as a number (1-31)
Math.abs(-3.14); // = 3.14 - absolute, positive value onprogress, onratechange, onseeked, ons
getDay(); // weekday as a number (0-6) ontimeupdate, onvolumechange, onwaitin
Math.ceil(3.14); // = 4 - rounded up
Math.floor(3.99); // = 3 - rounded down getFullYear(); // four digit year (yyyy)
getHours(); // hour (0-23) Animation
Math.sin(0); // = 0 - sine
getMilliseconds(); // milliseconds (0-999) animationend, animationiteration, animatio
Math.cos(Math.PI); // OTHERS: tan,atan,asin,acos,
Math.min(0, 3, -2, 2); // = -2 - the lowest value getMinutes(); // minutes (0-59)
getMonth(); // month (0-11) Miscellaneous
Math.max(0, 3, -2, 2); // = 3 - the highest value
getSeconds(); // seconds (0-59) transitionend, onmessage, onmousewhee
Math.log(1); // = 0 natural logarithm
getTime(); // milliseconds since 1970 onstorage, ontoggle, onwheel, ontouchca
Math.exp(1); // = 2.7182pow(E,x)
Math.random(); // random number between 0 and 1 ontouchstart
Setting part of a date
Math.floor(Math.random() * 5) + 1; // random integer, from 1 to 5
var d = new Date();
Constants like Math.PI: d.setDate(d.getDate() + 7); // adds a week to a date
E, PI, SQRT2, SQRT1_2, LN2, LN10, LOG2E, Log10E
setDate(); // day as a number (1-31)
setFullYear(); // year (optionally month and day) Arrays ≡
setHours(); // hour (0-23)
setMilliseconds(); // milliseconds (0-999) var dogs = ["Bulldog", "Beagle", "La
Global Functions ()
setMinutes(); // minutes (0-59) var dogs = new Array("Bulldog", "Bea
eval(); setMonth();
// executes a string as if it was script code // month (0-11)
String(23); // return string from number setSeconds(); // seconds (0-59) alert(dogs[1]); // acces
(23).toString(); // return string from number setTime(); // milliseconds since 1970) dogs[0] = "Bull Terier"; // chang
Number("23"); // return number from string
decodeURI(enc); // decode URI. Result: "my page.asp" for (var i = 0; i < dogs.length; i++
encodeURI(uri); // encode URI. Result: "my%page.asp" console.log(dogs[i]);
Regular Expressions \n }
decodeURIComponent(enc); // decode a URI component
encodeURIComponent(uri); // encode a URI component var a = str.search(/CheatSheet/i);
isFinite(); // is variable a finite, legal number Methods
isNaN(); // is variable an illegal number dogs.toString();
Modifiers
parseFloat(); // returns floating point number of string dogs.join(" * ");
parseInt();
i
// parses a string and returns an integer
perform case-insensitive matching dogs.pop();
g perform a global match dogs.push("Chihuahua");
m perform multiline matching

📣
dogs[dogs.length] = "Chihuahua";
Patterns dogs.shift();
Ads dogs.unshift("Chihuahua");
\ Escape character
delete dogs[0];
\d find a digit
\s find a whitespace character dogs.splice(2, 0, "Pug", "Boxer");
\b find match at beginning or end of a word var animals = dogs.concat(cats,birds
n+ contains at least one n dogs.slice(1,4);
n* contains zero or more occurrences of n dogs.sort();
n? contains zero or one occurrences of n dogs.reverse();
^ Start of string x.sort(function(a, b){return a - b})
$ End of string x.sort(function(a, b){return b - a})
\uxxxx find the Unicode character highest = x[0];
. Any single character x.sort(function(a, b){return 0.5 - M
(a|b) a or b
(...)
[abc]
Errors
[0-9]
[^abc]
⚠ Group section
In range (a, b or c)
any of the digits between the brackets
Not in range
concat, copyWithin, every, fill, filter, find, fi
lastIndexOf, map, pop, push, reduce, redu
splice, toString, unshift, valueOf
try { // block of code to try
\s White space
undefinedFunction();
a? Zero or one of a
}
a* Zero or more of a
catch(err) { // block to handle errors
a*? Zero or more, ungreedy JSON j
console.log(err.message);
a+ One or more of a
}
a+? One or more, ungreedy var str = '{"names":[' +
a{2} Exactly 2 of a '{"first":"Hakuna","lastN":"Matata"
Throw
a{2,} error 2 or more of a '{"first":"Jane","lastN":"Doe" },' +
a{,5} "My error message";
throw Up to 5 of a// throw a text '{"first":"Air","last":"Jordan" }]}'
a{2,5} 2 to 5 of a obj = JSON.parse(str);
a{2,5}?
Input validation 2 to 5 of a, ungreedy document.write(obj.names[1].first);
[:punct:] Any punctu­ation symbol
var x = document.getElementById("mynum").value;
[:space:] Any space character // get input value
Send
try {
[:blank:] Space or tab
if(x == "") throw "empty"; // error cases var myObj = { "name":"Jane", "age":1
if(isNaN(x)) throw "not a number"; var myJSON = JSON.stringify(myObj);
x = Number(x); window.location = "demo.php?x=" + my
if(x > 10) throw "too high";
Storing and retrieving
}
catch(err) { myObj
// if there's an = { "name":"Jane", "age":18, "
error
document.write("Input is " + err); // output error myJSON = JSON.stringify(myObj);
console.error(err); // write the error localStorage.setItem("testJSON",
in console myJ
} text = localStorage.getItem("testJSO
finally { obj = JSON.parse(text);
document.write("</br />Done"); document.write(obj.name);
// executed regardless of the
}

https://htmlcheatsheet.com/js/ 2/3
12/5/23, 4:03 PM JavaScript (JS) Cheat Sheet Online
Promises Þ Error name values Useful Links ↵
RangeError A number is "out of range"
function sum (a, b) { ReferenceError An illegal reference has occurred JS cleaner Obfus
return Promise(function (resolve, reject) { SyntaxError A syntax error has occurred
setTimeout(function () { // send th
TypeError A type error has occurred Node.js jQuery
if (typeof a !== "number" || typeof b !== "number") { // testing
URIError An encodeURI() error has occurred
return reject(new TypeError("Inputs must be numbers"));
}
resolve(a + b);
}, 1000);
});
}
var myPromise = sum(10, 5);
myPromsise.then(function (result) {
document.write(" 10 + 5: ", result);
return sum(null, "foo"); // Invalid data and return another p
}).then(function () { // Won't be called because of the
}).catch(function (err) { // The catch handler is called ins
console.error(err); // => Please provide two numbers to
});

States
pending, fulfilled, rejected

Properties
Promise.length, Promise.prototype

Methods
Promise.all(iterable), Promise.race(iterable), Promise.reject(reason),
Promise.resolve(value)

HTML Cheat Sheet is using cookies. | PDF | Terms and Conditions, Privacy Policy
© HTMLCheatSheet.com

https://htmlcheatsheet.com/js/ 3/3

You might also like