JAVASCRIPT CHEATSHEET AND THEORY GUIDE
===============================================
TABLE OF CONTENTS
=================
1. JavaScript Basics
2. Variables and Data Types
3. Functions
4. Control Structures
5. Objects and Arrays
6. DOM Manipulation
7. Events
8. Asynchronous JavaScript
9. ES6+ Features
10. Common Methods and Properties
11. Best Practices
12. Quick Reference Cheatsheet
===============================================
1. JAVASCRIPT BASICS
====================
What is JavaScript?
-------------------
JavaScript is a high-level, interpreted programming language that enables interactive web
pages. It's an essential part of web applications alongside HTML and CSS.
Key Features:
- Dynamic typing
- Prototype-based object orientation
- First-class functions
- Event-driven programming
- Client-side and server-side execution
How to Include JavaScript:
--------------------------
<!-- Inline JavaScript -->
<script>
console.log("Hello, World!");
</script>
<!-- External JavaScript file -->
<script src="script.js"></script>
<!-- Modern way with defer -->
<script src="script.js" defer></script>
===============================================
2. VARIABLES AND DATA TYPES
============================
Variable Declarations:
----------------------
// ES5 way
var name = "John";
// ES6+ way (preferred)
let age = 25;
const PI = 3.14159;
Differences:
- var: Function-scoped, can be redeclared, hoisted
- let: Block-scoped, cannot be redeclared, hoisted but not initialized
- const: Block-scoped, cannot be reassigned or redeclared
Data Types:
-----------
Primitive Types:
1. String: "Hello", 'World', `Template literal`
2. Number: 42, 3.14, Infinity, NaN
3. Boolean: true, false
4. Undefined: undefined
5. Null: null
6. Symbol (ES6): Symbol('id')
7. BigInt (ES2020): 123n
Non-Primitive Types:
1. Object: {}, {name: "John", age: 30}
2. Array: [], [1, 2, 3]
3. Function: function() {}, () => {}
Type Checking:
--------------
typeof "Hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (known quirk)
typeof {} // "object"
typeof [] // "object"
typeof function() {} // "function"
Array.isArray([]) // true
Array.isArray({}) // false
===============================================
3. FUNCTIONS
============
Function Declaration:
---------------------
function greet(name) {
return "Hello, " + name + "!";
Function Expression:
--------------------
const greet = function(name) {
return "Hello, " + name + "!";
};
Arrow Functions (ES6):
----------------------
const greet = (name) => {
return "Hello, " + name + "!";
};
// Shorthand for single expression
const greet = name => "Hello, " + name + "!";
// Multiple parameters
const add = (a, b) => a + b;
// No parameters
const sayHello = () => "Hello!";
Function Parameters:
--------------------
// Default parameters
function greet(name = "World") {
return "Hello, " + name + "!";
// Rest parameters
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
// Destructuring parameters
function greet({name, age}) {
return `Hello, ${name}! You are ${age} years old.`;
Higher-Order Functions:
-----------------------
// Function that takes another function as parameter
function execute(fn, value) {
return fn(value);
// Function that returns another function
function createMultiplier(factor) {
return function(number) {
return number * factor;
};
const double = createMultiplier(2);
console.log(double(5)); // 10
===============================================
4. CONTROL STRUCTURES
======================
Conditional Statements:
-----------------------
// if-else
if (condition) {
// code
} else if (anotherCondition) {
// code
} else {
// code
// Ternary operator
const result = condition ? valueIfTrue : valueIfFalse;
// Switch statement
switch (value) {
case 'option1':
// code
break;
case 'option2':
// code
break;
default:
// code
Loops:
------
// for loop
for (let i = 0; i < 10; i++) {
console.log(i);
// for...in (for object properties)
for (let key in object) {
console.log(key, object[key]);
// for...of (for iterable values)
for (let value of array) {
console.log(value);
// while loop
while (condition) {
// code
// do...while loop
do {
// code
} while (condition);
// forEach (array method)
array.forEach((item, index) => {
console.log(index, item);
});
Loop Control:
-------------
break; // Exit loop
continue; // Skip to next iteration
===============================================
5. OBJECTS AND ARRAYS
======================
Objects:
--------
// Object literal
const person = {
name: "John",
age: 30,
greet: function() {
return "Hello, I'm " + this.name;
};
// Accessing properties
console.log(person.name); // Dot notation
console.log(person['name']); // Bracket notation
// Adding properties
person.email = "[email protected]";
person['phone'] = "123-456-7890";
// Deleting properties
delete person.age;
// Object methods
Object.keys(person); // Returns array of keys
Object.values(person); // Returns array of values
Object.entries(person); // Returns array of [key, value] pairs
// Object destructuring
const {name, age} = person;
// Object spread operator
const newPerson = {...person, city: "New York"};
Arrays:
-------
// Array literal
const fruits = ["apple", "banana", "orange"];
// Array constructor
const numbers = new Array(1, 2, 3, 4, 5);
// Accessing elements
console.log(fruits[0]); // "apple"
console.log(fruits.length); // 3
// Common array methods
fruits.push("grape"); // Add to end
fruits.pop(); // Remove from end
fruits.unshift("mango"); // Add to beginning
fruits.shift(); // Remove from beginning
fruits.splice(1, 1, "kiwi"); // Remove/replace elements
// Array iteration methods
fruits.forEach(fruit => console.log(fruit));
const upperFruits = fruits.map(fruit => fruit.toUpperCase());
const longFruits = fruits.filter(fruit => fruit.length > 5);
const totalLength = fruits.reduce((sum, fruit) => sum + fruit.length, 0);
// Array destructuring
const [first, second, ...rest] = fruits;
// Array spread operator
const moreFruits = [...fruits, "pineapple", "watermelon"];
===============================================
6. DOM MANIPULATION
====================
Selecting Elements:
-------------------
// By ID
const element = document.getElementById('myId');
// By class name
const elements = document.getElementsByClassName('myClass');
// By tag name
const elements = document.getElementsByTagName('div');
// Query selector (CSS selectors)
const element = document.querySelector('.myClass');
const elements = document.querySelectorAll('.myClass');
Modifying Elements:
-------------------
// Content
element.textContent = "New text";
element.innerHTML = "<strong>Bold text</strong>";
// Attributes
element.setAttribute('class', 'newClass');
element.getAttribute('class');
element.removeAttribute('class');
// Properties
element.id = "newId";
element.className = "newClass";
element.value = "newValue"; // for form elements
// Style
element.style.color = "red";
element.style.backgroundColor = "blue";
element.style.display = "none";
// Classes
element.classList.add('newClass');
element.classList.remove('oldClass');
element.classList.toggle('activeClass');
element.classList.contains('someClass');
Creating and Removing Elements:
-------------------------------
// Create element
const newDiv = document.createElement('div');
newDiv.textContent = "Hello World";
// Append to parent
document.body.appendChild(newDiv);
// Insert before element
parent.insertBefore(newDiv, existingElement);
// Remove element
element.remove();
// or
parent.removeChild(element);
===============================================
7. EVENTS
==========
Event Listeners:
----------------
// Add event listener
element.addEventListener('click', function(event) {
console.log('Element clicked!');
});
// Arrow function
element.addEventListener('click', (event) => {
console.log('Element clicked!');
});
// Remove event listener
element.removeEventListener('click', handlerFunction);
Common Events:
--------------
- click: Mouse click
- mouseover/mouseout: Mouse hover
- mouseenter/mouseleave: Mouse enter/leave
- keydown/keyup: Keyboard events
- submit: Form submission
- load: Page/image loading
- resize: Window resize
- scroll: Page scrolling
Event Object:
-------------
element.addEventListener('click', (event) => {
event.preventDefault(); // Prevent default behavior
event.stopPropagation(); // Stop event bubbling
console.log(event.target); // Element that triggered event
console.log(event.type); // Event type
});
Event Delegation:
-----------------
// Handle events for dynamically created elements
document.addEventListener('click', (event) => {
if (event.target.classList.contains('button')) {
console.log('Button clicked!');
});
===============================================
8. ASYNCHRONOUS JAVASCRIPT
===========================
Callbacks:
----------
function fetchData(callback) {
setTimeout(() => {
const data = "Some data";
callback(data);
}, 1000);
fetchData((data) => {
console.log(data);
});
Promises:
---------
// Creating a promise
const myPromise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("Operation successful!");
} else {
reject("Operation failed!");
});
// Using promises
myPromise
.then(result => console.log(result))
.catch(error => console.error(error))
.finally(() => console.log("Promise completed"));
// Promise methods
Promise.all([promise1, promise2]) // Wait for all
Promise.race([promise1, promise2]) // First to complete
Promise.resolve(value) // Resolved promise
Promise.reject(error) // Rejected promise
Async/Await:
------------
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
// Using async function
fetchData().then(data => console.log(data));
Fetch API:
----------
// GET request
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
// POST request
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({name: 'John', age: 30})
})
.then(response => response.json())
.then(data => console.log(data));
===============================================
9. ES6+ FEATURES
=================
Template Literals:
------------------
const name = "John";
const age = 30;
const message = `Hello, my name is ${name} and I'm ${age} years old.`;
Destructuring:
--------------
// Array destructuring
const [a, b, c] = [1, 2, 3];
const [first, , third] = [1, 2, 3]; // Skip second element
// Object destructuring
const {name, age} = person;
const {name: userName, age: userAge} = person; // Rename
Spread Operator:
----------------
// Arrays
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
// Objects
const obj1 = {a: 1, b: 2};
const obj2 = {...obj1, c: 3}; // {a: 1, b: 2, c: 3}
// Function arguments
function sum(a, b, c) {
return a + b + c;
const numbers = [1, 2, 3];
sum(...numbers); // same as sum(1, 2, 3)
Rest Parameters:
----------------
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
Classes:
--------
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
greet() {
return `Hello, I'm ${this.name}`;
static species() {
return "Homo sapiens";
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
study() {
return `${this.name} is studying`;
}
Modules:
--------
// export.js
export const PI = 3.14159;
export function add(a, b) {
return a + b;
export default class Calculator {
// class definition
// import.js
import Calculator, { PI, add } from './export.js';
import * as math from './export.js';
Map and Set:
------------
// Map
const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');
console.log(map.get('key1')); // 'value1'
map.has('key1'); // true
map.delete('key1');
// Set
const set = new Set([1, 2, 3, 3, 4]);
console.log(set); // Set {1, 2, 3, 4}
set.add(5);
set.has(3); // true
set.delete(2);
===============================================
10. COMMON METHODS AND PROPERTIES
==================================
String Methods:
---------------
const str = "Hello World";
str.length // 11
str.charAt(0) // "H"
str.indexOf("o") // 4
str.lastIndexOf("o") // 7
str.slice(0, 5) // "Hello"
str.substring(0, 5) // "Hello"
str.substr(0, 5) // "Hello"
str.toLowerCase() // "hello world"
str.toUpperCase() // "HELLO WORLD"
str.trim() // Remove whitespace
str.split(" ") // ["Hello", "World"]
str.replace("World", "JS") // "Hello JS"
str.includes("World") // true
str.startsWith("Hello") // true
str.endsWith("World") // true
Number Methods:
---------------
const num = 123.456;
num.toString() // "123.456"
num.toFixed(2) // "123.46"
num.toPrecision(4) // "123.5"
parseInt("123") // 123
parseFloat("123.45") // 123.45
Number.isInteger(123) // true
Number.isNaN(NaN) // true
Math.round(123.456) // 123
Math.floor(123.456) // 123
Math.ceil(123.456) // 124
Math.max(1, 2, 3) // 3
Math.min(1, 2, 3) // 1
Math.random() // Random number 0-1
Array Methods:
--------------
const arr = [1, 2, 3, 4, 5];
arr.push(6) // Add to end
arr.pop() // Remove from end
arr.unshift(0) // Add to beginning
arr.shift() // Remove from beginning
arr.splice(1, 2, 'a', 'b') // Remove/insert elements
arr.slice(1, 3) // Extract portion
arr.concat([6, 7]) // Combine arrays
arr.join(", ") // Convert to string
arr.reverse() // Reverse array
arr.sort() // Sort array
arr.indexOf(3) // Find index
arr.includes(3) // Check if exists
arr.find(x => x > 3) // Find first match
arr.filter(x => x > 3) // Filter elements
arr.map(x => x * 2) // Transform elements
arr.reduce((sum, x) => sum + x, 0) // Reduce to single value
Date Methods:
-------------
const now = new Date();
now.getFullYear() // Year
now.getMonth() // Month (0-11)
now.getDate() // Day of month
now.getDay() // Day of week (0-6)
now.getHours() // Hours
now.getMinutes() // Minutes
now.getSeconds() // Seconds
now.getTime() // Milliseconds since epoch
now.toString() // String representation
now.toDateString() // Date string
now.toTimeString() // Time string
now.toISOString() // ISO format
===============================================
11. BEST PRACTICES
==================
Code Style:
-----------
1. Use meaningful variable names
2. Use camelCase for variables and functions
3. Use PascalCase for classes
4. Use UPPER_CASE for constants
5. Keep functions small and focused
6. Use consistent indentation (2 or 4 spaces)
Performance:
------------
1. Minimize DOM manipulation
2. Use event delegation for dynamic content
3. Avoid global variables
4. Use const and let instead of var
5. Use strict mode: 'use strict';
6. Cache DOM queries
7. Use document fragments for multiple DOM additions
Error Handling:
---------------
try {
// Code that might throw an error
riskyOperation();
} catch (error) {
console.error('An error occurred:', error.message);
} finally {
// Code that always runs
cleanup();
// Custom errors
throw new Error('Something went wrong');
Security:
---------
1. Validate user input
2. Escape HTML content
3. Use HTTPS
4. Don't expose sensitive data in client-side code
5. Use Content Security Policy (CSP)
===============================================
12. QUICK REFERENCE CHEATSHEET
===============================
Variable Declaration:
let name = "John";
const age = 30;
Functions:
function name() {}
const name = () => {};
Conditionals:
if (condition) {} else {}
condition ? true : false;
Loops:
for (let i = 0; i < 10; i++) {}
for (let item of array) {}
array.forEach(item => {});
Objects:
const obj = {key: value};
obj.key or obj['key']
Arrays:
const arr = [1, 2, 3];
arr.push(), arr.pop(), arr.map(), arr.filter()
DOM:
document.querySelector()
element.addEventListener()
element.textContent
element.style.property
Async:
async function() {}
await promise
fetch(url).then().catch()
Events:
element.addEventListener('click', () => {});
Console:
console.log()
console.error()
console.warn()
Common Operators:
=== (strict equality)
!== (strict inequality)
&& (logical AND)
|| (logical OR)
! (logical NOT)
++ (increment)
-- (decrement)
Type Checking:
typeof variable
Array.isArray()
instanceof
JSON:
JSON.stringify(object)
JSON.parse(string)
===============================================
ADDITIONAL RESOURCES
====================
Official Documentation:
- MDN Web Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript
- ECMAScript Specification: https://www.ecma-international.org/ecma-262/
Practice Platforms:
- freeCodeCamp
- Codecademy
- JavaScript.info
- LeetCode (for algorithms)
Useful Libraries:
- Lodash (utility functions)
- Moment.js (date manipulation)
- Axios (HTTP requests)
- jQuery (DOM manipulation - though less common now)
Frameworks:
- React
- Vue.js
- Angular
- Node.js (server-side)
===============================================
This cheatsheet covers the fundamental concepts and practical aspects of JavaScript
programming. Keep it handy for quick reference while coding!