JavaScript programming language cheat sheet.
- User
JavaScript programming language cheat sheet.
Assistant
/* * JAVASCRIPT CHEAT SHEET */ /*********************** * BASICS ***********************/ // Comments: // Single-line comment /* Multi-line comment */ // Variables: let myVariable = "Hello"; // Mutable variable (ES6+) const MY_CONSTANT = 123; // Immutable variable (ES6+) var oldVariable = true; // Older style, avoid using // Data Types: let myString = "This is a string"; let myNumber = 42; let myBoolean = true; let myNull = null; let myUndefined = undefined; let mySymbol = Symbol("unique"); // ES6+ symbol let myObject = { name: "John", age: 30 }; let myArray = [1, 2, 3]; let myFunction = function() { return "Hello from function"; }; // Operators: // Arithmetic: let sum = 10 + 5; // Addition let difference = 10 - 5; // Subtraction let product = 10 * 5; // Multiplication let quotient = 10 / 5; // Division let remainder = 10 % 3; // Modulus (remainder) let exponent = 2 ** 3; // Exponentiation (ES2016+) // Assignment: let x = 5; x += 2; // x = x + 2 x -= 2; // x = x - 2 x *= 2; // x = x * 2 x /= 2; // x = x / 2 x %= 2; // x = x % 2 // Comparison: let isEqual = 5 == "5"; // Loose equality (type coercion) - Avoid let isStrictEqual = 5 === "5"; // Strict equality (no type coercion) - Use this let isNotEqual = 5 != "5"; // Loose inequality - Avoid let isStrictNotEqual = 5 !== "5"; // Strict inequality - Use this let isGreaterThan = 10 > 5; let isLessThan = 10 < 5; let isGreaterOrEqual = 10 >= 5; let isLessOrEqual = 10 <= 5; // Logical: let and = true && false; // Logical AND let or = true || false; // Logical OR let not = !true; // Logical NOT // Typeof: let type = typeof myString; // Returns "string" /*********************** * CONTROL FLOW ***********************/ // If/Else Statements: let age = 20; if (age >= 18) { console.log("Adult"); } else if (age >= 13) { console.log("Teenager"); } else { console.log("Child"); } // Switch Statement: let day = "Monday"; switch (day) { case "Monday": console.log("Start of the week"); break; case "Friday": console.log("End of the week"); break; default: console.log("Mid-week"); } // For Loop: for (let i = 0; i < 5; i++) { console.log(i); } // While Loop: let i = 0; while (i < 5) { console.log(i); i++; } // Do-While Loop: let j = 0; do { console.log(j); j++; } while (j < 5); // For...in Loop (iterate over object properties): let person = { name: "Alice", age: 25 }; for (let key in person) { console.log(key, person[key]); } // For...of Loop (iterate over iterable objects - arrays, strings, etc.): let myArray2 = [10, 20, 30]; for (let value of myArray2) { console.log(value); } // Break & Continue: for (let k = 0; k < 10; k++) { if (k === 3) { break; // Exit loop } if (k === 1) { continue; // Skip to next iteration } console.log(k); } /*********************** * FUNCTIONS ***********************/ // Function Declaration: function greet(name) { return "Hello, " + name + "!"; } // Function Expression: let add = function(a, b) { return a + b; }; // Arrow Function (ES6+): let multiply = (a, b) => a * b; // Concise version let multiply2 = (a, b) => { // Block body return a * b; }; // Default Parameters: function sayHello(name = "Guest") { return "Hello, " + name + "!"; } // Rest Parameters: function sumNumbers(...numbers) { let total = 0; for (let number of numbers) { total += number; } return total; } // Immediately Invoked Function Expression (IIFE): (function() { console.log("IIFE is executed"); })(); /*********************** * OBJECTS ***********************/ // Object Literal: let car = { make: "Toyota", model: "Camry", year: 2023, start: function() { console.log("Engine started"); } }; // Accessing Properties: console.log(car.make); // Dot notation console.log(car["model"]); // Bracket notation // Adding/Modifying Properties: car.color = "Silver"; car.year = 2024; // Deleting Properties: delete car.color; // Object Destructuring (ES6+): let { make, model } = car; // Extracts make and model properties console.log(make, model); // Object.keys(), Object.values(), Object.entries(): let keys = Object.keys(car); // Returns array of keys let values = Object.values(car); // Returns array of values let entries = Object.entries(car); // Returns array of key-value pairs // 'this' Keyword: let dog = { name: "Buddy", bark: function() { console.log("Woof! My name is " + this.name); } }; dog.bark(); /*********************** * ARRAYS ***********************/ // Array Literal: let fruits = ["apple", "banana", "orange"]; // Accessing Elements: console.log(fruits[0]); // Accesses "apple" // Adding/Removing Elements: fruits.push("grape"); // Adds to end fruits.pop(); // Removes from end fruits.unshift("kiwi"); // Adds to beginning fruits.shift(); // Removes from beginning fruits.splice(1, 1, "pear"); // Removes 1 element starting at index 1 and inserts "pear" // Array Length: console.log(fruits.length); // Array Methods: // Concat: let moreFruits = ["mango", "pineapple"]; let allFruits = fruits.concat(moreFruits); // Slice: let slicedFruits = fruits.slice(1, 3); // Creates a new array from index 1 (inclusive) to 3 (exclusive) // Join: let fruitString = fruits.join(", "); // Converts array to string separated by commas // IndexOf: let index = fruits.indexOf("banana"); // Returns index of "banana" or -1 if not found // Includes (ES2016+): let hasApple = fruits.includes("apple"); // Returns true if array contains "apple" // Find, FindIndex (ES6+): let numbers = [10, 20, 30, 40, 50]; let foundNumber = numbers.find(number => number > 25); // Returns first number > 25 let foundIndex = numbers.findIndex(number => number > 25); // Returns index of first number > 25 // Map, Filter, Reduce (ES5+): // Map: Transforms each element in the array. let doubledNumbers = numbers.map(number => number * 2); // Filter: Creates a new array with elements that pass a test. let evenNumbers = numbers.filter(number => number % 2 === 0); // Reduce: Reduces the array to a single value. let sum2 = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); // 0 is the initial value of the accumulator // forEach (ES5+): fruits.forEach(fruit => { console.log("I like " + fruit); }); // Spread Syntax for Arrays (ES6+): let arr1 = [1, 2, 3]; let arr2 = [...arr1, 4, 5]; // Creates a new array with elements of arr1 and 4, 5 /*********************** * STRINGS ***********************/ // String Literal: let message = "Hello World!"; // String Length: console.log(message.length); // Accessing Characters: console.log(message[0]); // Accesses "H" // String Methods: // Concat: let greeting = "Hello"; let name2 = "John"; let fullGreeting = greeting.concat(", ", name2, "!"); // Slice: let slicedMessage = message.slice(0, 5); // Creates a new string from index 0 (inclusive) to 5 (exclusive) // Substring & Substr (Legacy): Avoid using substr, use slice instead let substringMessage = message.substring(0, 5); // Similar to slice but treats negative indexes differently // let substrMessage = message.substr(0, 5); // Deprecated // Replace: let replacedMessage = message.replace("World", "Universe"); // Replaces first occurrence // ToUpperCase & ToLowerCase: let upperCaseMessage = message.toUpperCase(); let lowerCaseMessage = message.toLowerCase(); // Trim: let stringWithWhitespace = " Hello "; let trimmedString = stringWithWhitespace.trim(); // Removes leading/trailing whitespace // Split: let words = message.split(" "); // Splits the string into an array of words separated by spaces // Includes, StartsWith, EndsWith (ES6+): let hasWorld = message.includes("World"); // Returns true if string contains "World" let startsWithHello = message.startsWith("Hello"); // Returns true if string starts with "Hello" let endsWithExclamation = message.endsWith("!"); // Returns true if string ends with "!" // Template Literals (ES6+): let myName = "Jane"; let templateString = `Hello, ${myName}!`; // Allows embedding expressions inside strings /*********************** * DATES ***********************/ // Creating Date Objects: let now = new Date(); // Current date and time let specificDate = new Date(2024, 0, 20); // January 20, 2024 (month is 0-indexed) let dateString = new Date("October 15, 2024"); // Date Methods: let year = now.getFullYear(); let month = now.getMonth(); // 0-indexed (0 = January) let dayOfMonth = now.getDate(); let dayOfWeek = now.getDay(); // 0-indexed (0 = Sunday) let hours = now.getHours(); let minutes = now.getMinutes(); let seconds = now.getSeconds(); // Date Formatting (requires external libraries like Moment.js or date-fns for more complex formatting) console.log(now.toLocaleDateString()); // Locale-specific date string console.log(now.toLocaleTimeString()); // Locale-specific time string console.log(now.toLocaleString()); // Locale-specific date and time string /*********************** * MATH ***********************/ // Math Object: let randomNumber = Math.random(); // Returns a random number between 0 (inclusive) and 1 (exclusive) let roundedNumber = Math.round(3.6); // Rounds to the nearest integer let ceilingNumber = Math.ceil(3.2); // Rounds up to the nearest integer let floorNumber = Math.floor(3.8); // Rounds down to the nearest integer let absoluteValue = Math.abs(-5); // Returns the absolute value let maxNumber = Math.max(10, 5, 20); // Returns the maximum value let minNumber = Math.min(10, 5, 20); // Returns the minimum value let powerOf = Math.pow(2, 3); // Returns 2 raised to the power of 3 let squareRoot = Math.sqrt(25); // Returns the square root let piValue = Math.PI; // Returns the value of Pi /*********************** * ERROR HANDLING ***********************/ // Try...Catch...Finally: try { // Code that might throw an error throw new Error("Something went wrong!"); } catch (error) { // Code to handle the error console.error(error.message); } finally { // Code that always executes, regardless of whether an error occurred console.log("Finally block executed"); } /*********************** * ASYNCHRONOUS JAVASCRIPT ***********************/ // Callbacks: function fetchData(callback) { setTimeout(function() { let data = "Data fetched!"; callback(data); }, 1000); } fetchData(function(result) { console.log(result); }); // Promises (ES6+): let myPromise = new Promise(function(resolve, reject) { setTimeout(function() { let success = true; // Simulate success or failure if (success) { resolve("Data fetched successfully!"); } else { reject("Error fetching data!"); } }, 1000); }); myPromise .then(function(result) { console.log(result); }) .catch(function(error) { console.error(error); }); // Async/Await (ES2017+): async function getData() { try { let result = await myPromise; console.log(result); } catch (error) { console.error(error); } } getData(); // Fetch API (Promises-based API for making HTTP requests): async function fetchUsers() { try { let response = await fetch("https://jsonplaceholder.typicode.com/users"); let users = await response.json(); // Parse JSON response console.log(users); } catch (error) { console.error("Error fetching users:", error); } } fetchUsers(); /*********************** * MODULES ***********************/ // ES Modules (ES6+): (Typically used in browser with bundlers like webpack, or in Node.js) // Export (in module1.js): // export function myFunction() { ... } // export let myVariable = 123; // Import (in module2.js): // import { myFunction, myVariable } from './module1.js'; /*********************** * DOM MANIPULATION (BROWSER ONLY) ***********************/ // Selecting Elements: // document.getElementById("myId"); // By ID // document.querySelector(".myClass"); // By class (first match) // document.querySelectorAll(".myClass"); // By class (all matches - returns a NodeList) // document.getElementsByTagName("p"); // By tag name (returns an HTMLCollection - live updating) // document.getElementsByClassName("myClass"); // By class name (returns an HTMLCollection - live updating) // Modifying Elements: // let element = document.getElementById("myId"); // element.textContent = "New text"; // Sets text content // element.innerHTML = "<p>New <b>HTML</b></p>"; // Sets HTML content // element.setAttribute("class", "newClass"); // Sets attribute // element.style.color = "red"; // Sets inline style // element.classList.add("active"); // Adds a class // element.classList.remove("active"); // Removes a class // element.classList.toggle("active"); // Toggles a class // Creating Elements: // let newElement = document.createElement("div"); // newElement.textContent = "This is a new div"; // document.body.appendChild(newElement); // Adds element to the end of the body // Event Listeners: // element.addEventListener("click", function(event) { // console.log("Clicked!"); // console.log(event.target); // The element that triggered the event // }); // Preventing Default Behavior: // element.addEventListener("submit", function(event) { // event.preventDefault(); // Prevents the default form submission // }); // Event Bubbling and Capturing: (More advanced topics related to event propagation in the DOM)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.