💡 **JavaScript Tip: map() vs filter() vs forEach()** These three array methods look similar but serve different purposes. 🔹 **map()** → Transforms every element and returns a **new array** 🔹 **filter()** → Selects elements that pass a **condition** and returns a **new array** 🔹 **forEach()** → Runs a function for each element but **does not return a new array** 👉 **Quick rule:** Use **map** to transform data, **filter** to select data, and **forEach** to simply loop through data. #JavaScript #WebDevelopment #Frontend #CodingTips
JavaScript Array Methods: map(), filter(), forEach()
More Relevant Posts
-
This pattern is everywhere: useEffect(() => { setLoading(true); fetch('/api/data') .then(r => r.json()) .then(setData) .catch(setError) .finally(() => setLoading(false)); }, []); Problems: ❌ No caching ❌ Race conditions ❌ Manual loading/error state ❌ No background refetch ❌ Stale data on re-focus Use TanStack Query: const { data, isLoading } = useQuery({ queryKey: ['data'], queryFn: fetchData }); All problems solved. Your future self will thank you. #ReactNative #JavaScript #CleanCode #ReactQuery #MobileDev
To view or add a comment, sign in
-
One small pattern I really like in JavaScript/TypeScript: return data.items .slice(offset, offset + limit) .map(({ id, firstName, lastName, companyId }) => ({ id, firstName, lastName, companyId, })); Why this is clean: • slice(offset, offset + limit) → handles pagination in a single, readable step • map(...) → transforms data immediately, returning only what’s needed • Object destructuring → avoids repetitive item.id, item.firstName, etc. • No mutations → everything is predictable and functional It’s concise, readable, and does exactly what it needs — nothing more. Sometimes clean code is just about using the right built-in methods. #JavaScript #TypeScript #CleanCode #javascript #remote
To view or add a comment, sign in
-
Day 85 of me reading random and basic but important dev topicsss..... Today I read about bridging the gap between Binary Data and Text in JavaScript (TextDecoder)..... To translate raw bytes into readable text, standard string manipulation won’t cut it. We need TextDecoder. TextDecoder is a built-in browser and Node.js object that reads a buffer and converts it into an actual JavaScript string based on a specified encoding (UTF-8 by default, but it supports windows-1251, big5, etc.). let uint8Array = new Uint8Array([72, 101, 108, 108, 111]); let decoder = new TextDecoder(); // defaults to utf-8 console.log(decoder.decode(uint8Array)); // "Hello" Some tricks which I read were....... 1. Zero-Copy Subarray Decoding: What if our string is buried inside a larger buffer (e.g. a custom network packet where the first byte is an ID and the string starts at byte 2)? Don’t slice the array! slice() copies memory. Instead, use a subarray to create a new "view" over the same memory block and decode that. let packet = new Uint8Array([0, 72, 101, 108, 108, 111, 0]); let stringView = packet.subarray(1, -1); // No memory copied! console.log(new TextDecoder().decode(stringView)); // "Hello" 2. Handling Streams (stream: true): When receiving data in chunks (like from the Streams API), a multi-byte character (like an emoji or an accented letter) might get split in half across two different network chunks. If we decode them separately, we will get corrupted garbage characters (``). By passing { stream: true } to the .decode() method, the TextDecoder memorizes the "unfinished" bytes and seamlessly combines them with the next chunk. Keep Learning!!!!! #JavaScript #WebDevelopment #Performance #DataStreams #SoftwareEngineering
To view or add a comment, sign in
-
-
⚡ 1-Minute JavaScript Remove duplicate values from an array using a single line. Utility function :- const unique = (arr) => [...new Set(arr)]; Usage :- unique([1, 2, 2, 3, 3, 4]); // [1, 2, 3, 4] 💡 Why this works: Set is a built-in JavaScript data structure that only stores unique values. When you pass an array into a Set, duplicates are automatically removed. Then the spread operator (...) converts it back into an array. 🔎 Practical use cases: 🧹 Cleaning duplicate API data 📊 Preparing datasets for charts 🧾 Removing repeated IDs before processing ⚡ Quick array normalization Small trick. Cleaner data. #JavaScript #FrontendDevelopment #CleanCode #WebDevelopment #DevTips
To view or add a comment, sign in
-
-
🚀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗧𝗶𝗽: 𝗝𝗦𝗢𝗡 vs 𝘀𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲𝗱𝗖𝗹𝗼𝗻𝗲() Most developers copy objects like this 👇 const copy = JSON.parse(JSON.stringify(obj)); 👉 Works… but only for simple data ❌ Removes undefined ❌ Converts Date → string ❌ Removes functions ❌ Breaks for Map, Set, circular refs ✅ 𝗠𝗼𝗱𝗲𝗿𝗻 𝘄𝗮𝘆: const copy = structuredClone(obj); ✔️ Real deep clone ✔️ Keeps Date, Map, Set ✔️ Handles circular references ✔️ Clean & safe 💡 𝗥𝘂𝗹𝗲 𝗼𝗳 𝘁𝗵𝘂𝗺𝗯: Use structuredClone() in modern apps Use JSON method only for basic data #JavaScript #Frontend #WebDevelopment #CodingTips 🚀
To view or add a comment, sign in
-
Today I learned about the useRef Hook in React and how to use localStorage to manage data in the browser. ** useRef Hook The useRef hook is used to create a reference that persists across renders. It is commonly used to directly access DOM elements or store values without causing re-renders. Example: import { useRef } from "react"; function InputFocus() { const inputRef = useRef(null); const handleClick = () => { inputRef.current.focus(); }; return ( <> <input ref={inputRef} /> <button onClick={handleClick}>Focus Input</button> </> ); } ** localStorage in JavaScript localStorage allows us to store data in the browser so that it remains even after refreshing the page. • setItem() – Store data • getItem() – Retrieve data • update – Modify existing data • removeItem() – Delete data Example: localStorage.setItem("name", "Avesh"); const data = localStorage.getItem("name"); localStorage.removeItem("name"); @Sheryians Coding School @Sarthak Sharma @Daneshwar Verma @Devendra Dhote @Ritik Rajput #ReactJS #JavaScript #FullStackDeveloper #WebDevelopment #CodingJourney
To view or add a comment, sign in
-
Day 3 of My JavaScript Journey Today, I learned about JavaScript data types and how to define variables. JavaScript has two main types of data: Primitive data types: These include 7 types such as number, string, boolean, null, undefined, symbol, and bigint. Object: used to store more complex data. I also learned three ways to declare variables in JavaScript: • let • const • var One key thing I understood: "const" should be used by default, "let" when the value needs to change, and "var" is mostly outdated. Example: const name = "John"; let age = 20; Key takeaway: Understanding data types and variable declarations is fundamental to writing clean and predictable JavaScript code. #JavaScript #WebDevelopment #LearningInPublic #100DaysOfCode
To view or add a comment, sign in
-
#js #7 **Function Declaration vs Function Expression in JavaScript** 🔹 Function Declaration Definition: A function declaration defines a named function using the function keyword. function greet() { console.log("Hello"); } ✅ Features: Must have a name Hoisted (can be called before it is defined) Declared as a separate statement Example (Hoisting): greet(); // works function greet() { console.log("Hello"); } 🔹 Function Expression Definition: A function expression is when a function is assigned to a variable. const greet = function () { console.log("Hello"); }; ✅ Features: Can be anonymous (no name) Not hoisted (cannot be used before definition) Treated like a value Example: greet(); // ❌ Error const greet = function () { console.log("Hello"); } #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
𝐈𝐬 𝐲𝐨𝐮𝐫 `𝐮𝐬𝐞𝐄𝐟𝐟𝐞𝐜𝐭` 𝐟𝐢𝐫𝐢𝐧𝐠 𝐰𝐚𝐲 𝐭𝐨𝐨 𝐨𝐟𝐭𝐞𝐧? 𝐘𝐨𝐮 𝐦𝐢𝐠𝐡𝐭 𝐛𝐞 𝐟𝐚𝐥𝐥𝐢𝐧𝐠 𝐟𝐨𝐫 𝐚 𝐜𝐨𝐦𝐦𝐨𝐧 𝐝𝐞𝐩𝐞𝐧𝐝𝐞𝐧𝐜𝐲 𝐚𝐫𝐫𝐚𝐲 𝐭𝐫𝐚𝐩. We've all been there: you put an object or array into your `useEffect`'s dependency array, thinking it's stable. But because JavaScript compares objects and arrays by reference, even if their content is identical, `useEffect` sees a new object on every render and re-runs your effect. This can lead to performance hits, stale data, or even infinite loops. 🚫 The Problem: ```javascript function MyComponent({ data }) { const options = { id: data.id, filter: 'active' }; useEffect(() => { // This runs every render if 'options' object is new fetchData(options); }, [options]); // 'options' is a new object reference each time // ... } ``` ✅ The Fix: Stabilize with `useMemo` If your object or array doesn't logically change across renders (or only changes based on specific primitives), wrap it in `useMemo`. This memoizes the object itself, ensuring its reference remains the same unless its dependencies actually change. ```javascript function MyComponent({ data }) { const stableOptions = useMemo(() => ({ id: data.id, filter: 'active' }), [data.id]); // Only re-create if data.id changes useEffect(() => { fetchData(stableOptions); }, [stableOptions]); // Now only re-runs if stableOptions' reference changes // ... } ``` This trick is a lifesaver for optimizing `useEffect` calls, especially when dealing with complex configurations or filtering logic passed down as props. It keeps your effects clean and your app performant. What's been your biggest `useEffect` headache, and how did you solve it? #React #FrontendDevelopment #JavaScript #Performance #WebDev
To view or add a comment, sign in
-
→ Most React devs make this mistake in forms… They create a new state for every input ❌ After building dashboards, multi-step forms, and filter panels — here’s the pattern that actually scales 👇 → Treat your form as data, not markup 💡 Define fields as config: const fields = [ { name: "email", label: "Email", type: "email", required: true }, { name: "role", label: "Role", type: "select", options: ["Admin", "User"] }, ]; → One state. One handler. const [formData, setFormData] = useState({}); const [errors, setErrors] = useState({}); const handleChange = (e) => { const { name, value } = e.target; setFormData(prev => ({ ...prev, [name]: value })); }; ⚡ Validation that scales: const validate = (name, value) => { const field = fields.find(f => f.name === name); if (field.required && !value) { setErrors(prev => ({ ...prev, [name]: `${field.label} is required` })); } }; → Why this works: → Add a field = 1 line change → No extra handlers → Works for 3 or 30 fields 🧠 Mental shift: → Stop thinking in inputs. Start thinking in schema. #ReactJS #Frontend #JavaScript #CleanCode #WebDevelopment
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