HackIndia Logo
HackathonsNewsSkillsGrowth
HackIndia LogoContact: +91 9910125804

General

  • Companies
  • Colleges
  • Board of Advisors
  • Brand Ambassadors
  • FAQ
  • Contact
  • Report a Bug

Hackathons

  • Upcoming Hackathons
  • Judges
  • Mentors
  • Partners
  • Participating Colleges
  • Testimonials

Resources

  • About Us
  • Branding
  • Latest News
  • Growth
  • Skills
  • Builders
  • Ecosystem
  • Forum
  • Ideas
  • Prompt Optimizer
  • Games

© 2026 HackIndia. All rights reserved.

Privacy PolicyTerms of ServiceCode of ConductSitemap

Build 2.139 · 05 Nov 2026, 10:27 UTC

    HackIndia
    HackathonsNewsInternshipsSkillsGrowthPro Perks
    ← Write JavaScript Without Guessing

    All the reading

    JavaScript

    8 lessons, about 36 minutes. The check's questions come from these.

    Contents
    Reading code and checking data
    1. 1. Stop Copying, Start Reading
    2. 2. Values, Types, And Checks
    3. 3. Arrays And Objects Together
    Functions and array work
    1. 4. Functions And Scope
    2. 5. Array Methods That Matter
    Async code and project shape
    1. 6. Async, Await, And Fetch
    2. 7. Modules And Project Shape
    3. 8. Ship The Repo Project

    Reading code and checking data

    1. Stop Copying, Start Reading

    4 min

    In 30 seconds
    • Read JavaScript by naming inputs, outputs, and data changes.
    • Use AI as a reviewer, not a copy-paste machine.
    • Keep a tiny notes file so your repo shows clear thinking.
    Key point

    One habit

    Before you run any JavaScript you copied, explain what each line receives, changes, and returns. If you cannot explain it, it is not your code yet.

    Why this matters

    In hackathons, copied snippets often work for the demo and fail during judging. You change one field name, one API response, or one button id, and the app breaks.

    Recruiters do not expect perfect code from a college project. They do expect code you can explain. This track starts there.

    Your to-do

    Read any snippet

    Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.

    0 of 5 done

    Example

    Read this code

    Do not start by asking, “Will this work?” Start by asking, “What does this need, and what does it produce?”

    const cart = [
      { name: "Notebook", price: 60, qty: 2 },
      { name: "Pen", price: 10, qty: 5 }
    ];
    
    let total = 0;
    
    for (const item of cart) {
      total = total + item.price * item.qty;
    }
    
    console.log(total);

    2. Values, Types, And Checks

    4 min

    In 30 seconds
    • Tell what type a JavaScript value is before using it.
    • Convert form and API values safely instead of hoping they work.
    • Add small checks so wrong input fails early and clearly.
    Key point

    One habit

    Before you use a value, ask two questions: what type is it, and can it be missing? Most JavaScript bugs in student projects start when code assumes an input is a number, string, or object without checking.

    Values have types

    JavaScript values can be strings, numbers, booleans, undefined, null, objects, and functions. You meet them when reading form inputs, URL params, localStorage, and API responses.

    Use typeof for a first check. Remember that form inputs usually arrive as strings, even when the user typed 499. That matters if you are building a fee splitter, event budget app, or UPI expense tracker.

    Example

    Check before using

    This is the kind of small guard code recruiters like to see. It shows you know what your code expects.

    const amountInput = "499";
    const nameInput = "Asha";
    
    const amount = Number(amountInput);
    
    if (typeof nameInput !== "string" || nameInput.trim() === "") {
      throw new Error("Name is required");
    }
    
    if (Number.isNaN(amount) || amount <= 0) {
      throw new Error("Amount must be a positive number");
    }
    
    console.log(`${nameInput.trim()} paid ₹${amount}`);

    3. Arrays And Objects Together

    5 min

    In 30 seconds
    • Store related data as objects, and lists of those objects as arrays.
    • Read, add, update, and remove items without guessing at the shape.
    • Create sample data for your hackathon repo that later works with fetch.
    Key point

    The core shape

    Most JavaScript project data is not just an array or just an object. It is usually an array of objects.

    An object describes one thing. An array holds many things. If you get this shape right, your code becomes easier to read, test, and later replace with API data.

    Example

    Project data example

    Think of a hackathon project that tracks college events. One event is an object. The full event list is an array.

    This same shape could later come from fetch. For now, keep it as sample data in your code.

    const events = [
      {
        id: 1,
        title: "AI Workshop",
        college: "SRM Chennai",
        fee: 0,
        tags: ["ai", "beginner"],
        registered: true
      },
      {
        id: 2,
        title: "UPI App Build Sprint",
        college: "Pune Institute",
        fee: 199,
        tags: ["fintech", "javascript"],
        registered: false
      }
    ];
    
    console.log(events[0].title);        // AI Workshop
    console.log(events[1].tags[0]);      // fintech

    Read the shape first

    Functions and array work

    4. Functions And Scope

    4 min

    In 30 seconds
    • Write small functions that do one clear job.
    • Use scope to avoid hidden bugs and messy globals.
    • Prepare functions that your repo can later export as modules.
    Key point

    One job only

    A good function has one clear job. You should be able to name it with a verb phrase like formatPrice, findTopScore, or buildStudentCard.

    If the name needs “and”, split the function. This makes your hackathon repo easier to read during judging or internship review.

    Why functions matter

    Functions turn repeated code into a reusable tool. Instead of copying the same 8 lines in three places, you write it once and call it when needed.

    This also makes testing easier. You can pass sample data into a function and check the returned result before connecting it to the page or an API.

    Example

    Start with data

    Keep the function focused on input and output. Do not make it depend on random outside variables unless it has to.

    Async code and project shape

    6. Async, Await, And Fetch

    4 min

    In 30 seconds
    • Use fetch to request real API data from JavaScript.
    • Use async/await to write readable code that waits safely.
    • Handle loading, success, and error states in your project.
    Key point

    One thing to remember

    fetch starts a network request. await pauses only inside an async function until that promise settles.

    Your page should not assume the internet works. Always handle loading, success, and error states.

    What fetch returns

    fetch(url) does not directly give you the data. It gives you a Response object.

    For most APIs, call await response.json() to read the JSON body. Also check response.ok so bad status codes do not look like success.

    Example

    Small API example

    This function gets a random programming joke from a public API. You can use the same shape for weather, college events, UPI expense logs from your own backend, or hackathon project data.

    10 questions, 7 to pass.

    Sign in to take the test

    What you should see

    Input: cart is an array of objects. Each object needs price and qty as numbers. name is not used in the calculation.

    Output: total becomes 170, then it is printed. The loop changes total each time. If price comes as "60" from a form, you need to check it before trusting the result. You will learn those checks later.

    Tip

    Use AI well

    AI is useful for reading code. Paste a small snippet and ask for a line-by-line explanation, inputs, outputs, and possible failure points.

    Then verify the answer. AI may assume data types that are not true in your app. Check variable names, browser console errors, and sample data yourself.

    Prompt:
    Explain this JavaScript in simple terms.
    List:
    1. Inputs
    2. Outputs
    3. What changes
    4. What can break
    Do not rewrite the code yet.
    Common mistake

    Common copying mistake

    Beginners copy a solution and change names randomly: data becomes result, result becomes item, item becomes x. After that, the code is harder to debug than the original.

    Better: change names towards meaning. If the value is a list of students, call it students. If it is one student, call it student.

    Your to-do

    Do this now

    Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.

    0 of 5 done

    Common mistake

    Common trap

    Do not trust truthy and falsy checks for everything. They are useful, but they can hide valid values.

    For example, 0 is falsy. If your app allows a zero balance, if (!balance) will treat it like a missing value. Be specific when the value matters.

    const balance = 0;
    
    // Too broad: treats 0 as missing
    if (!balance) {
      console.log("Balance missing");
    }
    
    // Better: checks only for no value
    if (balance === null || balance === undefined) {
      console.log("Balance missing");
    }
    Your to-do

    Safe conversion flow

    Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.

    0 of 5 done

    Tip

    Use AI carefully

    You can ask ChatGPT, Gemini, or Claude to write validation checks for a function. Paste the function and say what inputs are allowed.

    Then check the answer yourself. Look for vague checks like if (value), missing Number.isNaN, and errors that do not tell you what went wrong.

    Example

    Small reusable check

    You do not need a library for basic validation. A clear helper function is enough for many hackathon projects.

    function getPositiveNumber(value, fieldName) {
      if (value === null || value === undefined) {
        throw new Error(`${fieldName} is required`);
      }
    
      const numberValue = Number(value);
    
      if (Number.isNaN(numberValue) || numberValue <= 0) {
        throw new Error(`${fieldName} must be a positive number`);
      }
    
      return numberValue;
    }
    
    const ticketPrice = getPositiveNumber("149", "Ticket price");
    console.log(ticketPrice + 1);
    Your to-do

    Do this now

    Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.

    0 of 5 done

    Before writing logic, ask: what is one item, and what is the list? Draw it in comments if needed.

    Use names that show the shape. event is one object. events is an array. This small habit prevents many bugs.

    Your to-do

    Common operations

    Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.

    0 of 5 done

    Example

    Add and update

    In real projects, users add or change data. Practise that with sample objects before you connect an API.

    Notice that the update uses id, not index. Index can change when the list is sorted or filtered.

    const events = [
      { id: 1, title: "AI Workshop", fee: 0, registered: true },
      { id: 2, title: "UPI App Build Sprint", fee: 199, registered: false }
    ];
    
    const newEvent = {
      id: 3,
      title: "Resume Review Camp",
      fee: 49,
      registered: false
    };
    
    const updatedEvents = [...events, newEvent];
    
    const eventIdToRegister = 2;
    
    const afterRegistration = updatedEvents.map((event) => {
      if (event.id === eventIdToRegister) {
        return { ...event, registered: true };
      }
    
      return event;
    });
    
    console.log(afterRegistration);
    Common mistake

    Do not mix shapes

    A common beginner mistake is changing the data shape halfway. For example, fee is a number in one object and "free" as text in another.

    Pick one shape and stay with it. Use fee: 0 for free events. Use registered: true or false, not "yes" and "no".

    Tip

    Use AI carefully

    You can ask ChatGPT or Gemini to create sample data for your project. Ask for an array of objects with exact fields.

    Then check every object yourself. Make sure field names match, ids are unique, and values use the same types.

    Prompt:
    Create 8 sample events for a JavaScript college hackathon app.
    Return only a JavaScript array of objects.
    Each object must have: id number, title string, college string, fee number, tags array of strings, registered boolean.
    Your to-do

    Do this now

    Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.

    0 of 5 done

    This example takes an order object and returns a display string for a UPI-style payment summary.

    const order = {
      id: "ORD-104",
      customer: "Asha",
      amount: 249,
      paid: true
    };
    
    function formatPaymentStatus(order) {
      if (order.paid) {
        return `${order.customer} paid ₹${order.amount}`;
      }
    
      return `${order.customer} has not paid yet`;
    }
    
    console.log(formatPaymentStatus(order));

    Parameters beat guessing

    A parameter is the value a function asks for. An argument is the actual value you pass when you call it.

    Use parameters instead of making the function read from a variable outside. Then the function is easier to reuse in another file later.

    Common mistake

    Avoid global leaks

    A global variable is available everywhere in the file. It feels easy, but it can create bugs when two functions change the same value.

    Prefer const and let inside the smallest useful scope. If a value belongs only inside a function, declare it inside that function.

    let total = 0; // Avoid using this as shared state unless needed
    
    function addToCart(price) {
      const updatedTotal = total + price;
      return updatedTotal;
    }
    
    console.log(addToCart(99));
    Tip

    Return, do not print

    console.log is useful while checking your work. But most functions should return a value, not just print it.

    A returned value can be used by another function, shown on a page, saved in an object, or sent later with fetch.

    Example

    Scope in practice

    Variables declared inside a function cannot be used outside it. That is function scope.

    Variables declared inside if, for, or other blocks with const or let stay inside that block. That is block scope.

    function getPassMessage(score) {
      const passingScore = 40;
    
      if (score >= passingScore) {
        const message = "Passed";
        return message;
      }
    
      return "Try again";
    }
    
    console.log(getPassMessage(72));
    // console.log(message); // Error: message is not available here
    Your to-do

    Do this now

    Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.

    0 of 5 done

    5. Array Methods That Matter

    5 min

    In 30 seconds
    • Pick map, filter, find, some, reduce, and sort for the right job.
    • Turn arrays of objects into UI-ready data without messy loops.
    • Write array code that is easy to test and explain in your repo.
    Key point

    Choose by result

    Do not start with the method name. Start with the result you need.

    Use map to change every item. Use filter to keep some items. Use find to get one item. Use some to check if at least one item matches. Use reduce when you need one final value from many items.

    Why this matters

    Hackathon projects usually get data as arrays of objects: events, expenses, tasks, colleges, products, users, or API results.

    If your code uses clear array methods, a reviewer can read your logic fast. That helps when your GitHub repo is checked for internship shortlists.

    Your to-do

    Pick the method

    Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.

    0 of 5 done

    Example

    Common project data

    Imagine a simple student event planner. Your project may fetch this later. For now, practise on local data.

    const events = [
      { id: 1, title: "AI Meetup", city: "Bengaluru", fee: 0, seats: 12 },
      { id: 2, title: "JS Workshop", city: "Pune", fee: 299, seats: 0 },
      { id: 3, title: "Design Jam", city: "Bengaluru", fee: 149, seats: 5 }
    ];
    
    const eventCards = events.map((event) => ({
      id: event.id,
      label: `${event.title} - ₹${event.fee}`,
      available: event.seats > 0
    }));
    
    const freeEvents = events.filter((event) => event.fee === 0);
    
    const puneEvent = events.find((event) => event.city === "Pune");
    
    const hasSoldOutEvent = events.some((event) => event.seats === 0);
    
    const totalSeats = events.reduce((sum, event) => sum + event.seats, 0);
    
    console.log(eventCards);
    console.log(freeEvents);
    console.log(puneEvent);
    console.log(hasSoldOutEvent);
    console.log(totalSeats);
    Common mistake

    Do not mutate blindly

    Methods like map and filter return new arrays. That is usually safer for project code because your original data stays unchanged.

    sort changes the original array. If you need sorting, copy first.

    const sortedByFee = [...events].sort((a, b) => a.fee - b.fee);
    
    console.log(sortedByFee);
    console.log(events); // original order is still safe
    Tip

    Name the callback

    A good callback name makes your code read like English. This is better than writing short names everywhere.

    If AI gives you code with x, y, item1, or data2, rename them before you commit.

    const bengaluruEvents = events.filter((event) => event.city === "Bengaluru");
    
    const titles = bengaluruEvents.map((event) => event.title);

    Check AI output

    You can ask an AI tool to suggest array methods for a task. Do not paste the answer directly.

    Check three things: does the method return the shape you need, does it mutate the original array, and are edge cases handled, like an empty array or no match from find.

    Your to-do

    Do this now

    Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.

    0 of 5 done

    Notice the order: fetch, check, parse JSON, return clean data.

    async function getJoke() {
      const url = "https://official-joke-api.appspot.com/random_joke";
    
      const response = await fetch(url);
    
      if (!response.ok) {
        throw new Error(`Request failed: ${response.status}`);
      }
    
      const data = await response.json();
    
      return {
        setup: data.setup,
        punchline: data.punchline
      };
    }
    Your to-do

    Show it on page

    Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.

    0 of 5 done

    const resultBox = document.querySelector("#result");
    
    async function showJoke() {
      resultBox.textContent = "Loading...";
    
      try {
        const joke = await getJoke();
        resultBox.textContent = `${joke.setup} ${joke.punchline}`;
      } catch (error) {
        resultBox.textContent = "Could not load data. Check your internet and try again.";
        console.error(error);
      }
    }
    
    showJoke();
    Common mistake

    Do not guess timing

    A common bug is using data before it has arrived. If a function uses await, mark it async and await it where you need the result.

    Do not write code that depends on a network result outside the async flow.

    // Wrong: jokePromise is not the final joke data
    const jokePromise = getJoke();
    console.log(jokePromise.setup);
    
    // Right
    const joke = await getJoke();
    console.log(joke.setup);
    Tip

    Use AI carefully

    Ask AI to write the first fetch function, not the whole project. Then check three things yourself: the API URL, response.ok handling, and the exact JSON field names.

    If the API returns data.setup but the AI writes data.title, your app will show undefined. Open the API URL in the browser once and inspect the JSON.

    Prompt you can use:
    Write a JavaScript async function that fetches JSON from this API URL: <paste URL>.
    It should check response.ok, parse JSON, return only these fields: <field names>.
    Add try/catch in the UI function, not inside the data function.
    Your to-do

    Do this now

    Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.

    0 of 5 done

    7. Modules And Project Shape

    5 min

    In 30 seconds
    • Split a JavaScript project into small files with clear jobs.
    • Use import and export so files can share functions and data.
    • Shape your repo so another builder can run it without guessing.
    Key point

    One idea

    A module is a JavaScript file with one clear job. Export what other files need, and import it where you use it.

    Good project shape makes your code easier to read in a hackathon review. It also makes your README simpler.

    Why shape matters

    When all your code sits in one app.js file, every change feels risky. You scroll too much. You also mix UI, data fetching, and helper logic in one place.

    A recruiter or judge may spend only a few minutes in your repo. Clear files help them see that you understand the code, not just the final screen.

    Your to-do

    Use simple folders

    Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.

    0 of 5 done

    Example

    Small project shape

    For a project that shows public data, this shape is enough. Do not create extra folders just to look professional.

    my-js-project/
      index.html
      README.md
      src/
        main.js
        api.js
        render.js
        helpers.js
    Example

    Export and import

    Use named exports when a file has several useful functions. Use the exact exported name when importing.

    // src/helpers.js
    export function formatRupees(amount) {
      return `₹${Number(amount).toFixed(0)}`;
    }
    
    export function isValidItem(item) {
      return item && item.name && typeof item.price === 'number';
    }
    
    // src/render.js
    import { formatRupees, isValidItem } from './helpers.js';
    
    export function renderItems(items, container) {
      container.innerHTML = '';
    
      items.filter(isValidItem).forEach((item) => {
        const row = document.createElement('p');
        row.textContent = `${item.name}: ${formatRupees(item.price)}`;
        container.appendChild(row);
      });
    }
    Example

    Connect in main

    Your main.js should read like the story of the app. Get elements. Fetch data. Render it. Handle errors.

    // src/api.js
    export async function getProducts() {
      const response = await fetch('https://fakestoreapi.com/products?limit=5');
    
      if (!response.ok) {
        throw new Error('Could not load products');
      }
    
      return response.json();
    }
    
    // src/main.js
    import { getProducts } from './api.js';
    import { renderItems } from './render.js';
    
    const app = document.querySelector('#app');
    
    async function startApp() {
      try {
        const products = await getProducts();
        const items = products.map((product) => ({
          name: product.title,
          price: product.price * 83
        }));
    
        renderItems(items, app);
      } catch (error) {
        app.textContent = error.message;
      }
    }
    
    startApp();
    Common mistake

    Common module mistake

    If you use import in the browser, your script tag must use type="module". Without it, the browser will not understand import and export.

    Also include the .js extension in local imports, like './api.js'. This avoids path errors when running directly in the browser.

    <script type="module" src="./src/main.js"></script>
    Tip

    Use AI carefully

    You can ask AI to suggest a project structure. Then check if every file has a real job and if the imports match the exports.

    Reject structures with too many folders for a small hackathon app. Simple and readable beats fancy.

    Prompt:
    I have a small browser JavaScript app that fetches data and renders a list.
    Suggest a simple file structure using modules.
    Keep it beginner-friendly and explain what each file does.
    Your to-do

    Do this now

    Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.

    0 of 5 done

    8. Ship The Repo Project

    5 min

    In 30 seconds
    • Turn your JavaScript app into a repo that a reviewer can run.
    • Write a README with setup, features, and what JS concepts you used.
    • Do a final proof check before submitting your HackIndia project.
    Key point

    One idea

    Your project is not shipped when it works on your laptop. It is shipped when a stranger can open the repo, understand it, run it, and see the JavaScript skills you used.

    Your to-do

    Final repo check

    Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.

    0 of 5 done

    Example

    README skeleton

    Your README should answer three questions fast: what is it, how do I run it, and where is the JavaScript skill visible.

    Keep it honest. If one feature is incomplete, say so in a small “Known issues” section instead of hiding it.

    # Campus Event Finder
    
    A small JavaScript app that fetches event data and helps students filter events by category.
    
    ## Features
    
    - Fetches event data from an API or local JSON file
    - Shows events as cards
    - Filters events by category
    - Handles loading and error states
    
    ## JavaScript used
    
    - Modules: code is split across files in `src/`
    - Functions: rendering, filtering, and API calls are separate
    - Arrays and objects: event data is stored and filtered as objects in an array
    - fetch and async/await: data is loaded asynchronously
    
    ## How to run
    
    1. Clone the repo
    2. Open the project folder
    3. Start a local server
    
    ```bash
    npx serve .
    ```
    
    4. Open the local URL shown in the terminal
    
    ## Known issues
    
    - Data is not saved after refresh
    - Search works only by category
    Common mistake

    Common mistake

    Do not submit only a live demo link. A recruiter or hackathon reviewer needs the repo too.

    Also avoid vague READMEs like “run the project”. Say the exact command. If your app needs an API key, explain where to add it and never commit the key.

    Tip

    Use AI carefully

    You can ask ChatGPT, Gemini, or Claude to review your README and repo structure. Ask it to check clarity, not to invent features you did not build.

    Verify every suggestion. AI may add fake commands, fake API details, or claim your code uses a concept that is not actually present.

    Prompt:
    Review this README for a beginner JavaScript hackathon project. Check if a reviewer can run it from scratch. Do not add features that are not mentioned. Point out missing setup steps, unclear commands, and places where the JavaScript skills are not visible.
    Your to-do

    Submission proof

    Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.

    0 of 5 done

    Example

    Good commit message

    Your last commit should tell a human what changed. Avoid messages like “final final” or “changes”.

    Small, clear commits make the repo easier to read later during internship shortlisting.

    git status
    git add .
    git commit -m "Add README and final project setup steps"
    git push
    Your to-do

    Do this now

    Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.

    0 of 5 done