🌟 10 Useful JavaScript Snippets You Might Not Know Quick, practical JS helpers that can save time and clean up your code! 💡 --- 1️⃣ Randomize an array (Fisher-Yates shuffle) ```javascript const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5); console.log(shuffleArray([1, 2, 3, 4, 5])); ``` 2️⃣ Flatten nested arrays ```javascript const flatten = (arr) => [].concat(...arr); console.log(flatten([1, [2, 3], [4, [5]]])); ``` 3️⃣ Check if an object is empty ```javascript const isEmpty = (obj) => Object.keys(obj).length === 0; console.log(isEmpty({})); // true ``` 4️⃣ Remove duplicates from an array ```javascript const unique = (arr) => [...new Set(arr)]; console.log(unique([1, 2, 2, 3, 3, 4])); ``` 5️⃣ Get current date in YYYY-MM-DD format ```javascript const today = () => new Date().toISOString().slice(0, 10); console.log(today()); ``` 6️⃣ Capitalize the first letter of a string ```javascript const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1); console.log(capitalize("hello world")); ``` 7️⃣ Convert RGB to Hex ```javascript const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); console.log(rgbToHex(255, 100, 50)); ``` 8️⃣ Wait/delay function ```javascript const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms)); await delay(2000); // waits 2 seconds ``` 9️⃣ Copy text to clipboard ```javascript const copyToClipboard = (text) => navigator.clipboard.writeText(text); copyToClipboard("Hello, devs! 👨💻"); ``` 🔟 Extract parameters from URL ```javascript const getParams = (url) => Object.fromEntries(new URL(url).searchParams); console.log(getParams('https://lnkd.in/g3Y-T5jw')); ``` --- 📌 Which snippet did you find most useful? Have a better version? Share below! 👇 --- 📌 Follow Sasikumar S for more hands-on developer content ❤️ Join skAI – Daily Developer Learning Community for daily tips, growth hacks & career opportunities 💌 Repost to help others in your network 🤝 Connect: sasiias2024@gmail.com 💟 Explore more: sk-techland.web.app #JavaScript #WebDevelopment #CodingTips #JS #DeveloperTools #Programming #CodeSnippets #TechTips #Frontend #LearnToCode
10 Useful JavaScript Snippets for Web Development
More Relevant Posts
-
🚀 20 JavaScript Snippets Tiny code, big impact. Bookmark this for your next project! 🔖 1. Flatten an array ```javascript const flatten = arr => arr.flat(Infinity); ``` 2. Check if object is empty ```javascript const isEmpty = obj => Object.keys(obj).length === 0; ``` 3. Generate random hex color ```javascript const randomHex = () => `#${Math.floor(Math.random()*0xffffff).toString(16).padEnd(6,"0")}`; ``` 4. Remove duplicates from array ```javascript const unique = arr => [...new Set(arr)]; ``` 5. Capitalize first letter ```javascript const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1); ``` 6. Copy to clipboard ```javascript const copyToClipboard = text => navigator.clipboard.writeText(text); ``` 7. Get current URL params ```javascript const params = new URLSearchParams(window.location.search); ``` 8. Detect dark mode preference ```javascript const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches; ``` 9. Debounce function ```javascript const debounce = (func, wait) => { let timeout; return (...args) => { clearTimeout(timeout); timeout = setTimeout(() => func.apply(this, args), wait); }; }; ``` 10. Wait for a set time ```javascript const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); ``` 11. Toggle boolean in state (React-friendly) ```javascript const toggle = prev => !prev; ``` 12. Sort by key ```javascript const sortBy = (arr, key) => arr.sort((a, b) => a[key] > b[key] ? 1 : -1); ``` 13. Convert RGB to hex ```javascript const rgbToHex = (r,g,b) => "#" + ((1<<24) + (r<<16) + (g<<8) + b).toString(16).slice(1); ``` 14. Validate email ```javascript const isValidEmail = email => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); ``` 15. Group array by property ```javascript const groupBy = (arr, key) => arr.reduce((acc, obj) => { acc[obj[key]] = (acc[obj[key]] || []).concat(obj); return acc; }, {}); ``` 16. Get average of array ```javascript const average = arr => arr.reduce((a, b) => a + b, 0) / arr.length; ``` 17. Random item from array ```javascript const randomItem = arr => arr[Math.floor(Math.random() * arr.length)]; ``` 18. Scroll to top smoothly ```javascript const scrollToTop = () => window.scrollTo({ top: 0, behavior: 'smooth' }); ``` 19. Format number with commas ```javascript const formatNumber = num => num.toLocaleString(); ``` 20. Check if array includes all values ```javascript const includesAll = (arr, values) => values.every(v => arr.includes(v)); ``` --- ✨ Which one will you use first? 💬 Comment your favorite snippet or share one of your own! #JavaScript #WebDevelopment #CodingTips #Programming #Frontend #DeveloperTools #CodeSnippets #JS #TechTips #LearnJavaScript #SoftwareEngineering #DevCommunity 📌 Follow Sasikumar S for daily practical developer tips & hands-on learning. ❤️ Join TechVerse Collective – a daily learning community for coders growing together. 🔁 Repost to save for later & share with your network.
To view or add a comment, sign in
-
Demystifying JavaScript Functions: The Complete Beginner's Guide 🧠 As a developer, understanding functions is like learning to walk in JavaScript—it's fundamental to everything you'll build. Let me break down every type of function in the simplest way possible! 1️⃣ Function Declaration (The Classic) The most basic way to define a function. Gets "hoisted" so you can call it before declaring it. ```javascript function greet(name) { return `Hello, ${name}!`; } console.log(greet('Sasi')); // Hello, Sasi! ``` 2️⃣ Function Expression (The Flexible) Assigning a function to a variable. More flexible but not hoisted. ```javascript const greet = function(name) { return `Hello, ${name}!`; }; ``` 3️⃣ Arrow Function (The Modern) ES6's concise syntax. Perfect for callbacks and one-liners! ```javascript const greet = (name) => `Hello, ${name}!`; // Single parameter? No parentheses needed! const square = x => x * x; ``` 4️⃣ IIFE (Immediately Invoked) Runs immediately after definition. Great for isolated scopes. ```javascript (function() { console.log('I run immediately!'); })(); ``` 5️⃣ Higher-Order Functions (The Smart Ones) Functions that take other functions as arguments or return them. ```javascript // map() is a higher-order function const numbers = [1, 2, 3]; const doubled = numbers.map(x => x * 2); ``` 6️⃣ Generator Functions (The Pausable) Can pause execution and resume later. Use function* and yield. ```javascript function* countUp() { let count = 0; while (true) { yield count++; } } ``` 7️⃣ Async Functions (The Patient) Simplify working with promises using async/await. ```javascript async function fetchData() { const response = await fetch('url'); const data = await response.json(); return data; } ``` 🔄 Function Types Quick Guide: · Regular functions: Your all-purpose workhorse · Arrow functions: Short, clean, no this binding · Async functions: Handle promises elegantly · Generator functions: Control execution flow · IIFEs: Run once, protect scope · Higher-order: Treat functions as data 🎯 When to Use What: · Need this binding? → Regular functions · Writing callbacks? → Arrow functions · Working with APIs? → Async functions · Need reusable logic? → Function expressions · Want clean, modern code? → Arrow functions 💡 Pro Tip: Arrow functions don't have their own this context—they inherit it from the parent scope. Regular functions do have their own this. --- Let's Discuss! 👇 · Which function type do you use most often? · What's your favorite "aha!" moment with JavaScript functions? 🔥 Want more practical insights like this? ✅ Follow Sasikumar S for daily JavaScript tips ✅ Like & Repost to help other developers ✅ Comment your function questions below! #JavaScript #WebDevelopment #Programming #Coding #Frontend #Developer #WebDev #Tech #SoftwareEngineering #LearnToCode #ProgrammingTips #CodeNewbie #JavaScriptTips #Functions #ES6 #AsyncJavaScript
To view or add a comment, sign in
-
"JavaScript is single-threaded" We don't call C++ or Go "single-threaded" — yet they execute in one thread by default too. Creating parallel threads requires explicit code in any language. So why do we label JavaScript this way? -- HISTORICAL CONTEXT -- In the 2000s, browsers themselves were single-process. One frozen tab = entire browser frozen. Chrome (2008) pioneered multi-process architecture. Firefox followed with Electrolysis only in 2016. The "JS is single-threaded" myth was born in that era — and stuck. -- MODERN JAVASCRIPT -- Today, JavaScript has full parallelism capabilities. Let's look at the tools. -- WEB WORKERS -- Separate threads with their own event loop. True parallel execution. const worker = new Worker('heavy-task.js'); worker.postMessage(data); worker.onmessage = (e) => console.log(e.data); Limitation: no DOM access, communication via postMessage (structured clone). -- SHARED MEMORY -- SharedArrayBuffer + Atomics enable lock-free concurrent programming: // Main thread const sab = new SharedArrayBuffer(1024); const view = new Int32Array(sab); worker.postMessage(sab); // Worker Atomics.add(view, 0, 1); // atomic increment Atomics.wait(view, 0, expectedValue); // block until changed Same memory model as C++/Rust. Race conditions included. -- WORKLETS -- Lightweight threads for specific tasks: • AudioWorklet — real-time audio processing • PaintWorklet — custom CSS painting • AnimationWorklet — off-main-thread animations -- NODE.JS -- Node.js is multithreaded out of the box. libuv thread pool: 4 threads by default (UV_THREADPOOL_SIZE, max 1024). Handles: file system, DNS, crypto. For custom parallelism: worker_threads. For multiprocessing: child_process, cluster. -- THE REAL CONSTRAINT -- DOM access is single-threaded. Not JavaScript itself. The event loop is scheduling, not a threading limitation. V8 runs on multiple threads — it just gives you one main thread by default. Same story as C++ or Go: one thread by default, explicit code for parallelism. #JavaScript #WebWorkers #NodeJS #Concurrency #Performance
To view or add a comment, sign in
-
-
JavaScript Arrays, Objects & Array Methods Understanding how arrays and objects work helps you organize, transform, and analyze data in JavaScript. Here's a quick and clear breakdown: *1️⃣ Arrays in JavaScript* An array stores a list of values. ```js let fruits = ["apple", "banana", "mango"]; console.log(fruits[1]); // banana ``` ▶️ This creates an array of fruits and prints the second fruit (`banana`), since arrays start at index 0. *2️⃣ Objects in JavaScript* Objects hold key–value pairs. ```js let user = { name: "Riya", age: 25, isAdmin: false }; console.log(user.name); // Riya console.log(user["age"]); // 25 ``` ▶️ This object represents a user. You can access values using dot (`.`) or bracket (`[]`) notation. *3️⃣ Array Methods – map, filter, reduce* 🔹 *map()* – Creates a new array by applying a function to each item ```js let nums = [1, 2, 3]; let doubled = nums.map(n => n * 2); console.log(doubled); // [2, 4, 6] ``` ▶️ This multiplies each number by 2 and returns a new array. 🔹 *filter()* – Returns a new array with items that match a condition ```js let ages = [18, 22, 15, 30]; let adults = ages.filter(age => age >= 18); console.log(adults); // [18, 22, 30] ``` ▶️ This filters out all ages below 18. 🔹 *reduce()* – Reduces the array to a single value ```js let prices = [100, 200, 300]; let total = prices.reduce((acc, price) => acc + price, 0); console.log(total); // 600 ``` ▶️ This adds all prices together to get the total sum. *💡 Extra Notes:* • `map()` → transforms items • `filter()` → keeps matching items • `reduce()` → combines all items into one result 🎯 *Practice Challenge:* • Create an array of numbers • Use `map()` to square each number • Use `filter()` to keep only even squares • Use `reduce()` to add them all up
To view or add a comment, sign in
-
🧠 JavaScript – Operators & Conditional Statements Making Decisions Using Code In real applications, programs don’t just run line by line they think, compare, and decide what to do next. This is where operators and conditional statements become essential. 🔹 Operators in JavaScript Operators are used to perform actions on values. ➕ Arithmetic Operators Used for calculations. let a = 10; let b = 5; a + b; // 15 a - b; // 5 a * b; // 50 a / b; // 2 a % b; // 0 Used in: Calculations Scores Prices Counters 🔍 Comparison Operators Used to compare values. 10 == "10"; // true 10 === "10"; // false 10 > 5; // true == → compares value === → compares value and type (recommended) 👉 Always prefer === in modern JavaScript. 🔗 Logical Operators Used to combine conditions. true && false; // false true || false; // true !true; // false Used for: Login checks Multiple conditions Access control 🔹 Conditional Statements Conditional statements help JavaScript choose different paths based on conditions. ✅ if – else let age = 20; if (age >= 18) { console.log("Eligible to vote"); } else { console.log("Not eligible"); } Used for: Validations Permissions User actions 🔁 else if (Multiple Conditions) let marks = 75; if (marks >= 90) { console.log("Excellent"); } else if (marks >= 60) { console.log("Good"); } else { console.log("Needs improvement"); } 🔀 switch Statement Best when checking one value against many cases. let role = "admin"; switch (role) { case "admin": console.log("Full access"); break; case "user": console.log("Limited access"); break; default: console.log("Guest access"); } Used in: Menu options User roles Status handling 🧠 Simple Way to Think Operators → compare values Conditions → make decisions Code → behaves differently based on input This is how JavaScript becomes smart. ✅ Key Takeaway If you understand: ✔ Operators ✔ if–else logic ✔ switch cases You can control how your program behaves — a core skill in web development. . . #JavaScript #WebDevelopment #ProgrammingBasics #LearningInPublic #FrontendDevelopment #FullStackJourney
To view or add a comment, sign in
-
-
Here's the thing: JavaScript developers are stuck in a naming crisis. It's crazy: you start typing `useQ` and your IDE just gets lost. So, what's going on? Well, it turns out there are a ton of libraries using the same hook names - and it's causing chaos. You've got `useQuery` from `@apollo/client` for GraphQL queries, `useQuery` from `urql` for more GraphQL queries, `useQuery` from `@tanstack/react-query` for REST/HTTP queries... and the list goes on. There's `useQuery` from `react-relay`, `graphql-hooks`, `@supabase/react`, `react-firebase-hooks`, `@algolia/react-hooks`, and `swr` - all doing different things. It's like, the wordquery has lost all meaning. You can use `useQuery` for a GraphQL query, like this: `const { data } = useQuery(gql`query GetUser($id: ID!) { user(id: $id) { name, email } }``)`. Or, you can use it for a REST API query: `const { data } = useQuery(['user', id], () => fetch(`/api/users/${id}`))`. And then there's database queries, search queries... it's all just a mess. This isn't just a problem with `useQuery`, by the way - it affects all sorts of hooks: authentication, client/connection, store/state, subscription... So, what can libraries do to fix this? First, they should prefix their names with some kind of library identity. Second, they should be specific about what kind of query they're doing. And third, they should try to maintain some consistency across their hooks. As for us developers, we can help by sharing this article with library authors, opening issues on the libraries we use, and tweeting about our own import alias hell with #JSNamingCrisis. We can also vote with our feet, so to speak - by supporting libraries that actually care about our experience. Check out the full article here: https://lnkd.in/gJhfjHN5 #JSNamingCrisis #JavaScript #DeveloperExperience
To view or add a comment, sign in
-
🔍 JavaScript Objects: Dot Notation vs Bracket Notation Why do we have two ways to access object properties — and when should we use each? If both dot notation and bracket notation do the same thing, why does JavaScript even support both? The short answer: flexibility + real-world use cases. Let’s break it down 👇 ⸻——————————————————- 1️⃣ Dot Notation – Clean, readable, and predictable const user = { name: "Jagdish", role: "Frontend Developer" }; user.name; // "Jagdish" ——————————————- ✅ When to use dot notation • Property names are known at development time • Keys are valid JavaScript identifiers • You want clean & readable code 🚫 When you can’t use dot notation user.first-name ❌ // Error user["first-name"] ✅ Why? Dot notation does not support: • Spaces • Hyphens (-) • Dynamic values —————————————————— 2️⃣ Bracket Notation – Dynamic and powerful const key = "role"; user[key]; // "Frontend Developer" ✅ When to use bracket notation • Property name is dynamic • Key comes from user input, API response, or loop • Property contains special characters ———————————— const data = { "total-users": 120, "2025": "Active" }; data["total-users"]; // 120 data["2025"]; // "Active" —————————————- Dot notation fails here ❌ Bracket notation works perfectly ✅ _______________________________ 3️⃣ Real-world examples 🔹 API responses response.data[fieldName]; You don’t know the key beforehand → bracket notation is required. 🔹 Forms & dynamic filters filters[selectedFilter]; 🔹 Looping through objects for (let key in user) { console.log(user[key]); } Dot notation simply cannot work here. ——————————————————————- 4️⃣ Mental model to remember forever 🧠 • Dot notation → Static & known • Bracket notation → Dynamic & unknown If JavaScript needs to evaluate the key at runtime, you must use bracket notation. JavaScript didn’t give us two notations by accident. It gave us simplicity and power. Knowing why and when to use each is what separates 👉 someone who knows syntax from 👉 someone who understands JavaScript deeply. If this helped you, react or share — someone in your network needs this today 🚀 #JavaScript #FrontendDevelopment #WebDevelopment #JavaScriptTips #CodingBestPractices #LearnJavaScript #SoftwareEngineering #CleanCode #DeveloperCommunity #ProgrammingConcepts #TechCareers #ReactJS #WebDev
To view or add a comment, sign in
-
-
✅ *Advanced JavaScript Part-1: ES6+ Features (Arrow Functions, Destructuring & Spread/Rest)* 🧠💻 Mastering these ES6 features will make your code cleaner, shorter, and more powerful. Let’s break them down: *1️⃣ Arrow Functions* Arrow functions are a shorter way to write function expressions. 🔹 Syntax: ```js const add = (a, b) => a + b; ``` 🔹 Key Points: • No need for `function` keyword • If one expression, return is implicit • `this` is *not* rebound — it uses the parent scope’s `this` 🧪 Example: ```js // Regular function function greet(name) { return "Hello, " + name; } // Arrow version const greet = name => `Hello, name`; console.log(greet("Riya")); // Hello, Riya ``` *2️⃣ Destructuring* Destructuring lets you extract values from arrays or objects into variables. 🔹 Object Destructuring: ```js const user = name: "Aman", age: 25 ; const name, age = user; console.log(name); // Aman ``` 🔹 Array Destructuring: ```js const numbers = [10, 20, 30]; const [a, b] = numbers; console.log(a); // 10 ``` 🧠 Real Use: ```js function displayUser( name, age ) console.log(`{name} is ${age} years old.`); } displayUser({ name: "Tara", age: 22 }); ``` *3️⃣ Spread & Rest Operators (`...`)* ✅ Spread – Expands elements from an array or object ```js const arr1 = [1, 2]; const arr2 = [...arr1, 3, 4]; console.log(arr2); // [1, 2, 3, 4] ``` 🔹 Copying objects: ```js const obj1 = { a: 1, b: 2 }; const obj2 = { ...obj1, c: 3 }; console.log(obj2); // { a: 1, b: 2, c: 3 } ``` ✅ Rest – Collects remaining elements into an array 🔹 In function parameters: ```js function sum(...nums) { return nums.reduce((total, n) => total + n, 0); } console.log(sum(1, 2, 3)); // 6 ``` 🔹 In destructuring: ```js const [first, ...rest] = [10, 20, 30]; console.log(rest); // [20, 30] ``` 🎯 *Practice Tips:* • Convert a `function` to an arrow function • Use destructuring in function arguments • Merge arrays or objects using spread • Write a function using rest to handle any number of inputs 💬 *Tap ❤️ for more!*
To view or add a comment, sign in
-
𝗘𝗿𝗿𝗼𝗿 𝗣𝗿𝗼𝗽𝗮𝗴𝗮𝘁𝗶𝗼𝗻 𝗪𝗶𝗍𝗵 𝗖𝗨𝗦𝗧𝗢𝗠 𝗘𝗿𝗿𝗼𝗿 𝗧𝗬𝗣𝗘𝗦 Error handling is a key part of JavaScript development. You need to handle errors well to avoid problems in your applications. Here are some ways to handle errors: - Create custom error classes to give more information about errors - Use try/catch blocks to catch and handle errors - Handle errors in asynchronous code with async/await or promise chains You can create a custom error class like this: ```javascript class CustomError extends Error { constructor(message, code) { super(message); this.name = this.constructor.name; this.code = code; Error.captureStackTrace(this, this.constructor); } } ``` You can use this class to throw errors with more information: ```javascript function riskyFunction() { throw new CustomError("Something went wrong!", 500); } ``` You can also add more properties to your custom error class: ```javascript class DetailedError extends Error { constructor(message, code, details) { super(message); this.name = this.constructor.name; this.code = code; this.details = details; Error.captureStackTrace(this, this.constructor); } } ``` When working with promises, you need to handle errors in the promise chain: ```javascript class NetworkError extends CustomError { constructor(message, endpoint) { super(message, 503); this.endpoint = endpoint; } } function fetchData(url) { return fetch(url).then(response => { if (!response.ok) { throw new NetworkError(`Failed to fetch data from ${url}`, url); } return response.json(); }); } ``` In React, you can use error boundaries to catch and handle errors: ```javascript class ReactErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, info) { console.error("Caught an error:", error); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } } ``` Some things to keep in mind: - Creating error objects can impact performance - You should log or capture necessary details from the original error when re-throwing - Use async/await or promise chains to handle asynchronous errors For more information, you can check out these resources: Source: https://lnkd.in/dQzv3DkF
To view or add a comment, sign in
-
✅ Advanced JavaScript: ES6+ Concepts 💡🧠 Mastering modern JavaScript is key to writing cleaner, faster, and more efficient code. Here's a breakdown of essential ES6+ features with examples. 1️⃣ let & const (Block Scope) let and const replace var . • let = reassignable • const = constant (can't reassign) javascript let score = 90; const name = "Alice"; ▶️ Use const by default. Switch to let if the value changes. 2️⃣ Arrow Functions (=>) Shorter syntax for functions. javascript const add = (a, b) => a + b; ▶️ No this binding – useful in callbacks. 3️⃣ Template Literals Use backticks (`` ` ``) for multiline strings and variable interpolation. javascript const user = "John"; console.log(`Hello, user¡); 4️⃣ Destructuring Extract values from objects or arrays. javascript const person = name: "Sam", age: 30 ; const name, age = person; 5️⃣ Spread and Rest Operators ( ... ) • Spread – expand arrays/objects • Rest – collect arguments javascript const nums = [1, 2, 3]; const newNums = [...nums, 4]; function sum(...args) return args.reduce((a, b) => a + b); 6️⃣ Default Parameters javascript function greet(name = "Guest") return `Hello,{name}`; } 7️⃣ for...of Loop Loop over iterable items like arrays. javascript for (let fruit of ["apple", "banana"]) { console.log(fruit); } 8️⃣ Promises (Basics) javascript const fetchData = () => { return new Promise((resolve, reject) => { setTimeout(() => resolve("Done"), 1000); }); }; Mini Practice Task: ✅ Convert a regular function to arrow syntax ✅ Use destructuring to get properties from an object ✅ Create a promise that resolves after 2 seconds
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development