JavaScript Cheat Sheet - A Basic Guide to JavaScript
JavaScript Cheat Sheet - A Basic Guide to JavaScript
Instant PDF
Download.
Open
Open In App
JavaScript Chear Sheet
Fundamentals
To use JavaScript on a website, attach the JavaScript file to the HTML
file. Enclose the code within the <script> tag for the browser to
recognize and execute it:
<script type="text/javascript">
// Your JavaScript code
</script>
<script src="filename.js"></script>
Variables
Datatypes
In JavaScript, data types define the type of value a variable can hold.
Understanding the types is crucial for evaluating expressions and
ensuring the correct operations are performed on variables.
JavaScript has both primitive and non-primitive data types:
Open In App
Datatype Description Example
Undefined Represents a
variable which is
let x; / let x= undefined;
declared but not
assigned any value.
y: any datatype
Stores multiple
values of same type
in a single variable.
Secure your business for the AI future
// String
let str = "hello geeks";
console.log(str); Open In App
// Number
const num = 10;
console.log(num);
// Boolean
const x = "true";
console.log(x);
// Undefined
let name;
console.log(name );
// Null
// Symbol
const val1 = Symbol("hello");
const val2 = Symbol("hello");
console.log(val1);
console.log(val2);
const obj = {
firstName: "geek",
lastName: null,
batch: 2,
};
console.log(obj);
Primitive types (like Number, String, Boolean, Null, and Undefined) store
single values.
Non-primitive types (like Object, Array, and Function) can store
collections of data or executable code.
Operators
Open In App
Operators Description Symbols
let x = 5;
let y = 3;
// Addition
console.log("x + y = ", x); // 8
// Subtraction
console.log("x - y = ", x - y); // 2
// Multiplication
console.log("x * y = ", x * y); // 15
// Division
console.log("x / y = ", x / y);
// Remainder
Open//
console.log("x % y = ", (x % y)); In App
2
// Increment
console.log("++x = ", ++x); // x is now 6
console.log("x++ = ", x++);
console.log("x = ", x); // 7
// Decrement
console.log("--x = ", --x); // x is now 6
console.log("x-- = ", x--);
console.log("x = ", x); // 5
// Exponentiation
console.log("x ** y =", x ** y);
// Comparison
console.log(x > y); // true
// Equal operator
console.log((2 == 2)); // true
// Logical Operator
// Logical AND
console.log((x < 6 && y < 5)); // true
// Logical OR
console.log((x < 6 || y > 6)); // true
// Logical NOT
console.log(!(x < 6)); // false
Scope Chain:
let a = 10;
function example() {
let b = 20; // Exists in function scope
if (true) {
var c = 30; // Exists in function scope (due to 'var')
const d = 40; // Exists in block scope
}
example();
Functions
Function Description
prompt() Creates a dialogue box for taking input from the user.
// JS parseInt function:
const num1 = parseInt("100.45");
console.log('Using parseInt("100.45") = ' + num1);
// JS parseFloat function:
const num2 = parseFloat("123.45abc");
console.log('parseFloat("123.45abc") = ' + num2);
// JS isNaN function:
console.log(isNaN("hello"));
// JS Number() function:
const num3 = Number("123"); Open In App
console.log("Value of '123': " + num3);
// JS eval() function:
function evalExample() {
const expression = "2 + 3 * 4"; // Example expression to evaluate
const result = eval(expression); // Evaluates '2 + 3 * 4' and
returns 14
console.log(result);
}
evalExample();
// JS encodeURI function:
const url = "https://example.com/hello world?query=javascript";
const encodedURL = encodeURI(url); // Encodes spaces as '%20' and
ensures valid URL.
console.log(encodedURL);
Arrays
Example:
Open In App
var House = [ ]; // Method 1
var House = new Array(); // Method 2
Method Description
// Num Array
let arr = [10, 20, 30, 40, 50];
let arr1 = [110, 120, 130, 140];
// String array
let string_arr = ["Alex", "peter", "chloe"];
Loops
do- do
while {
Exit Control Loop which
statements..
executes once before
}
checking the condition.
while (condition);
do {
z++;
} while (z < 20);
If-else
Open In App
JavaScript allows us to nest if statements within if statements as well.
i.e, we can place an if statement inside another if statement.
if (i < 15)
console.log("Value of i is less than 10");
else
console.log("Value of i is greater than 10");
Strings
Strings in JavaScript are primitive and immutable data types used for
storing and manipulating text data which can be zero or more
characters consisting of letters, numbers or symbols.
JavaScript provides a lot of methods to manipulate strings. Some most
used ones are:
Methods Description
// concat() method
console.log(gfg.concat(geeks));
// match() method
console.log(geeks.match(/eek/));
// charAt() method
console.log(geeks.charAt(5));
// valueOf() method
console.log(geeks.valueOf());
// lastIndexOf() method
console.log(geeks.lastIndexOf('for'));
// substr() method
console.log(geeks.substr(6));
// indexOf() method
console.log(gfg.indexOf('G'));
// replace() method
console.log(gfg.replace('FG', 'fg'));
// slice() method
Open In App
console.log(geeks.slice(2, 8));
// split() method
console.log(geeks.split('-'));
// toUpperCase method
console.log(geeks.toUpperCase(geeks));
// toLowerCase method
console.log(geeks.toLowerCase(geeks));
Regular Expressions
Modifiers Description
Open In App
Metacharacters Description
Quantifiers:
Quantifiers Description
if (result) {
console.log("The email is valid.");
} else {
console.log("The email is not valid.");
}
}
// Input Email Id
let email = "[email protected]"
validateEmail(email);
email = "abc#$#@45com"
validateEmail(email);
Data Transformation
function checkAdult(age) {
return age >= 18;
}
Date objects
Syntax:
new Date()
new Date(milliseconds)
new Date(dataString)
Open In App
new Date(year, month, date, hour, minute, second,
millisecond)
There are various methods in JavaScript used to get date and time values
or create custom date objects. Some of these methods are:
Method Description
// getDate()
let A = DateObj.getDate();
// getTime()
let B = DateObj.getTime();
// Printing minute.
console.log(minutes);
// getFullYear()
let C = DateObj.getFullYear();
// Printing year
console.log(C);
// getDay()
let Day = DateObj.getDay();
// setDate
DateObj.setDate(15);
let D = DateObj.getDate();
DOM
Method Description
Open In App
Method Description
<!DOCTYPE html>
<html>
<head>
/* CSS is used to make the output looks good */
<style>
#sudo {
border: 1px solid green;
background-color: green;
margin-bottom: 10px;
color: white;
font-weight: bold;
}
h1,
h2 {
text-align: center;
color: green;
font-weight: bold;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h2>DOM appendChild() Method</h2>
Open In App
<div id="sudo">
The Good Website is learning for Computer Science is-
</div>
<button onclick="geeks()">Submit</button>
<br />
<div style="border: 3px solid green">
<h1>GeeksforGeeks</h1>
<h2>A computer science portal for geeks</h2>
</div>
<h2>DOM cloneNode() Method</h2>
<button onclick="nClone()">
Click here to clone the above elements.
</button>
<br />
<h2>DOM hasAttributes() Method</h2>
<p id="gfg">
Click on the button to check if that
body element has any attributes
</p>
<button type="button" onclick="hasAttr()">
Submit
</button>
<br />
<h2>DOM removeChild() Method</h2>
<p>Sorting Algorithm</p>
<ul id="listitem">
<li>Insertion sort</li>
<li>Merge sort</li>
<li>Quick sort</li>
</ul>
<button onclick="Geeks()">
Click Here!
</button>
<br />
<h2>DOM getAttribute() Method</h2>
<br />
<button id="button" onclick="getAttr()">
Submit
</button>
<p id="gfg1"></p>
<br />
<h2>DOM getElementsByTagName()</h2>
<p>A computer science portal for geeks.</p>
<button onclick="getElememt()">
Try it
</button>
<h3>DOM isEqualNode() method .</h3>
<!-- 3 div elements-->
<div>GeeksforGeeks</div>
<div>GfG</div>
<div>GeeksforGeeks</div>
<button onclick="isequal()">
Check
</button>
<p id="result"></p> Open In App
<script>
function geeks() {
var node = document.createElement("P");
var t = document.createTextNode("GeeksforGeeks");
node.appendChild(t);
document.getElementById("sudo").appendChild(node);
}
function nClone() {
// Accessing div attribute using a variable geek
var geek = document.getElementsByTagName("DIV")[0];
function Geeks() {
var doc = document.getElementById("listitem");
doc.removeChild(doc.childNodes[0]);
}
/* Using getElementById */
function getAttr() {
var rk =
document.getElementById("button").getAttribute("onClick");
document.getElementById("gfg1").innerHTML = rk;
}
/* Using getElementsByTagName */
function getElement() {
var doc = document.getElementsByTagName("p");
doc[0].style.background = "green";
doc[0].style.color = "white";
}
</html>
Method Description
<script type="text/javascript">
var num = 213;
var num1 = 213.3456711;
// JS valueof() Method
console.log("Output : " + num.valueOf());
// JS tostring() Method
console.log("Output : " + num.toString(2));
// JS tofixed() Method
console.log("Output : " + Open In App
num1.toString(2));
// JS topricision() Method
console.log("Output : " + num1.toPrecision(3));
// JS toexponential() Method
console.log("Output : " + num1.toExponential(4));
</script>
Method Description
<script>
document.getElementById("GFG").innerHTML =
"Math.LN10: " + Math.LN10 + "<br>" +
Open In App
"Math.LOG2E: " + Math.LOG2E + "<br>" +
"Math.Log10E: " + Math.LOG10E + "<br>" +
"Math.SQRT2: " + Math.SQRT2 + "<br>" +
"Math.SQRT1_2: " + Math.SQRT1_2 + "<br>" +
"Math.LN2: " + Math.LN2 + "<br>" +
"Math.E: " + Math.E + "<br>" +
"Math.round: " + Math.round(5.8) + "<br>" +
"Math.PI: " + Math.PI + "<br>" +
"
< p > <b>Math.sin(90 * Math.PI / 180):</b> " +
Math.sin(90 * Math.PI / 180) + "</p>
" +
"
< p > <b>Math.tan(90 * Math.PI / 180):</b> " +
Math.tan(90 * Math.PI / 180) + "</p>
" +
"
< p > <b>Math.max(0, 150, 30, 20, -8, -200):</b> " +
Math.max(0, 150, 30, 20, -8, -200) + "</p>
" +
"
< p > <b>Math.min(0, 150, 30, 20, -8, -200):</b> " +
Math.min(0, 150, 30, 20, -8, -200) + "</p>
" +
"
< p > <b>Math.pow(3,4):</b> " + Math.pow(3, 4) + "</p >
";
</script>
Events
Events Description
Open In App
Events Description
<!DOCTYPE html>
<html>
<head>
/* CSS is used to make the output looks good */
<style>
#geeks {
border: 1px solid black;
padding: 15px;
width: 60%;
}
h1 {
color: green;
}
</style>
<script> Open In App
function hiThere() {
alert("Hi there!");
}
function focused() {
var e = document.getElementById("inp");
if (confirm("Got it?")) {
e.blur();
}
}
/* Mouseover event */
document.getElementById("hID").addEventListener("mouseover",
over);
/* Mouseoout event */
document.getElementById("hID").addEventListener("mouseout",
out);
/* Over on green */
function over() {
document.getElementById("hID").style.color = "green";
}
function Geeks() {
var x = document.getElementById("GFG").value;
document.getElementById("sudo").innerHTML = "Selected
Subject: " + x;
}
/* Success alert */
function Geek() {
alert("Form submitted successfully.");
}
function Function() {
document.getElementById("geeks").style.fontSize = "30px";
document.getElementById("geeks").style.color = "green";
}
</script>
</head>
<body>
<!-- onload event -->
<img onload="alert('Image completely loaded')" alt="GFG-Logo"
src="https://media.geeksforgeeks.org/wp-content/cdn-
uploads/GeeksforGeeksLogoHeader.png" />
<br />
<p id="sudo"></p>
Error
When executing JavaScript code, errors will most definitely occur when
the JavaScript engine encounters a syntactically invalid code.
These errors can occur due to the fault from the programmer’s side or
the input is wrong or even if there is a problem with the logic of the
program.
Javascript has a few statements to deal with these errors:
Statement Description
<!DOCTYPE html>
<html>
<body>
<h2>
JavaScript throw try catch finally keywords
</h2>
<p>Please enter a number:</p>
<input id="demo" type="text" />
<button type="button" onclick="myFunction()">
Test Input
</button>
<p id="p01"></p>
<script>
function myFunction() {
const message = document.getElementById("p01");
message.innerHTML = "";
let x = document.getElementById("demo").value;
Open In App
/* Using try.. catch.. with conditions*/
try {
if (x == "") throw "is empty";
if (isNaN(x)) throw "is not a number";
x = Number(x);
if (x > 20) throw "is too high";
if (x <= 20) throw "is too low";
} catch (err) {
message.innerHTML = "Input " + err;
} finally {
document.getElementById("demo").value = "";
}
}
</script>
</body>
</html>
Window Properties
Syntax:
window.property_name
The properties and methods of Window object that are commonly used
are listed in the below tables:
Property Description
Open In App
Property Description
<!DOCTYPE html>
<html>
<body>
<h1>The Window properties</h1>
<h2>The origin Property</h2>
<p id="demo"></p>
<br />
<button type="button" onclick="getResolution();">
Get Resolution
</button>
<br />
<button type="button" onclick="checkConnectionStatus();">
Check Connection Status
</button>
<br />
<button type="button" onclick="getViews();">
Get Views Count</button>
<br />
<p>
<button onclick="closeWin()">
Close "myWindow"
</button>
</p>
Open In App
<script>
// JS location property
let origin = window.location.origin;
document.getElementById("demo").innerHTML = origin;
// JS screen property
function getResolution() {
alert("Your screen is: " + screen.width + "x" +
screen.height);
}
// JS toolbar property
var visible = window.toolbar.visible;
// JS navigator property
function checkConnectionStatus() {
if (navigator.onLine) {
alert("Application is online.");
} else {
alert("Application is offline.");
}
}
// JS history property
function getViews() {
alert(
"You've accessed " + history.length + " web pages in
this session."
);
}
// JS close property
let myWindow;
function closeWin() {
if (myWindow) {
myWindow.close();
}
}
</script>
</body>
</html>
Method Description
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Window Methods</title>
/* CSS is used to make the output looks good */
<style>
.gfg {
font-size: 36px;
}
form {
float: right;
margin-left: 20px;
}
</style>
</head>
<body>
<div class="gfg">JavaScript Window Methods</div>
<br />
<button onclick="windowOpen()">
JavaScript window Open
</button>
<button onclick="resizeWin()">
Open In App
JavaScript window resizeTo
</button>
<button onclick="windowBlur()">
JavaScript window Blur
</button>
<button onclick="windowFocus()">
JavaScript window Focus
</button>
<button onclick="windowClose()">
JavaScript window Close
</button>
<br />
<br />
<p id="g"></p>
<form>
<button onclick="setTimeout(wlcm, 2000);">
Alert after 2 Second
</button>
<button onclick="geek()">Click me!</button>
<input type="button" value="Print" onclick="window.print()"
/>
</form>
<br /><br />
<button id="btn" onclick="fun()" style="color: green">
JavaScript Used setTimeOut
</button>
<button id="btn" onclick="stop()">
JavaScript clearTimeout
</button>
<script>
var gfgWindow;
// Alert function
function wlcm() {
alert("Welcome to GeeksforGeeks");
}
// Prompt function
function geek() {
var doc = prompt("Please enter some text",
"GeeksforGeeks");
if (doc != null) {
document.getElementById("g").innerHTML = "Welcome to
" + doc;
}
}
</html>
Recommended Links:
JavaScript Tutorial
JavaScript Examples
HTML Cheat Sheet
CSS Cheat Sheet
Self-paced JavaScript course
Similar Reads
15 min read
13 min read
5 min read
6 min read
Registered Address:
K 061, Tower K, Gulshan Vivante
Apartment, Sector 137, Noida,
Gautam Buddh Nagar, Uttar Pradesh,
201305
Open In App
Advertise with us
Company Languages
About Us Python
Legal Java
Privacy Policy C++
In Media PHP
Contact Us GoLang
Advertise with us SQL
GFG Corporate Solution R Language
Placement Training Program Android Tutorial
GeeksforGeeks Community Tutorials Archive
Open In App