# Software Side Hustles > Software Side Hustles is an independent educational guide for developers exploring remote AI training and code-evaluation work. It provides sourced platform guides, original practice exercises, a background questionnaire and optional paid tutoring, plus tested cross-language programming guides covering everyday coding tasks, error-message fixes, debugging and core software engineering concepts. It is not a hiring platform and does not guarantee acceptance, work or earnings. Provider facts retain their original verification dates. Published rates are not earnings guarantees. Paid education is optional. AI assistants can connect to our Model Context Protocol server at https://softwaresidehustles.com/mcp (Streamable HTTP, no sign-in) to run the opportunity-fit questionnaire with a user, compare platforms, fetch guides and offer free code-evaluation practice. ## Start here ### Software Side Hustles https://softwaresidehustles.com/ Software Side Hustles is an independent educational guide for developers exploring remote AI training and code-evaluation work. It provides sourced platform guides, original practice exercises, a background questionnaire and optional paid tutoring, plus tested cross-language programming guides covering everyday coding tasks, error-message fixes, debugging and core software engineering concepts. It is not a hiring platform and does not guarantee acceptance, work or earnings. Independent guide. Not affiliated with or endorsed by any AI training platform. Some links may be referral links. Earnings vary and are not guaranteed. --- ### How AI training work works https://softwaresidehustles.com/how-it-works Technical AI training is work in which developers evaluate AI-generated code and responses, compare implementations and explain their decisions. ### 1. Understand the work See how developers review AI-generated code, compare solutions and explain their decisions. Start with the guides before choosing a platform. ### 2. Build your shortlist Use the questionnaire to compare your background and location with published requirements. Read each provider’s guide and check current eligibility. ### 3. Practise the core skills Try original code-comparison and code-review exercises. Learn to test edge cases and write specific, evidence-based feedback before applying. ### 4. Apply on the provider’s site Follow the provider’s application and complete any assessment independently. Review times vary; acceptance and access to projects are never guaranteed. ### 5. Learn the project’s guidelines If accepted and offered work, complete onboarding and read the task rubric. Use optional tutoring for general code-reading and reasoning skills, with original or public examples. ### 6. Build a feedback habit Reflect on the skills you need to strengthen, practise between projects and track your time. Optional tutoring can help refine your explanations without sharing confidential work. This is a typical sequence, not a promised schedule. Each platform controls its assessments, acceptance, rates and project availability. Tutoring is optional and never includes live assessment answers or confidential client tasks. --- ### Opportunity questionnaire https://softwaresidehustles.com/get-started The questionnaire compares your experience, skills and location with published platform requirements. Its recommendations are guidance, not confirmation of eligibility or acceptance. Each provider makes its own application decisions. AI assistants can run the same questionnaire conversationally through the site's MCP server at https://softwaresidehustles.com/mcp (tools: get_questionnaire, then get_recommendations). --- ## Platforms ### AI training platforms https://softwaresidehustles.com/opportunities ### DataAnnotation DataAnnotation offers remote contract work training AI models. Its coding roles involve working with frontier models on real tasks, analysing AI-written code against production standards and red-teaming models to expose broken or unsafe code. Applicants choose a qualification track and take a starter assessment. [Full guide](https://softwaresidehustles.com/opportunities/dataannotation) ### Alignerr Alignerr connects experts with paid AI training work, including a coding category. You apply to individual job listings, each showing its requirements and pay. Some projects add an AI interview or a domain-specific assessment, and accepted contributors complete identity verification. [Full guide](https://softwaresidehustles.com/opportunities/alignerr) ### Mercor Mercor connects professionals with AI companies for human evaluation, data and benchmark work, including software engineering benchmarks. You apply to specific listings; the process can include an AI interview, assessments and identity verification, and pay is set per contract. [Full guide](https://softwaresidehustles.com/opportunities/mercor) ### micro1 micro1 runs an expert network for AI training work. You apply to an opportunity, complete an AI-led interview, and, once certified, may be invited to AI training projects that match your verified skills across domains such as engineering, finance, healthcare, legal and more. Certification does not guarantee placement, and pay is set per opportunity. [Full guide](https://softwaresidehustles.com/opportunities/micro1) --- ### DataAnnotation: developer guide https://softwaresidehustles.com/opportunities/dataannotation DataAnnotation offers remote contract work training AI models. Its coding roles involve working with frontier models on real tasks, analysing AI-written code against production standards and red-teaming models to expose broken or unsafe code. Applicants choose a qualification track and take a starter assessment. Sources last checked: 2026-10-12. ## What the work involves DataAnnotation describes its work as tasks that help AI perform better: reviewing responses, checking accuracy, refining prompts and rating outputs. Its **Software Engineer** listing is specific to coding: - working with frontier models on real tasks; - analysing the AI's work against production standards; - red-teaming models to expose unsafe code, faked test passes and confidently wrong solutions. The job board also lists Frontend, Backend, DevOps and Full Stack engineering roles. ## Who it is aimed at For coding roles, the listing asks for: - professional or serious open-source experience shipping production code; - comfort in at least one major stack — it states most tasks use Python, C++, Rust, Go or JavaScript; - clear written English, because "your explanations are the training signal". The listing states that **no degree is required** for this role. The general FAQ describes a baseline of a bachelor's degree *or equivalent real-world experience* for generalist work, and requires all workers to have reliable internet access and be fluent in English. ## How applying works According to the FAQ, you choose a qualification track at sign-up by selecting a **Starter Assessment**. The FAQ states: - you can only take the Starter Assessment **once**; - most assessments take about an hour, and specialised ones may take one to two hours. Because there is only one attempt, it is worth reading the instructions carefully and making sure you have uninterrupted time before you start. ## Pay and schedule The job board lists coding roles at "up to $40–$150+/hr depending on task difficulty and specialization" (as published when we checked on 12 October 2026). These are the provider's own published figures, not a promise: the FAQ states that work availability depends on demand for your skills and your past performance. The FAQ also states that payments are sent via PayPal and that there are no minimum hours. ## Location The public FAQ does not list eligible countries. If location matters for you, confirm with DataAnnotation before investing time in the assessment. ## Our independence SoftwareSideHustles.com is not affiliated with or endorsed by DataAnnotation. DataAnnotation alone decides who is accepted and which projects are offered. ### Published requirements - Fluent written English is required (all workers). (sourced) [Source](https://www.dataannotation.tech/faqs) - Coding roles ask for professional or serious open-source experience shipping production code. (sourced) [Source](https://www.dataannotation.tech/job-board/software-engineer) - The Starter Assessment can only be taken once. (sourced) [Source](https://www.dataannotation.tech/faqs) ### Sources - [DataAnnotation — homepage](https://www.dataannotation.tech/) - [DataAnnotation — FAQs](https://www.dataannotation.tech/faqs) - [DataAnnotation — Software Engineer role](https://www.dataannotation.tech/job-board/software-engineer) --- ### Alignerr: developer guide https://softwaresidehustles.com/opportunities/alignerr Alignerr connects experts with paid AI training work, including a coding category. You apply to individual job listings, each showing its requirements and pay. Some projects add an AI interview or a domain-specific assessment, and accepted contributors complete identity verification. Sources last checked: 2026-10-12. ## What the work involves Alignerr describes itself as a place "where experts get paid to train AI" and is branded **powered by Labelbox**. Its homepage lists work such as evaluating AI answers and search results, reviewing AI for ethics and writing domain-specific tasks, and it has a **Coding** category of listings. ## How applying works Alignerr's process page describes these steps: 1. **Sign up** with Google, upload your résumé and correct the auto-filled details — the page specifically asks you to check your location. 2. **Apply** to individual job listings. Each listing shows its requirements and pay. 3. **Verify your identity**: phone verification by text, then ID verification through Persona. 4. **Contract and billing setup** through Stripe Connect or PayPal, depending on your location. 5. **Onboarding**: learn the Labelbox platform and join the community. The page notes that some projects may require a **Zara AI interview** or a **domain-specific assessment**, depending on the project you are matched with. ## Pay and schedule Pay is shown on each job listing and varies by role. Work is described as remote and flexible. Like every platform here, project availability is not guaranteed. ## Location Alignerr's public pages do not list eligible countries. Payment setup depends on location, so check the listing and Alignerr's FAQ for your country. ## Our independence SoftwareSideHustles.com is not affiliated with or endorsed by Alignerr or Labelbox. Alignerr alone decides who is accepted and which projects are offered. ### Published requirements - Some projects require an AI interview or a domain-specific assessment. (sourced) [Source](https://www.alignerr.com/process) - Accepted contributors complete phone and ID verification (via Persona). (sourced) [Source](https://www.alignerr.com/process) ### Sources - [Alignerr — homepage](https://www.alignerr.com/) - [Alignerr — application process](https://www.alignerr.com/process) - [Alignerr — FAQs](https://www.alignerr.com/faqs) --- ### Mercor: developer guide https://softwaresidehustles.com/opportunities/mercor Mercor connects professionals with AI companies for human evaluation, data and benchmark work, including software engineering benchmarks. You apply to specific listings; the process can include an AI interview, assessments and identity verification, and pay is set per contract. Sources last checked: 2026-10-12. ## What the work involves Mercor describes itself as "organizing human intelligence to power the AI economy". It offers human evaluation, data and benchmark work to AI companies, including **APEX-SWE**, a benchmark of real-world software engineering tasks. Its network includes engineers alongside other professionals. ## How applying works Mercor's talent documentation covers these parts of the process: - creating an account with passwordless email verification and setting up your profile and résumé; - applying to specific listings; - an **AI interview**, with guidance on preparation, resets and retakes; - **assessments** used to qualify for opportunities; - **ID verification** through Persona, and background checks for some projects; - project onboarding, which can include time tracking with Insightful. ## Location Mercor's referral documentation states: when a job listing indicates a specific region, only candidates from that region are eligible; where no location is specified, the opportunity is presumed to be available to applicants in the **United States, Canada, the United Kingdom or the European Union**. Mercor also publishes a list of countries where it can pay experts (via Stripe Connect, or Wise in some countries). Check the listing and these pages for your country. ## Pay Pay is set per listing and contract. Mercor's homepage advertises an average contracted rate, but individual rates vary by role and project, and work is not guaranteed. ## Our independence SoftwareSideHustles.com is not affiliated with or endorsed by Mercor. Mercor alone decides who is accepted and which projects are offered. ### Published requirements - Region-specific listings accept only candidates from that region; listings without a location are presumed open to the US, Canada, the UK and the EU. (sourced) [Source](https://talent.docs.mercor.com/policies/referrals) - The process can include an AI interview, assessments and ID verification. (sourced) [Source](https://talent.docs.mercor.com/llms.txt) ### Sources - [Mercor — homepage](https://www.mercor.com/) - [Mercor talent docs — index](https://talent.docs.mercor.com/llms.txt) - [Mercor — Referral Policy and FAQs](https://talent.docs.mercor.com/policies/referrals) - [Mercor — Supported Countries for Payment](https://talent.docs.mercor.com/policies/supported-countries) --- ### micro1: developer guide https://softwaresidehustles.com/opportunities/micro1 micro1 runs an expert network for AI training work. You apply to an opportunity, complete an AI-led interview, and, once certified, may be invited to AI training projects that match your verified skills across domains such as engineering, finance, healthcare, legal and more. Certification does not guarantee placement, and pay is set per opportunity. Sources last checked: 2026-10-16. ## What the work involves micro1 runs an expert network that helps "teach next-generation AI systems". Work is described broadly as **AI training projects** in your area of expertise — reviewing and annotating AI-generated content for accuracy and giving expert feedback. Job listings for the network name task types such as **RLHF**, **SFT** and **evaluations**, and target domains include engineering, finance, healthcare and medical, legal, economics, linguistics and cinematography. ## How applying works micro1's experts page lists four steps: **apply for opportunities**, **take the AI interview** (run by its AI recruiter, "Zara"), **get onboarded**, and **start earning**. Once certified you "may be invited to contribute" to projects that fit your verified skills — certification does not guarantee placement. You can check your application status at talent.micro1.ai. ## Who it's for The page says opportunities range from early-career professionals to PhDs and industry leaders, and that certification decisions are "based on demonstrated knowledge rather than background, location, or personal characteristics". It emphasises validated, subject-matter expertise. ## Remote & location micro1 advertises fully remote, flexible work that it says can be compatible with other professional or academic commitments. It says it hires globally with exceptions, and its experts page lists countries whose residents it does not hire, citing legal, regulatory and security requirements. Individual job listings may add their own location requirements, so check each posting. ## Referrals & our independence micro1 operates a "Refer & earn" affiliate program (referral links are created at refer.micro1.ai). SoftwareSideHustles.com is independent and is not affiliated with or endorsed by micro1. micro1 alone decides who is accepted and which projects are offered. ### Published requirements - micro1's experts page states it does not hire residents of these countries, citing legal, regulatory and security requirements. The list can change — check micro1's current page before relying on this. (sourced) [Source](https://micro1.ai/experts) - The process includes an AI interview (micro1's recruiter, "Zara"), and certification is based on demonstrated knowledge and does not guarantee placement. (sourced) [Source](https://micro1.ai/experts) ### Sources - [micro1 — Experts](https://micro1.ai/experts) - [micro1 — Refer & earn (affiliate program)](https://www.micro1.ai/affiliate-program) - [micro1 — Referral terms](https://www.micro1.ai/legal/referral-terms) --- ## Software engineering concepts ### Big O Notation Explained With Real Code Examples https://softwaresidehustles.com/blog/big-o-notation-explained By Software Side Hustles Editorial Team Published: 2026-10-26T09:00:00Z Updated: 2026-10-26T09:00:00Z A practical explanation of Big O — what O(1), O(log n), O(n), O(n log n) and O(n²) mean, how to work out the complexity of your own code, and the hidden linear operations that make innocent-looking loops slow. **Quick answer:** Big O describes how the work an algorithm does **grows** as its input grows, ignoring constant factors. O(1) is constant regardless of size, O(n) grows in proportion to the input, O(n²) grows with the square of it. It matters because the difference between O(n) and O(n²) is invisible on 100 items and decisive on 1,000,000. ## The common complexities | Big O | Name | Example | Operations for n = 1,000,000 | |---|---|---|---| | O(1) | Constant | Read `arr[i]`, look up a key in a hash map | 1 | | O(log n) | Logarithmic | Binary search in a sorted array | ~20 | | O(n) | Linear | Loop over every item once | 1,000,000 | | O(n log n) | Linearithmic | Efficient sorting (Timsort, merge sort) | ~20,000,000 | | O(n²) | Quadratic | Compare every item with every other item | 1,000,000,000,000 | | O(2ⁿ) | Exponential | Try every subset; naive recursive Fibonacci | astronomically large | At a billion simple operations per second, the O(n log n) column finishes in a fraction of a second. The O(n²) column takes over a quarter of an hour. ## O(1): constant time ```python def first(items): return items[0] prices = {"apple": 0.5} prices["apple"] # hash lookup: O(1) on average ``` The work does not depend on how big `items` or `prices` is. "Constant" does not mean "fast" — it means "does not grow". ## O(n): linear time ```python def total(items): s = 0 for x in items: s += x return s ``` One pass, one unit of work per item. Double the input, double the time. ## O(n²): quadratic time ```python def has_duplicates(items): for i in range(len(items)): for j in range(i + 1, len(items)): if items[i] == items[j]: return True return False ``` A loop inside a loop over the same data. With a set, the same question becomes O(n): ```python def has_duplicates(items): return len(set(items)) != len(items) ``` Trading memory (the set) for time is one of the most common optimisations in practice. ## O(log n): logarithmic time Each step halves the remaining work. Binary search on a sorted list of a million items needs about 20 comparisons, because 2²⁰ ≈ 1,000,000: ```python import bisect i = bisect.bisect_left(sorted_ids, target) found = i < len(sorted_ids) and sorted_ids[i] == target ``` Balanced trees and database B-tree indexes give O(log n) lookups for the same reason — which is why adding the right index turns a slow query into a fast one. ## O(n log n): sorting Comparison-based sorting cannot do better than O(n log n) in general, and the built-in sorts in Python, Java and JavaScript achieve it. If you sort inside a loop, though, you multiply: sorting once per item is O(n² log n). ## How to work out the complexity of your code 1. **Count loops over the input.** One loop: O(n). Nested loops over the same input: O(n²). Sequential loops: O(n) + O(n) = still O(n). 2. **Drop constants and smaller terms.** O(3n + 50) is O(n). O(n² + n) is O(n²). 3. **Use different letters for different inputs.** Looping over `users` and, inside, over `orders` is O(u × o), not O(n²). 4. **Look inside the loop body for hidden costs.** This is where most real-world slowness comes from. ## Hidden O(n) operations inside loops These look like single steps but scan or copy the whole collection: | Operation | Cost | Faster alternative | |---|---|---| | `x in some_list` (Python), `arr.includes(x)` (JS) | O(n) | use a `set` / `Set`: O(1) | | `list.pop(0)`, `list.insert(0, x)` (Python) | O(n) | `collections.deque`: O(1) at both ends | | `arr.shift()` / `arr.unshift()` (JS) | O(n) | index pointer, or a proper queue | | `ArrayList.remove(0)` (Java) | O(n) | `ArrayDeque` | | `LinkedList.get(i)` (Java) | O(n) | `ArrayList` for random access | | `s = s + piece` in a loop (Python, Java) | O(n) copy per step | `"".join(parts)`, `StringBuilder` | | `arr.indexOf(x)` / `list.index(x)` | O(n) | a dict/map from value to index | | A database query inside a loop (N+1 queries) | n round trips | one query with `JOIN` or `IN` | A loop of n iterations containing any of these is O(n²) — even though there is only one visible loop. ## Space complexity Big O also describes **memory**. Building a set of all items is O(n) extra space; reversing an array in place with two pointers is O(1) extra space. Recursion uses stack space proportional to its depth, which is how [stack overflow errors](https://softwaresidehustles.com/blog/maximum-recursion-depth-and-stack-overflow) happen. ## Average, worst case and amortised - **Hash maps** are O(1) on *average*, but O(n) in the worst case when many keys collide. Real implementations make that worst case very unlikely. - **Appending to a dynamic array** (`list.append`, `ArrayList.add`, `arr.push`) is *amortised* O(1): occasionally the array has to grow and copy everything, but averaged over many appends each costs a constant amount. - **Quicksort** is O(n log n) on average and O(n²) in the worst case, which is why libraries use variants or other algorithms with better guarantees. ## When Big O does not matter For small inputs, constants dominate: a simple O(n²) loop over 20 items can beat a clever O(n log n) algorithm with more overhead. Readability matters too. Optimise when the input can be large or the code runs often — and measure with a profiler, not guesses. ## Frequently asked questions ### What is the difference between Big O, Big Theta and Big Omega? Strictly, Big O is an upper bound, Omega a lower bound and Theta a tight bound. In everyday engineering conversation, "Big O" is used to mean the tight bound for the case being discussed. ### Is O(2n) the same as O(n)? Yes. Constant factors are dropped because they do not change how the cost grows. ### What is the Big O of a dictionary lookup? O(1) on average for hash-based dictionaries (Python `dict`, JavaScript `Map`, Java `HashMap`). Tree-based maps such as Java's `TreeMap` are O(log n). ### How do I improve an O(n²) algorithm? Usually by precomputing a lookup structure (a set or map), sorting first so you can use two pointers or binary search, or reducing repeated work with caching. ## Where this skill pays off Complexity analysis is one of the main criteria for judging AI-generated solutions — is the "clever" answer actually faster, and does the stated complexity match the code? Try our free [linear vs binary search](https://softwaresidehustles.com/practice/code-comparison) and nested-loop exercises, and read [what makes one coding solution better than another](https://softwaresidehustles.com/blog/what-makes-one-coding-solution-better-than-another). ### About the author Written and reviewed by the Software Side Hustles editorial team. Code examples are executed before publication, and platform facts link to the platform's own pages with the date they were checked. --- ### Concurrency vs Parallelism: Threads, Processes, async and Python's GIL Explained https://softwaresidehustles.com/blog/concurrency-vs-parallelism By Software Side Hustles Editorial Team Published: 2026-10-26T09:00:00Z Updated: 2026-10-26T09:00:00Z The difference between concurrency and parallelism, when to use threads, processes or async/await, why Python threads don't speed up CPU-bound code, and the race conditions and deadlocks to watch for. **Quick answer:** **concurrency** is about *dealing with* many tasks at once — making progress on several by interleaving them. **Parallelism** is about *doing* many tasks at the same instant on multiple CPU cores. Waiting on networks, disks or databases (I/O-bound work) benefits from concurrency: threads or async/await. Heavy computation (CPU-bound work) needs parallelism: multiple processes, or threads in a runtime that can run them on several cores at once. ## An analogy One chef cooking three dishes — chopping while the water boils, stirring while the oven heats — is **concurrent**: one worker, many tasks in progress, switching during waits. Three chefs each cooking a dish is **parallel**. A busy restaurant kitchen is both. A single-core machine can be concurrent but not parallel. A multi-core machine can be both. ## I/O-bound vs CPU-bound The first question for any performance problem is *what the program is waiting for*. | Workload | Bottleneck | Helps | Example | |---|---|---|---| | I/O-bound | Network, disk, database latency | Concurrency: async, threads | Calling 100 APIs, web servers, scrapers | | CPU-bound | Processor time | Parallelism: processes, multi-core threads | Image processing, compression, number crunching | Making an I/O-bound task "parallel" across cores does little; making a CPU-bound task "concurrent" on one core does nothing at all. ## Threads, processes and async compared | Model | Memory | Runs in parallel? | Good for | Watch out for | |---|---|---|---|---| | Processes | Separate | Yes | CPU-bound work, isolation | Start-up cost; data must be serialised between them | | Threads | Shared | Yes (except under a GIL) | I/O and CPU work in Java, C#, Go, C++ | Race conditions, deadlocks | | async/await (event loop) | Shared, one thread | No | Many concurrent I/O operations | Blocking calls freeze everything | | Goroutines / virtual threads | Shared | Yes | Huge numbers of concurrent tasks | Same races as threads | ## Python and the GIL CPython's **Global Interpreter Lock** allows only one thread to execute Python bytecode at a time. So: - **Threads do help I/O-bound code**, because the GIL is released while waiting for network or disk. - **Threads do not speed up pure-Python CPU-bound code** — four threads computing in a loop take about as long as one, and sometimes longer. ```python from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor # I/O-bound: threads (or asyncio) with ThreadPoolExecutor(max_workers=10) as pool: pages = list(pool.map(fetch_url, urls)) # CPU-bound: processes, one interpreter (and one GIL) per core if __name__ == "__main__": with ProcessPoolExecutor() as pool: results = list(pool.map(resize_image, paths)) ``` The `if __name__ == "__main__":` guard is required for process pools on Windows and macOS, which start workers by re-importing your module. Two qualifications. First, libraries such as NumPy release the GIL inside their C code, so threads *can* run NumPy operations in parallel. Second, CPython 3.13 introduced an experimental **free-threaded** build without the GIL, and Python 3.14 made it officially supported (though still not the default build). Check that your dependencies support it before relying on it. ## JavaScript: one thread, an event loop JavaScript runs your code on a single thread. `async`/`await` provides concurrency for I/O: while one request waits, others proceed. But a CPU-heavy loop blocks *everything* — no other requests are served and the browser UI freezes. For CPU-bound work, use **Worker threads** in Node.js or **Web Workers** in the browser. See [async/await mistakes](https://softwaresidehustles.com/blog/promise-pending-async-await) for the I/O side. ## Java: platform threads and virtual threads Java threads run truly in parallel. Since Java 21, **virtual threads** make it cheap to have hundreds of thousands of concurrent tasks for I/O-heavy servers: ```java try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { for (String url : urls) { executor.submit(() -> fetch(url)); } } ``` Virtual threads help with *waiting*, not with computing; for CPU-bound work, a pool sized to the number of cores remains the right tool. ## Race conditions When threads share mutable data, operations that look atomic are not: ```python counter = 0 def work(): global counter for _ in range(100_000): counter += 1 # read, add, write — another thread can interleave ``` Run that in several threads and the final count may be lower than expected, depending on the interpreter version and timing — which is exactly what makes races hard to reproduce. Fixes, roughly in order of preference: 1. **Avoid sharing:** give each worker its own data and combine results at the end (`pool.map` returning values). 2. **Use thread-safe structures:** `queue.Queue`, Java's `ConcurrentHashMap`, `AtomicInteger`, Go channels. 3. **Lock** around the critical section: `with lock:` in Python, `synchronized` or `ReentrantLock` in Java. Even single-threaded async code can race: two concurrent requests that each "read balance, then write balance minus 10" can both read the same starting value if there is an `await` between the read and the write. Databases solve the same problem with transactions, row locks and atomic updates (`UPDATE accounts SET balance = balance - 10 WHERE id = ?`). ## Deadlocks A deadlock happens when two tasks each hold a lock the other needs: - Thread A locks `accounts[1]`, then waits for `accounts[2]`. - Thread B locks `accounts[2]`, then waits for `accounts[1]`. Neither can continue. Prevent it by always acquiring locks in a consistent order (for example, by ascending ID), holding locks for as little time as possible, and using timeouts. ## Amdahl's law: why 8 cores is not 8× faster If 25% of a job is inherently sequential, then even with infinite cores the maximum speed-up is 4×. Parallelising the rest helps, but the sequential part soon dominates. Measure where time actually goes before parallelising — and remember that coordination (locks, serialising data between processes) has its own cost. ## Frequently asked questions ### Is async faster than threads? For many concurrent I/O operations, async uses less memory and avoids context-switch overhead. It is not faster for CPU-bound work, and it requires async-compatible libraries throughout. ### Should I use multiprocessing or threading in Python? Threading (or asyncio) for I/O-bound tasks; multiprocessing (`ProcessPoolExecutor`) for CPU-bound pure-Python tasks. ### Is Node.js multithreaded? Your JavaScript runs on one thread, but Node.js uses a thread pool internally for some I/O, and you can create Worker threads explicitly. ### What is a thread-safe function? One that behaves correctly when called from several threads at once, typically because it does not modify shared state or protects that state with synchronisation. ## Where this skill pays off "Use threads to speed up this CPU-bound loop" is a claim AI assistants make confidently — and in CPython it is usually wrong. Our [preference labelling lab](https://softwaresidehustles.com/practice/preference-labelling) includes exactly that exercise. Spotting overclaims like this is a core skill in paid AI evaluation work; see [how to prepare for technical AI evaluation work](https://softwaresidehustles.com/blog/how-to-prepare-for-technical-ai-evaluation-work). ### About the author Written and reviewed by the Software Side Hustles editorial team. Code examples are executed before publication, and platform facts link to the platform's own pages with the date they were checked. --- ### Deep Copy vs Shallow Copy: Why Changing the Copy Changed the Original https://softwaresidehustles.com/blog/deep-copy-vs-shallow-copy By Software Side Hustles Editorial Team Published: 2026-10-26T09:00:00Z Updated: 2026-10-26T09:00:00Z Why editing a "copy" of a list or object also changes the original, the difference between assignment, shallow copy and deep copy, and how to copy correctly in Python, JavaScript and Java. **Quick answer:** assignment (`b = a`) copies a *reference*, so both names point at the same object. A **shallow copy** creates a new outer container but shares the items inside it. A **deep copy** recursively copies everything. If your data contains nested lists, dictionaries or objects and you need an independent copy, use `copy.deepcopy(x)` in Python or `structuredClone(x)` in JavaScript. ## Assignment, shallow copy and deep copy ```python import copy original = {"name": "Ada", "skills": ["python", "sql"]} alias = original # same object shallow = original.copy() # new dict, same 'skills' list deep = copy.deepcopy(original) # new dict, new list original["skills"].append("go") alias["skills"] # ['python', 'sql', 'go'] shallow["skills"] # ['python', 'sql', 'go'] — shared inner list deep["skills"] # ['python', 'sql'] — independent ``` | Operation | New outer object? | New nested objects? | |---|---|---| | `b = a` | No | No | | Shallow copy | Yes | No | | Deep copy | Yes | Yes | For flat data — a list of numbers or strings — a shallow copy is enough, because numbers and strings are immutable and cannot be changed through the copy. ## How do I copy a list or dictionary in Python? ```python nums = [1, 2, 3] a = nums.copy() # shallow b = nums[:] # shallow c = list(nums) # shallow d = copy.deepcopy(nested_structure) ``` ### The grid bug: `[[0] * 3] * 3` ```python grid = [[0] * 3] * 3 grid[0][0] = 1 print(grid) # [[1, 0, 0], [1, 0, 0], [1, 0, 0]] ``` Multiplying the outer list repeats a **reference** to the same inner list three times. Change one row and every row changes. Build independent rows with a comprehension: ```python grid = [[0] * 3 for _ in range(3)] ``` The inner `[0] * 3` is fine, because integers are immutable. ## How do I deep copy an object in JavaScript? ```javascript const original = { name: "Ada", skills: ["js"], joined: new Date("2020-01-01") }; const shallow = { ...original }; // or Object.assign({}, original) const deep = structuredClone(original); // modern browsers and Node.js 17+ shallow.skills.push("go"); original.skills; // ["js", "go"] — shared deep.skills; // ["js"] deep.joined instanceof Date; // true ``` `structuredClone` handles nested objects, arrays, `Date`, `Map`, `Set` and even circular references. It cannot clone functions (it throws a `DataCloneError`), DOM nodes, or class behaviour — a cloned class instance becomes a plain object without its methods. The older `JSON.parse(JSON.stringify(obj))` trick is lossy: | Value | After the JSON round trip | |---|---| | `Date` | an ISO string | | `undefined` property | removed | | `Map` / `Set` | `{}` | | `NaN`, `Infinity` | `null` | | Circular reference | throws `TypeError` | Use it only when you know the data is plain JSON. ### Copying arrays in JavaScript `[...arr]`, `arr.slice()` and `Array.from(arr)` are shallow. An array of objects copied with spread still shares the objects; changing `copy[0].name` changes `arr[0].name`. Map to new objects if you need to change them: `arr.map((o) => ({ ...o }))`. ## How do I copy objects in Java? Java has no built-in deep copy. The usual options are: ```java List copy = new ArrayList<>(original); // shallow, mutable List frozen = List.copyOf(original); // shallow, immutable Person p2 = new Person(p1); // copy constructor you write ``` `Object.clone()` is shallow by default and awkward to implement correctly; *Effective Java* recommends copy constructors or static factory methods instead. For deep copies of complex graphs, write the copying explicitly, or serialise and deserialise (for example with Jackson) if performance is not critical. The more idiomatic Java answer is often **immutability**: records with immutable fields and `List.copyOf` can be shared freely because nobody can change them. ## When should you copy at all? Copying is a defensive tool. You need it when: - **A function must not modify its input.** Sorting a list passed in by the caller with `list.sort()` mutates their data; `sorted(list)` does not. See [pass by value vs pass by reference](https://softwaresidehustles.com/blog/pass-by-value-vs-pass-by-reference). - **State management requires new objects.** React and Redux detect changes by reference, so you must create new objects rather than mutate existing ones. A shallow copy at each changed level is the norm: `{ ...state, user: { ...state.user, name } }`. - **You store something a caller can still change.** A class that keeps a reference to a list passed into its constructor can have its internals modified from outside. Copy on the way in (and out). Deep copies have a cost: they allocate and traverse everything. For large structures, prefer designs where data is not mutated after creation, so copies are unnecessary. ## Common mistakes 1. **Believing slicing makes an independent copy of nested data.** `rows[:]` copies the outer list only. 2. **Mutable default arguments in Python.** `def add(item, items=[])` shares one list across every call. Use `items=None` and create the list inside. 3. **Copying too late.** By the time you copy, the shared object may already have been modified. 4. **Deep-copying objects that hold resources** — database connections, file handles, locks. Those should be shared, not copied. ## Frequently asked questions ### Is `list.copy()` a deep copy? No. It is shallow: the new list contains the same element objects. ### Is the spread operator a deep copy? No. `{ ...obj }` and `[...arr]` copy one level only. ### What is the fastest way to deep copy in JavaScript? `structuredClone` is the standard, correct choice. Hand-written copy functions for a known shape can be faster, but measure before optimising. ### Why does `copy.deepcopy` not copy my class correctly? It does by default, attribute by attribute. If your class holds resources or caches, implement `__deepcopy__` to control what is shared. ## Where this skill pays off "The function must not modify its input" is a requirement that AI-generated code breaks surprisingly often — our free guide on [how to evaluate AI-generated code](https://softwaresidehustles.com/blog/how-to-evaluate-ai-generated-code) walks through exactly that bug. Catching it, and explaining it in one clear sentence, is what AI code-evaluation work pays for. ### About the author Written and reviewed by the Software Side Hustles editorial team. Code examples are executed before publication, and platform facts link to the platform's own pages with the date they were checked. --- ### == vs === vs is vs equals(): Equality in JavaScript, Python and Java Explained https://softwaresidehustles.com/blog/equality-operators-explained By Software Side Hustles Editorial Team Published: 2026-10-26T09:00:00Z Updated: 2026-10-26T09:00:00Z The difference between value equality and identity, why JavaScript has == and ===, why Python's is works for small numbers but not large ones, why Java strings must be compared with equals(), and how to compare objects correctly. **Quick answer:** there are two questions you can ask about two values: *are they equal?* (same value) and *are they the same object?* (identity). JavaScript: use `===` for almost everything. Python: use `==` for values and `is` only for `None` (and other singletons). Java: use `.equals()` for objects including `String`, and `==` for primitives. ## Equality versus identity ```python a = [1, 2, 3] b = [1, 2, 3] c = a a == b # True — same contents a is b # False — two different list objects a is c # True — two names for one object ``` Every language makes this distinction; they just spell it differently. | Question | JavaScript | Python | Java | C# | |---|---|---|---|---| | Same value? | `===` (primitives) | `==` | `.equals()` | `==` for strings, `.Equals()` | | Same object? | `===` (objects) | `is` | `==` (objects) | `ReferenceEquals()` | | Loose, with type coercion | `==` | — | — | — | ## JavaScript: `==` versus `===` `===` (strict equality) compares without converting types. `==` (loose equality) converts the operands first, following rules few people remember: ```javascript 0 == ""; // true "0" == false; // true [] == false; // true "1" == 1; // true null == undefined; // true null == 0; // false 0 === ""; // false "1" === 1; // false ``` Use `===` and `!==` everywhere. The one idiom some teams allow is `x == null`, which is true for both `null` and `undefined`; the clearer modern alternative is `x ?? fallback`. ### Objects compare by reference ```javascript { a: 1 } === { a: 1 }; // false — different objects [1, 2] === [1, 2]; // false ``` There is no built-in deep equality operator. Compare the fields you care about, use a library function (Node's `util.isDeepStrictEqual`, lodash `isEqual`), or in tests use `toEqual` rather than `toBe`. ### NaN and -0 ```javascript NaN === NaN; // false — NaN is not equal to anything, itself included Number.isNaN(x); // the correct check Object.is(NaN, NaN); // true Object.is(0, -0); // false, although 0 === -0 is true ``` ## Python: `==` versus `is` `==` calls `__eq__` and compares values. `is` checks whether two names refer to the same object. The trap is that `is` *appears* to work for numbers and strings in quick experiments: ```python a = int("5"); b = int("5") a is b # True — CPython caches small integers (-5 to 256) a = int("257"); b = int("257") a == b # True a is b # False — two separate int objects ``` String literals are often *interned* too, so `"hello" is "hello"` may be `True` — but strings built at runtime usually are not. Results depend on the implementation and context, which is exactly why you must not rely on them. Recent Python versions emit `SyntaxWarning: "is" with 'int' literal. Did you mean "=="?` when you write `x is 5`. Use `is` for singletons, where identity *is* the meaning: ```python if value is None: ... if result is NotImplemented: ... ``` `x is None` is preferred over `x == None` because a class can override `__eq__` to return anything; identity cannot be overridden. ## Java: `==` versus `.equals()` For primitives (`int`, `double`, `char`, `boolean`), `==` compares values. For objects, `==` compares **references**: ```java String s = "hello"; String t = "hello"; String u = new String("hello"); s == t; // true — both literals refer to the same interned string s == u; // false — u is a separate object s.equals(u); // true — same characters ``` The literal case "working" is what makes this bug survive testing; strings read from input, built with `+` at runtime or returned from methods are separate objects. Always use `.equals()` (or `Objects.equals(a, b)` when either may be null). ### The Integer cache trap ```java Integer a = 127, b = 127; a == b; // true — values -128..127 are cached Integer c = 128, d = 128; c == d; // false — different Integer objects c.equals(d); // true ``` Code comparing boxed `Integer` or `Long` IDs with `==` works in development, where IDs are small, and fails in production once they exceed 127. ### Implementing `equals` and `hashCode` If you override `equals`, you must override `hashCode` so that equal objects have equal hash codes. Otherwise `HashSet` and `HashMap` treat equal objects as different, and duplicates appear. Java `record`s generate both from their fields. In Python, defining `__eq__` sets `__hash__` to `None` (making instances unhashable) unless you also define `__hash__`; `@dataclass(frozen=True)` handles it for you. ## Comparing floating-point numbers `0.1 + 0.2 == 0.3` is false in all of these languages because of binary floating-point representation. Compare with a tolerance instead — `math.isclose(a, b)` in Python, or `Math.abs(a - b) < epsilon` — as explained in [rounding and floating point](https://softwaresidehustles.com/blog/round-to-two-decimal-places). ## Equality in tests | Framework | Same object | Same value / structure | |---|---|---| | Jest / Vitest | `toBe` | `toEqual`, `toStrictEqual` | | pytest | `assert a is b` | `assert a == b` | | JUnit | `assertSame` | `assertEquals` | | AssertJ | `isSameAs` | `isEqualTo`, `usingRecursiveComparison()` | Using `toBe` on objects is a common reason for "expected [1, 2] but received [1, 2]". ## Frequently asked questions ### Should I ever use `==` in JavaScript? Rarely. `x == null` to catch both `null` and `undefined` is the only widely accepted use, and many style guides forbid even that. ### Why does `is` work for small integers in Python? CPython pre-creates integers from -5 to 256 and reuses them. It is an implementation detail and may differ across implementations and versions. ### Why does `==` work for strings in my Java test? Because both strings are literals in the same program and are interned. Strings created at runtime are different objects. ### How do I compare two objects by their contents? Python: implement `__eq__` (or use a dataclass). Java: implement `equals` and `hashCode` (or use a record). JavaScript: compare fields, or use a deep-equality helper. ## Where this skill pays off "`==` versus `is` in Python" is a real exercise in our [preference labelling lab](https://softwaresidehustles.com/practice/preference-labelling) — two plausible explanations where one subtly overstates when `is` is safe. Ranking answers like these, with a clear justification, is paid AI training work; see [how preference ranking works](https://softwaresidehustles.com/blog/how-preference-ranking-works-in-ai-evaluation). ### About the author Written and reviewed by the Software Side Hustles editorial team. Code examples are executed before publication, and platform facts link to the platform's own pages with the date they were checked. --- ### How to Write Good Unit Tests (With an Edge-Case Checklist You Can Reuse) https://softwaresidehustles.com/blog/how-to-write-good-unit-tests By Software Side Hustles Editorial Team Published: 2026-10-26T09:00:00Z Updated: 2026-10-26T09:00:00Z What makes a unit test useful rather than noise — structure, naming, testing behaviour not implementation, deterministic tests, parameterised cases, mocking sparingly — plus a reusable checklist of edge cases most bugs hide in. **Quick answer:** a good unit test checks one behaviour, reads like a specification, fails for exactly one reason and gives the same result every time it runs. Structure it as **Arrange, Act, Assert**, test the public behaviour rather than private details, and spend most of your effort on **edge cases** — empty input, boundaries, duplicates, invalid values and time — because that is where bugs live. ## The anatomy of a good test ```python def test_order_total_applies_percentage_discount(): # Arrange order = Order(items=[Item(price=Decimal("20.00"), qty=2)]) # Act total = order.total(discount_percent=10) # Assert assert total == Decimal("36.00") ``` The same in Jest: ```javascript test("applies a percentage discount to the order total", () => { const order = new Order([{ price: 2000, qty: 2 }]); // amounts in pence expect(order.total({ discountPercent: 10 })).toBe(3600); }); ``` And JUnit 5: ```java @Test void appliesPercentageDiscountToTotal() { var order = new Order(List.of(new Item(new BigDecimal("20.00"), 2))); assertEquals(new BigDecimal("36.00"), order.total(10)); } ``` What makes these good: - **The name states the behaviour.** When it fails, the test name tells you what broke without reading the code. - **One behaviour per test.** Several assertions are fine if they describe one outcome; testing discounts *and* tax *and* shipping in one test is not. - **No logic in the test.** Loops and conditionals in tests can have bugs of their own. Hard-code the expected value. - **Exact, meaningful values.** `36.00` derived by hand is better than `assert total > 0`. ## Test behaviour, not implementation Tests that check *how* code works — which private method was called, the order of internal steps — break whenever you refactor, even when behaviour is unchanged. Tests that check *what* the code does survive refactoring and catch real regressions. Ask: "If I rewrote this function completely but it still produced correct results, would this test still pass?" If not, it is coupled to the implementation. ## The edge-case checklist Run through this list for any function that takes input. Most production bugs are in one of these rows. | Category | Cases to try | |---|---| | Size | empty, one element, two elements, many, maximum allowed | | Numbers | zero, negative, one, very large, decimals, `NaN`/infinity, overflow boundaries | | Boundaries | exactly at the limit, one below, one above (off-by-one) | | Strings | empty, whitespace only, leading/trailing spaces, very long, Unicode and emoji, mixed case | | Collections | duplicates, already sorted, reverse sorted, all identical, unsorted | | Missing data | `None`/`null`/`undefined`, missing keys, optional fields absent | | Invalid input | wrong type, malformed format, out-of-range values — does it fail clearly? | | Time | midnight, month end, leap day, DST change, other time zones, New Year week | | Money | rounding of halves, many small amounts summed, currency with no minor unit | | State | first call, repeated call (idempotency), call after an error | | Concurrency | two operations at once on the same record | You do not need every row for every function. The habit of *asking* catches the bugs that "the example works" testing misses. See [off-by-one errors](https://softwaresidehustles.com/blog/index-out-of-range-off-by-one) and [dates and time zones](https://softwaresidehustles.com/blog/dates-times-and-time-zones) for common examples. ## Parameterised tests for many cases Instead of copying a test ten times, list the cases: ```python import pytest @pytest.mark.parametrize("raw, expected", [ ("42", 42), (" 42\n", 42), ("-7", -7), ("0", 0), ]) def test_parse_quantity_accepts_valid_integers(raw, expected): assert parse_quantity(raw) == expected @pytest.mark.parametrize("raw", ["", "4.2", "abc", "1e3"]) def test_parse_quantity_rejects_invalid_input(raw): with pytest.raises(ValueError): parse_quantity(raw) ``` Jest has `test.each`, JUnit 5 has `@ParameterizedTest` with `@CsvSource` or `@MethodSource`. Splitting valid and invalid cases into separate tests keeps each test's purpose clear. ## Make tests deterministic A test that sometimes fails ("flaky") is worse than no test: people learn to ignore failures. Common causes and fixes: - **The current time:** inject a clock, or freeze time (`freezegun`/`time-machine` in Python, `vi.useFakeTimers()` / `jest.useFakeTimers()`, `java.time.Clock` in Java). - **Randomness:** inject the random generator or fix the seed. - **Network and external services:** replace them with fakes at the boundary; keep real network calls for a smaller set of integration tests. - **Shared state between tests:** each test should create its own data; never depend on test order. - **Timing with sleeps:** wait for a condition, not for a fixed number of milliseconds. ## Mock sparingly Mocks are useful at boundaries you do not own — HTTP APIs, payment providers, email. Mocking everything inside your own code produces tests that only confirm the code calls what it calls. Prefer real objects for in-process collaborators, simple in-memory fakes (a dictionary-backed repository) over deep mock chains, and a few integration tests against a real database (for example with Testcontainers) for queries. ## Coverage is a tool, not a goal Line coverage tells you which code your tests never run; it cannot tell you whether the tests check anything meaningful. A test with no assertions can reach 100% coverage. Use coverage to find untested branches, then write tests that assert on behaviour. Mutation testing (mutmut, Stryker, PIT) is a stronger signal: it changes your code slightly and checks whether a test fails. ## Write the failing test first when fixing a bug Before fixing a bug, write a test that reproduces it and watch it fail. Then fix the code and watch it pass. This proves the test actually detects the bug, documents the case, and prevents the bug returning. See [how to debug code systematically](https://softwaresidehustles.com/blog/how-to-debug-code-systematically). ## Property-based testing For functions with clear invariants, let a library generate hundreds of inputs: "sorting twice equals sorting once", "decode(encode(x)) == x", "the output is never longer than the input". Hypothesis (Python), fast-check (JavaScript) and jqwik (Java) find edge cases you would not think to write, and shrink failures to a minimal example. ## Frequently asked questions ### How many tests should a function have? Enough to cover each distinct behaviour and the relevant edge cases. A simple getter may need none; a pricing function may need twenty. ### Should I test private methods? Usually not directly. Test them through the public behaviour they support. If a private method is complex enough to need its own tests, it may belong in its own unit. ### What is the difference between unit and integration tests? Unit tests check a small piece in isolation and run in milliseconds. Integration tests check that pieces work together — your code with a real database, queue or HTTP layer. You need both. ## Where this skill pays off Writing edge cases that break a plausible solution is one of the most valuable skills in AI code evaluation — and our free [merge intervals review](https://softwaresidehustles.com/practice/code-review) tests whether you can confirm that correct code is correct, not only find bugs. Read [how to evaluate AI-generated code](https://softwaresidehustles.com/blog/how-to-evaluate-ai-generated-code) to see how edge-case hunting fits into paid review work. ### About the author Written and reviewed by the Software Side Hustles editorial team. Code examples are executed before publication, and platform facts link to the platform's own pages with the date they were checked. --- ### HTTP Status Codes for REST APIs: Which One to Return (401 vs 403, 400 vs 422 and More) https://softwaresidehustles.com/blog/http-status-codes-for-apis By Software Side Hustles Editorial Team Published: 2026-10-26T09:00:00Z Updated: 2026-10-26T09:00:00Z A practical guide to choosing HTTP status codes in a REST API — the codes you actually need, the confusing pairs (401/403, 400/422, 200/204, 404/410, 502/503/504), and a consistent error response format. **Quick answer:** use `2xx` for success (`200` with a body, `201` when you created something, `204` with no body), `4xx` when the **client** must change the request (`400` malformed, `401` not authenticated, `403` not allowed, `404` not found, `409` conflict, `422` failed validation, `429` rate-limited) and `5xx` when the **server** failed (`500` bug, `502`/`504` upstream problems, `503` temporarily unavailable). The most-confused pair: **401 means "who are you?", 403 means "I know who you are, and no".** ## The status codes you actually need | Code | Name | Use it when | |---|---|---| | 200 | OK | Successful `GET`, or an update that returns the resource | | 201 | Created | A `POST` created a resource; include a `Location` header | | 202 | Accepted | Work was queued and will finish later | | 204 | No Content | Success with no body, e.g. `DELETE` | | 301 / 308 | Moved Permanently / Permanent Redirect | A URL changed for good (308 keeps the method) | | 302 / 307 | Found / Temporary Redirect | Temporary redirect (307 keeps the method) | | 304 | Not Modified | Conditional `GET`: the client's cached copy is still valid | | 400 | Bad Request | Malformed syntax: invalid JSON, wrong types, missing required parameter | | 401 | Unauthorized | No credentials, or invalid/expired credentials | | 403 | Forbidden | Authenticated, but not permitted | | 404 | Not Found | The resource does not exist (or you will not reveal it does) | | 405 | Method Not Allowed | e.g. `DELETE` on an endpoint that only supports `GET` | | 409 | Conflict | The request conflicts with current state: duplicate email, version mismatch | | 410 | Gone | The resource existed but has been permanently removed | | 415 | Unsupported Media Type | Wrong `Content-Type`, e.g. form data sent to a JSON endpoint | | 422 | Unprocessable Content | Well-formed but semantically invalid: end date before start date | | 429 | Too Many Requests | Rate limit exceeded; include `Retry-After` | | 500 | Internal Server Error | An unexpected bug or unhandled exception | | 502 | Bad Gateway | A proxy got an invalid response from the upstream server | | 503 | Service Unavailable | Overloaded or in maintenance; temporary | | 504 | Gateway Timeout | A proxy timed out waiting for the upstream server | ## 401 vs 403 - **401 Unauthorized** is really "unauthenticated": the request has no valid credentials. The client should log in or refresh its token and try again. The response should include a `WWW-Authenticate` header describing the scheme. - **403 Forbidden** means the server knows who the caller is, and they lack permission. Logging in again will not help. An expired token is `401`. A regular user calling an admin endpoint is `403`. ## 400 vs 422 - **400 Bad Request** — the server cannot even parse or interpret the request: invalid JSON, a string where a number belongs, a missing required field. - **422 Unprocessable Content** — the request is well-formed, but violates business rules: a negative quantity, an end date before the start date, a password that fails the policy. Many APIs use `400` for both, which is acceptable if you are consistent and your error body explains which field failed. What matters most is that clients can tell "fix your request" (4xx) from "try again later" (5xx). ## 404 vs 403 vs 410 Returning `403` for another user's private resource confirms that it exists. When existence itself is sensitive (other users' orders, private repositories), return **404** for both "does not exist" and "exists but not yours". Use `410 Gone` only when you want clients and search engines to know a resource was intentionally removed. ## 200 vs 201 vs 204 - `POST /orders` that creates an order: **201**, with the new resource (or its ID) in the body and `Location: /orders/123`. - `PUT` or `PATCH` that returns the updated resource: **200**. If nothing is returned: **204**. - `DELETE`: **204** is conventional. A repeated `DELETE` of something already deleted can return `404` or `204`; either is defensible if documented. Do not return `200` with `{"success": false}` for errors. Clients, proxies, monitoring and retry logic all rely on the status code; burying failures in the body breaks every one of them. ## 409 Conflict and concurrency Use `409` for duplicates (a username already taken) and for optimistic-locking conflicts: the client sent `If-Match: "v3"` but the resource is now at version 4. With conditional requests specifically, `412 Precondition Failed` is the precise code. ## 5xx: whose fault was it? - **500** — your code threw an unexpected exception. Log it with a stack trace, return a generic message (never the stack trace itself), and fix the bug. - **502** — a gateway or load balancer received a bad response from your app: it crashed mid-request, closed the connection, or is not listening on the expected port. - **503** — the service is temporarily unable to handle requests: overload, maintenance, a dependency circuit breaker. Add `Retry-After`. - **504** — a gateway gave up waiting for your app; the request took longer than the proxy's timeout. Clients may safely retry `502`, `503` and `504` (with backoff) for idempotent requests, and should not blindly retry `500` or any `4xx`. ## A consistent error format RFC 9457 ("Problem Details for HTTP APIs") defines a standard JSON shape, served as `application/problem+json`: ```json { "type": "https://example.com/problems/validation-error", "title": "Your request is invalid", "status": 422, "detail": "end_date must be after start_date", "errors": [{ "field": "end_date", "message": "must be after start_date" }] } ``` Spring Boot (`ProblemDetail`), ASP.NET Core (`ProblemDetails`) and many other frameworks support it out of the box. Whatever format you choose, use the same one for every endpoint, include a machine-readable code, and add a request ID that matches your logs. ## Idempotency and methods `GET`, `PUT` and `DELETE` should be **idempotent**: repeating them has the same effect as doing them once. `POST` is not, which is why retries can create duplicate orders. For payment-like `POST` endpoints, accept an `Idempotency-Key` header and return the original result for repeated keys. ## Frequently asked questions ### Should validation errors be 400 or 422? Either works if you are consistent. `422` distinguishes "valid JSON, invalid values" from "unparseable request", which some clients find useful. ### What status code for a failed login? `401` for wrong credentials. Use the same response for "unknown user" and "wrong password" so attackers cannot discover which accounts exist. ### Is 418 a real status code? "I'm a teapot" began as an April Fools' joke (RFC 2324). It is reserved so nobody assigns it, but do not use it in a real API. ## Where this skill pays off API design questions — "what should this endpoint return?" — are common in AI coding evaluations, and a response that returns `200` with an error body or leaks a stack trace in a `500` should lose. Judging those trade-offs is paid work; see [what makes one coding solution better than another](https://softwaresidehustles.com/blog/what-makes-one-coding-solution-better-than-another). ### About the author Written and reviewed by the Software Side Hustles editorial team. Code examples are executed before publication, and platform facts link to the platform's own pages with the date they were checked. --- ### Pass by Value vs Pass by Reference (and What Python, JavaScript and Java Actually Do) https://softwaresidehustles.com/blog/pass-by-value-vs-pass-by-reference By Software Side Hustles Editorial Team Published: 2026-10-26T09:00:00Z Updated: 2026-10-26T09:00:00Z Why a function can change your list but not reassign your variable, what "pass by object reference" means in Python and JavaScript, why Java is always pass-by-value, and the mutable default argument trap. **Quick answer:** Python, JavaScript and Java all pass arguments **by value** — but for objects, the value being copied is a **reference** to the object. So a function *can modify* an object you pass in (append to a list, set a field), but it *cannot replace* your variable with a different object. This model is often called "pass by sharing" or "pass by object reference". True pass-by-reference, where the function can rebind the caller's variable, exists in C++ (`&`) and C# (`ref`). ## The two behaviours people confuse ```python def add_item(items): items.append(4) # mutates the object the caller passed def replace(items): items = [0] # rebinds the local name only nums = [1, 2, 3] add_item(nums) print(nums) # [1, 2, 3, 4] — changed replace(nums) print(nums) # [1, 2, 3, 4] — unchanged ``` Inside the function, `items` is a new name pointing at the same list as `nums`. Calling a method on it reaches the shared list. Assigning to it just points the local name somewhere else; the caller's `nums` is untouched. The same experiment gives the same results in JavaScript and Java: ```javascript function addItem(items) { items.push(4); } function replace(items) { items = [0]; } const nums = [1, 2, 3]; addItem(nums); // nums is [1, 2, 3, 4] replace(nums); // nums is still [1, 2, 3, 4] ``` ```java static void addItem(List items) { items.add(4); } static void replace(List items) { items = List.of(0); } ``` ## Why numbers and strings never seem to change ```python def increment(n): n += 1 x = 5 increment(x) print(x) # 5 ``` Integers, floats, strings and tuples are **immutable** in Python; there is no method that changes them in place. `n += 1` creates a new integer and rebinds the local name. Strings and numbers behave the same way in JavaScript and Java (`String` is immutable in Java). So, for immutable values, passing a reference and passing a copy are indistinguishable — which is why people describe them as "pass by value" and objects as "pass by reference". The underlying mechanism is the same for both. ## Java is always pass-by-value The classic proof is a swap function that does not work: ```java static void swap(StringBuilder a, StringBuilder b) { StringBuilder tmp = a; a = b; b = tmp; // only the local copies of the references are swapped } ``` After calling `swap(x, y)`, `x` and `y` still refer to their original objects. Java copies the reference into the parameter; it never gives the method access to the caller's variable. That is why Java methods return new values, or mutate an object they were given, rather than "returning through" parameters. ## Real pass-by-reference: C++ and C# ```cpp void increment(int& n) { n += 1; } // & makes n an alias for the caller's variable int x = 5; increment(x); // x is now 6 ``` ```csharp void Replace(ref List items) { items = new List { 0 }; } Replace(ref nums); // nums now refers to the new list ``` C# also has `out` parameters (for returning extra values, as in `int.TryParse(s, out var n)`) and `in` parameters (read-only references, used for performance with large structs). In C, you get the same effect explicitly by passing a pointer. ## Go: values, with built-in references Go passes everything by value, including structs (copied in full). Slices, maps and channels, however, are small headers containing pointers, so a function receiving a slice can modify its **elements**. Appending is subtler: if `append` has to grow the underlying array, the function's slice points to new memory and the caller does not see the new elements. Return the slice from the function (`s = add(s, x)`) — the same pattern as the built-in `append`. ## The mutable default argument trap (Python) ```python def add_tag(tag, tags=[]): tags.append(tag) return tags add_tag("a") # ['a'] add_tag("b") # ['a', 'b'] — the same list as last time! ``` Default values are evaluated **once**, when the function is defined. Every call that uses the default shares that one list. Use `None` as a sentinel: ```python def add_tag(tag, tags=None): if tags is None: tags = [] tags.append(tag) return tags ``` Linters (Pylint's `dangerous-default-value`, Ruff's `B006`) flag the bug automatically. JavaScript does not have this problem — default parameters are evaluated on every call. ## Designing functions with this in mind - **Do not mutate arguments unless that is the function's job** — and when it is, name it clearly (`sort_in_place`, `appendTo`). Callers do not expect `calculate_total(order)` to change the order. - **Return new values** for transformations: `sorted(items)` rather than `items.sort()` when the caller's list must be preserved. - **Copy at boundaries** when you store objects passed in by someone else. See [deep copy vs shallow copy](https://softwaresidehustles.com/blog/deep-copy-vs-shallow-copy). - **Prefer immutable data** (tuples, frozen dataclasses, Java records with immutable fields, `Object.freeze`) for values shared widely. ## Frequently asked questions ### Is Python pass by value or pass by reference? Neither label fits perfectly. Python passes references to objects by value ("pass by object reference"). Mutations are visible to the caller; reassignments are not. ### Is JavaScript pass by reference for objects? No — it is the same model as Python. A function can change an object's properties, but cannot make the caller's variable refer to a different object. ### How do I make a function change a variable in Python? Return the new value and assign it: `x = increment(x)`. For several values, return a tuple. ### Does passing a large list to a function copy it? No. Only the reference is passed, so it is cheap regardless of size. ## Where this skill pays off Our [behavioural evaluation lab](https://softwaresidehustles.com/practice/behavioural-evaluation) includes a case where a user pushes back on a *correct* explanation of list mutability — and the AI caves. Recognising which answer is technically right, and holding to it politely, is part of paid AI evaluation work. Read [how software engineers earn money training AI models](https://softwaresidehustles.com/blog/how-software-engineers-can-earn-money-training-ai-models). ### About the author Written and reviewed by the Software Side Hustles editorial team. Code examples are executed before publication, and platform facts link to the platform's own pages with the date they were checked. --- ### Software Engineering Concepts Explained: The Fundamentals Every Developer Should Know https://softwaresidehustles.com/blog/software-engineering-concepts-explained By Software Side Hustles Editorial Team Published: 2026-10-26T09:00:00Z Updated: 2026-10-26T09:00:00Z Plain-English explanations of the concepts that come up in code reviews, interviews and debugging sessions — complexity, equality, references, mutability, recursion, concurrency, idempotency, SQL joins, HTTP and testing — each linked to an in-depth guide. **How to use this page:** each concept below gets a short, precise definition, the practical consequence you will actually meet in code, and a link to a full guide. Together they cover most of the "why did that happen?" moments in day-to-day development — and most of the fundamentals technical interviews probe. ## Time and space complexity (Big O) **Definition:** how the work or memory an algorithm needs grows as its input grows, ignoring constant factors. **Why it matters:** an O(n²) loop is invisible on test data and catastrophic on production data. The most common cause is a hidden linear operation inside a loop — `x in some_list`, `list.pop(0)`, string concatenation, or a database query per item. **Rule of thumb:** if you search a list inside a loop, you probably want a set or a dictionary. [Big O notation explained](https://softwaresidehustles.com/blog/big-o-notation-explained). ## Hash tables **Definition:** a structure that maps keys to values by computing a hash of the key to find a storage slot directly — Python's `dict` and `set`, JavaScript's `Map` and `Set`, Java's `HashMap`. **Why it matters:** lookups, inserts and deletes are O(1) on average, which is why "use a set" fixes so many slow loops. Keys must be hashable and must not change while stored — and in Java, objects used as keys need consistent `equals` and `hashCode`. [Checking for keys](https://softwaresidehustles.com/blog/check-if-a-key-exists-in-a-dictionary). ## Equality versus identity **Definition:** equality asks "do these have the same value?"; identity asks "are these the same object?". **Why it matters:** `==` on Java strings, `is` on Python integers and `===` on JavaScript objects all compare identity, and all produce bugs that pass small tests. [== vs === vs is vs equals()](https://softwaresidehustles.com/blog/equality-operators-explained). ## References, values and mutability **Definition:** in Python, JavaScript and Java, variables holding objects hold *references*. Passing an object to a function passes a copy of the reference, so the function can mutate the object but cannot rebind the caller's variable. Immutable values (numbers, strings, tuples) cannot be changed in place at all. **Why it matters:** "I changed the copy and the original changed too" and "my function modified the caller's list" both follow from this. So does Python's mutable default argument trap. [Pass by value vs pass by reference](https://softwaresidehustles.com/blog/pass-by-value-vs-pass-by-reference) · [Deep vs shallow copy](https://softwaresidehustles.com/blog/deep-copy-vs-shallow-copy). ## Floating-point numbers **Definition:** most languages store decimals in binary (IEEE 754), which cannot represent values such as 0.1 exactly. **Why it matters:** `0.1 + 0.2 != 0.3`, rounding surprises like `round(2.675, 2) == 2.67`, and money that drifts by a penny. Use decimal types or integer cents for money, and tolerances for comparisons. [Rounding and floating point](https://softwaresidehustles.com/blog/round-to-two-decimal-places). ## Recursion and the call stack **Definition:** a recursive function solves a problem by calling itself on a smaller version, until it reaches a base case. Each active call occupies a frame on the call stack, which has a limited size. **Why it matters:** a wrong base case or accidental recursion (a getter calling itself) produces stack overflows, and correct recursion can still fail on very deep input. Any recursion can be rewritten with an explicit stack or queue. [Recursion depth and stack overflow](https://softwaresidehustles.com/blog/maximum-recursion-depth-and-stack-overflow). ## Concurrency and parallelism **Definition:** concurrency is managing several tasks in overlapping time; parallelism is executing several at the same instant on multiple cores. **Why it matters:** I/O-bound work (network, disk) benefits from async or threads; CPU-bound work needs multiple cores — and in CPython, usually multiple processes because of the GIL. Shared mutable state invites race conditions and deadlocks. [Concurrency vs parallelism](https://softwaresidehustles.com/blog/concurrency-vs-parallelism) · [async/await mistakes](https://softwaresidehustles.com/blog/promise-pending-async-await). ## Idempotency **Definition:** an operation is idempotent if doing it twice has the same effect as doing it once. `PUT /users/7 {name: "Ada"}` is idempotent; `POST /payments` is not. **Why it matters:** networks fail and clients retry. Non-idempotent operations retried after a timeout create duplicate orders and double charges. Idempotency keys, upserts and "set" rather than "increment" operations make retries safe. [HTTP status codes and methods](https://softwaresidehustles.com/blog/http-status-codes-for-apis). ## Time: instants versus calendar dates **Definition:** an *instant* is a single moment worldwide (store it in UTC); a *local date or time* is a calendar value with no time zone (a birthday, an opening hour). **Why it matters:** mixing them produces off-by-one-day bugs for users in other time zones, and daylight saving time makes "add a day" differ from "add 24 hours". [Dates, times and time zones](https://softwaresidehustles.com/blog/dates-times-and-time-zones). ## Relational joins **Definition:** a join combines rows from two tables based on a condition. Inner joins keep only matches; outer joins keep unmatched rows with `NULL`s. **Why it matters:** the joins are easy; the mistakes around them are not — a `WHERE` clause that silently turns a `LEFT JOIN` into an `INNER JOIN`, `COUNT(*)` counting missing rows, totals inflated by one-to-many fan-out, and `NOT IN` returning nothing when a `NULL` is present. [SQL joins explained](https://softwaresidehustles.com/blog/sql-joins-explained). ## Injection and untrusted input **Definition:** injection happens when data is interpreted as code — SQL, shell commands, HTML. The fix is to keep data and code separate: parameterised queries, argument lists instead of shell strings, and output encoding. **Why it matters:** SQL injection remains one of the most common serious vulnerabilities, including in AI-generated code. [Preventing SQL injection](https://softwaresidehustles.com/blog/prevent-sql-injection-with-parameterized-queries). ## HTTP semantics **Definition:** HTTP status codes tell clients what happened: 2xx success, 4xx "change your request", 5xx "the server failed". **Why it matters:** clients, proxies, monitoring and retry logic all depend on the code. Returning 200 with an error body breaks them; confusing 401 with 403 confuses users. CORS is a browser-enforced layer on top. [Status codes for APIs](https://softwaresidehustles.com/blog/http-status-codes-for-apis) · [CORS errors](https://softwaresidehustles.com/blog/fix-cors-errors). ## Testing **Definition:** automated tests check behaviour against expectations. Unit tests isolate small pieces; integration tests check pieces working together. **Why it matters:** most bugs live at the edges — empty input, boundaries, nulls, time zones, rounding. Good tests are deterministic, named after behaviour and focused on those edges. [How to write good unit tests](https://softwaresidehustles.com/blog/how-to-write-good-unit-tests). ## Version control **Definition:** Git records snapshots (commits) of a project and lets branches diverge and merge. **Why it matters:** knowing the difference between rewriting history (`reset`, `amend`) and adding to it (`revert`), and how to resolve conflicts calmly, prevents lost work and broken shared branches. [Undoing commits](https://softwaresidehustles.com/blog/undo-the-last-git-commit) · [Merge conflicts](https://softwaresidehustles.com/blog/resolve-git-merge-conflicts). ## Frequently asked questions ### Which of these concepts matter most for interviews? Big O, hash tables, recursion and equality/references come up constantly in coding interviews; concurrency, idempotency, HTTP and SQL dominate system-design and backend interviews. ### How do I get better at these fundamentals? Read code critically. Predict what a snippet will do before running it, then check. Reviewing other people's (or AI models') solutions is one of the fastest ways to build intuition. ### Do I need a computer science degree to understand these? No. Every concept on this page can be learned from practice and the linked guides. What matters is being able to apply them when reading real code. ## Where this skill pays off These fundamentals are exactly what AI training platforms assess when they hire developers to evaluate model-written code — the ability to say *why* one answer is better. Read [what coding-focused AI data annotation is](https://softwaresidehustles.com/blog/what-is-coding-focused-ai-data-annotation), then try the free [practice labs](https://softwaresidehustles.com/practice) to see how your judgement compares. ### About the author Written and reviewed by the Software Side Hustles editorial team. Code examples are executed before publication, and platform facts link to the platform's own pages with the date they were checked. --- ### SQL Joins Explained: INNER, LEFT, RIGHT and FULL — Plus the Mistakes That Give Wrong Results https://softwaresidehustles.com/blog/sql-joins-explained By Software Side Hustles Editorial Team Published: 2026-10-26T09:00:00Z Updated: 2026-10-26T09:00:00Z What each SQL join returns, with one small dataset used throughout — and the silent bugs that cause wrong reports: WHERE clauses that cancel a LEFT JOIN, COUNT(*) counting missing rows, fan-out inflating SUMs and NOT IN with NULLs. **Quick answer:** `INNER JOIN` returns only rows that match in both tables. `LEFT JOIN` returns every row from the left table, with `NULL`s where the right table has no match. `RIGHT JOIN` is the mirror image, and `FULL OUTER JOIN` keeps unmatched rows from both sides. Most join bugs come not from choosing the wrong join but from what happens next — a `WHERE` on the right table, `COUNT(*)`, or duplicated rows. ## The example data ```sql -- customers -- orders -- id | name -- id | customer_id | total -- 1 | Ada -- 10 | 1 | 50 -- 2 | Linus -- 11 | 1 | 70 -- 3 | Grace -- 12 | 2 | 30 -- -- 13 | NULL | 90 (guest checkout) ``` Grace has no orders. Order 13 has no customer. ## INNER JOIN: only matches ```sql SELECT c.name, o.id, o.total FROM customers c JOIN orders o ON o.customer_id = c.id; ``` | name | id | total | |---|---|---| | Ada | 10 | 50 | | Ada | 11 | 70 | | Linus | 12 | 30 | Grace disappears (no orders) and so does order 13 (no customer). `JOIN` on its own means `INNER JOIN`. ## LEFT JOIN: everything from the left ```sql SELECT c.name, o.id, o.total FROM customers c LEFT JOIN orders o ON o.customer_id = c.id; ``` | name | id | total | |---|---|---| | Ada | 10 | 50 | | Ada | 11 | 70 | | Linus | 12 | 30 | | Grace | NULL | NULL | Use `LEFT JOIN` whenever the question includes "…including those with none": customers including those with zero orders, products including those never sold. ## RIGHT, FULL OUTER and CROSS JOIN - **`RIGHT JOIN`** keeps every row from the right table. `customers RIGHT JOIN orders` includes order 13 with a `NULL` name. Most teams rewrite it as a `LEFT JOIN` with the tables swapped, which reads more naturally. - **`FULL OUTER JOIN`** keeps unmatched rows from both: Grace *and* order 13. PostgreSQL, SQL Server, Oracle and SQLite (3.39+) support it; MySQL does not, so you emulate it with a `LEFT JOIN` `UNION` a `RIGHT JOIN`. - **`CROSS JOIN`** pairs every row with every row (3 customers × 4 orders = 12 rows). Useful for generating combinations such as every product for every month; disastrous when it happens accidentally through a missing `ON` condition. - **Self join** joins a table to itself, e.g. employees to their managers: `FROM employees e LEFT JOIN employees m ON m.id = e.manager_id`. ## Mistake 1: a WHERE clause that cancels the LEFT JOIN "All customers, with their orders over 40": ```sql SELECT c.name, o.id FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.total > 40; -- Grace and Linus vanish ``` For Grace, `o.total` is `NULL`, and `NULL > 40` is not true, so `WHERE` filters her out. Linus's only order is 30, so he goes too. The `LEFT JOIN` has quietly become an `INNER JOIN`. Put conditions on the right-hand table **in the `ON` clause**: ```sql SELECT c.name, o.id FROM customers c LEFT JOIN orders o ON o.customer_id = c.id AND o.total > 40; -- Ada 10, Ada 11, Grace NULL, Linus NULL ``` Rule of thumb: conditions about *which right rows to attach* go in `ON`; conditions about *which final rows to keep* go in `WHERE`. ## Mistake 2: COUNT(*) counts the missing row "Orders per customer, including zero": ```sql SELECT c.name, COUNT(*) AS orders -- Grace: 1 (wrong) FROM customers c LEFT JOIN orders o ON o.customer_id = c.id GROUP BY c.name; SELECT c.name, COUNT(o.id) AS orders -- Grace: 0 (right) FROM customers c LEFT JOIN orders o ON o.customer_id = c.id GROUP BY c.name; ``` `COUNT(*)` counts rows, and Grace has one row (full of `NULL`s). `COUNT(column)` ignores `NULL`s. Similarly, `SUM(o.total)` returns `NULL`, not `0`, for Grace — wrap it: `COALESCE(SUM(o.total), 0)`. ## Mistake 3: fan-out inflates totals Joining a one-to-many relationship repeats the "one" side for each match. Aggregating after joining two separate one-to-many tables multiplies rows: ```sql -- Each customer has several orders AND several support tickets SELECT c.name, SUM(o.total), COUNT(t.id) FROM customers c LEFT JOIN orders o ON o.customer_id = c.id LEFT JOIN tickets t ON t.customer_id = c.id GROUP BY c.name; -- totals multiplied by the number of tickets ``` Aggregate each child table in a subquery or CTE first, then join the results: ```sql WITH order_totals AS ( SELECT customer_id, SUM(total) AS revenue FROM orders GROUP BY customer_id ), ticket_counts AS ( SELECT customer_id, COUNT(*) AS tickets FROM tickets GROUP BY customer_id ) SELECT c.name, COALESCE(ot.revenue, 0), COALESCE(tc.tickets, 0) FROM customers c LEFT JOIN order_totals ot ON ot.customer_id = c.id LEFT JOIN ticket_counts tc ON tc.customer_id = c.id; ``` If adding `DISTINCT` "fixes" a report, suspect fan-out — `DISTINCT` usually hides the problem rather than solving it. ## Mistake 4: NOT IN with NULLs returns nothing "Customers with no orders": ```sql SELECT name FROM customers WHERE id NOT IN (SELECT customer_id FROM orders); -- returns no rows at all! ``` Order 13 has `customer_id = NULL`. `x NOT IN (1, 2, NULL)` can never be true, because comparing with `NULL` is unknown. Use `NOT EXISTS`, which handles `NULL`s correctly: ```sql SELECT name FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id); -- Grace ``` The "anti-join" form `LEFT JOIN … WHERE o.id IS NULL` also works. ## Joins and performance Index the columns you join on, especially foreign keys (`orders.customer_id`); PostgreSQL does not create those indexes automatically. Use `EXPLAIN` (or `EXPLAIN ANALYZE`) to see whether the database uses a nested loop, hash or merge join. And avoid issuing one query per row from application code — the "N+1 queries" problem — when a single join would do. See [Big O notation explained](https://softwaresidehustles.com/blog/big-o-notation-explained). ## Frequently asked questions ### What is the difference between JOIN and INNER JOIN? None. `INNER` is optional. ### Is LEFT JOIN the same as LEFT OUTER JOIN? Yes. `OUTER` is optional. ### Which is faster, a JOIN or a subquery? Modern optimisers often produce the same plan for both. Write the clearest query, then check `EXPLAIN` if it is slow. ### Why does my join return more rows than the table has? The join condition matches several rows on the other side (one-to-many), or the `ON` condition is incomplete and creates a partial cross join. ## Where this skill pays off Our [response evaluation lab](https://softwaresidehustles.com/practice/response-evaluation) includes "count orders per customer, including zero" — a request where AI answers regularly reach for `COUNT(*)`. Our free [VIP customers report review](https://softwaresidehustles.com/practice/code-review) tests similar reasoning. Catching wrong-but-plausible SQL is valuable paid evaluation work; see [how to evaluate AI-generated code](https://softwaresidehustles.com/blog/how-to-evaluate-ai-generated-code). ### About the author Written and reviewed by the Software Side Hustles editorial team. Code examples are executed before publication, and platform facts link to the platform's own pages with the date they were checked. --- ## Error messages and debugging ### How to Fix "TypeError: Cannot read properties of undefined" in JavaScript https://softwaresidehustles.com/blog/cannot-read-properties-of-undefined By Software Side Hustles Editorial Team Published: 2026-10-26T09:00:00Z Updated: 2026-10-26T09:00:00Z What "Cannot read properties of undefined (reading 'x')" and its null twin actually mean, the six situations that cause it in browsers, React and Node.js, and how to fix the cause instead of hiding it. **Quick answer:** `Cannot read properties of undefined (reading 'map')` means the value **to the left** of `.map` is `undefined`. The bug is not in `map` — it is wherever that value was supposed to come from. Find which expression is undefined (the stack trace gives the line), then work out why: data not loaded yet, a misspelt property, a different API response shape, or a missing element. Optional chaining (`?.`) hides the symptom; fix the cause first. ## What the error means ```javascript const user = undefined; user.name; // TypeError: Cannot read properties of undefined (reading 'name') ``` The message names the property you tried to read (`'name'`), not the variable that was undefined. In `order.customer.address.city`, an error "reading 'city'" means `order.customer.address` was undefined — the problem is one step to the left. You will see the same bug phrased differently depending on the environment: | Environment | Message | |---|---| | Chrome, Edge, Node.js (current) | `Cannot read properties of undefined (reading 'name')` | | Older Chrome / Node.js | `Cannot read property 'name' of undefined` | | Firefox | `user is undefined` | | Safari | `undefined is not an object (evaluating 'user.name')` | | Any, with `null` | `Cannot read properties of null (reading 'name')` | | Writing instead of reading | `Cannot set properties of undefined (setting 'name')` | ## Cause 1: data that has not loaded yet (React, Vue, async code) The most common case in front-end code: ```jsx function Orders() { const [orders, setOrders] = useState(); // initially undefined useEffect(() => { fetchOrders().then(setOrders); }, []); return
    {orders.map((o) =>
  • {o.total}
  • )}
; // First render: Cannot read properties of undefined (reading 'map') } ``` The component renders once *before* the fetch completes. Fix it by giving state the right empty value, and by rendering loading states deliberately: ```jsx const [orders, setOrders] = useState([]); // or if (!orders) return

Loading…

; ``` The same pattern appears in Node.js when you forget to `await` — the variable holds a Promise, and `promise.data` is `undefined`. See [why your async function returns Promise pending](https://softwaresidehustles.com/blog/promise-pending-async-await). ## Cause 2: the property name or path is wrong ```javascript const res = await fetch("/api/user").then((r) => r.json()); res.data.user.firstName; // API actually returns { user: { first_name: ... } } ``` Log the real shape before guessing: `console.log(JSON.stringify(res, null, 2))`. Common mismatches are `snake_case` versus `camelCase`, an extra `data` wrapper added by Axios (`response.data`), and arrays where you expected an object (`res.users[0].name`, not `res.users.name`). ## Cause 3: an array index that does not exist ```javascript const first = items[0].name; // fails when items is [] const last = items[items.length].name; // off by one: should be length - 1 ``` Arrays return `undefined` for missing indexes instead of throwing, so the error appears one step later. Check the length, or use `items.at(-1)` for the last element. See [off-by-one and index out of range errors](https://softwaresidehustles.com/blog/index-out-of-range-off-by-one). ## Cause 4: the DOM element was not found (the `null` version) ```javascript document.querySelector("#submit").addEventListener("click", send); // TypeError: Cannot read properties of null (reading 'addEventListener') ``` `querySelector` returns `null` when nothing matches. Either the selector is wrong (`#submit` vs `.submit`, a typo), or the script ran **before the HTML was parsed** because it sits in `` without `defer`. Use `