JavaScript Snippets
Console
Section titled “Console”// In web browser console, allow editing directly on web page// Useful for viewing content changesdocument.designMode = "on";
Basics
Section titled “Basics”Datatypes and Variables
Section titled “Datatypes and Variables”// Numbers - example: number of likes, prices// Integer - whole numbers0
// Decimal035.6-40
// String - example: letters, words, symbols, anything on your keyboard// 0 or more characters"a""a long string"'another string'"5""first.name@email.com"
// Character"a"
// Boolean// - example: wrong password, invalid email (incorrect),// available (true)truefalse
// Array - example: list of friends, comments["John", "Mary", "Ralph"][4, 4.6, 6]// Data types can be mixed in array
// Object - example: product review has group of information// written using curly braces { ... }// Any datatype can be used inside an object, as well as objects{authorName: "user12", rating: 5, explanation: "great product", images ["imageLink1", "imageLink2"]}
// Array of objects[ {authorName: "user12", rating: 5, explanation: "great product", images ["imageLink1", "imageLink2"]}, {authorName: "user62", rating: 4, explanation: "great product", images ["imageLink6", "imageLink7"]}, // Other objects
]
// Working with numbers - example: calculate prices, distances3 + 46 * 5// Strings with + will combine strings// String concatenation"12" + "12" = "1212"
// Variablevar userName = "app-user-A"var price = "50"// Display $50"$" + 50
// var, let, const// variables that will not changeconst = "Brand Name"
// variables that can change, but not recreatedlet userName = "James"
Conditions and Operators, Functions
Section titled “Conditions and Operators, Functions”// Equality comparision
// Set variablelet age = 30// True equality check of valuesage == 30// False, equality check of values and data type// using triple equals ===, good practice to use it most of timeage === "30"
// Not equals comparisonlet userMembership = "regular"if (userMembership !== "premium"){ // show user regular content} else { // show premium content}
// Comparisionslet totalPrice = 19// False - check greater thantotalPrice > 20// True - check greater than, equal tototalPrice >= 19
// If, else conditionslet totalPrice = 19;let shippingCost;if (totalPrice <= 10) { shippingCost = 0} else if (totalPrice <= 20 ){ shippingCost = 3} else { shippingCost = 0}
// Logical AND, OR || operators// OR operator(totalPrice > 20 || premiumMember === true)
// AND operator(today === birthday && birthdayDisplayed === true)
// Negate condition with !()!((totalPrice > 20 || premiumMember === true))
// Log text with variableconsole.log(`Shipping cost for you is ${shippingCost}`);
// Function with no parameters and void returnfunction calculateShippingCost() { let totalPrice = 19;
if (totalPrice <= 10) { shippingCost = 5; } else if (totalPrice <= 20) { shippingCost = 3; } else { shippingCost = 0; }
console.log(`Shipping cost for you is ${shippingCost}`);}
Debugger
Section titled “Debugger”function startsWithJ(array) { {const jStudents = []; // Add debugger, will run in things like web tools or node inspect debugger; for (let i = 0; i < array.length; i++) { const currentStudent = array[i]; const firstLetter = currentStudent[0]; if (firstLetter === "J") { jStudents.push(currentStudent); } } } return jStudents;}
Bookmarklets
Section titled “Bookmarklets”Source: What are Bookmarklets? How to Use JavaScript to Make a Bookmarklet in Chromium and Firefox
Creating a bookmarklet is like creating a regular bookmark in the browser. Instead of the URL HTTP/HTTPS in the URL field, write JavaScript.
// Bookmarklet with (() => { }) as an anonymous (lambda) functionjavascript: (() => { alert('Dismissing topics'); // Select a button inside a specific div const selector = 'div[aria-label=Dismiss][role=button]'; const topics = document.querySelectorAll(selector);
// Click dismiss for each topic for (let i = 0; i < topics.length; i++) { let topic = topics[i]; setTimeout(() => topic.click(), i * 250); }
// generate and return HTML return '<h1 style="color: white; background-color: black;">Hello, World!</h1>';})();
// Find unique emails on pagejavascript: (() => { const documentHTML = document.documentElement.outerHTML; const matches = documentHTML.matchAll(/[\w.+=~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*/g); const flatMatches = Array.from(matches).map((item) => item[0]); const uniqueMatches = Array.from(new Set(flatMatches));
if (uniqueMatches.length > 0) { const result = uniqueMatches.join('\n'); alert(result); } else { alert('No emails found!'); }})();
// Change all font elementsjavascript: (() => { const allElements = document.querySelectorAll('*');
for (let element of allElements) { element.style.fontFamily = 'Comic Sans MS'; }})();
<!-- Create a link for someone to bookmark the link as a bookmarklet --><a href="javascript: (() => { alert('Hello, World!'); })();"> Hello, World!</a>