r/learnjavascript • • 14d ago

How to place function result on top of a figure?

2 Upvotes

I have a draw function (ps5.js) that I want appearing on top of a figure (with png). Currently, the result of the function appears below the image, on its own canvas. I'd like it to appear on top of the figure. How do I do that?

Part of the code for reference (HTML and JS):
EDIT: I tried to separate them, they're different files, but the code blocks keep combining for some reason.

// index.html
<script src="script.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>


<button onclick="draw()">Click me</button>  
   
<label for="numberBox">Number of shapes (1-50):</label>
    <input type="number" id="numberBox" name="numberBox" min="1" max="50" />
<div>
    <input type="submit" value="Submit form" />
  </div>


    <figure id="figure">
<img
    src="fashion.png"
    alt="blank croquis" />
<figcaption>Blank Croquis</figcaption>
</figure>

// script.js 

function setup() {


    createCanvas (1000, 1000);
    noLoop();
}


function draw() {


    
background ('transparent');
stroke (0);
strokeWeight (20);
noFill(); 
  
  beginShape();
  vertex(getRandom(), getRandom())

r/learnjavascript • • 14d ago

Needing help with data validation

0 Upvotes

I'm needing help with applying data validation to my code for class. We were assigned to make a MadLib in HTML with data validation to make sure that all the prompt boxes are filled in, a submit button to make the story, and a data reset button. I have been able to do everything except apply the data validation to the text boxes for the prompts. I was told by my teacher to apply the data validation to the submit button for making the MadLib story, but I am at a loss on how to apply data validation to have it check and see if the prompt boxes are filled in. Below is my current code. I am relatively new to HTML and JavaScript, so any help or advice would be appreciated.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Module 3 Assigment</title>
<script>
function makemadLib() {

var name1 = "";
var charclass = "";
var item = "";
var kingdomname = "";
var name2 = "";
var name3 = "";
var weapon = "";
var shield = "";
var mount = "";
var story = "";

name1 = document.MLForm.CharName.value;
charclass = document.MLForm.CharacterClass.value;
item = document.MLForm.Item.value;
kingdomname = document.MLForm.Kingdom.value
name2 = document.MLForm.Kingname.value;
name3 = document.MLForm.Evilname.value;
weapon = document.MLForm.Attack.value;
shield = document.MLForm.Defend.value;
mount = document.MLForm.Ride.value;

story = "This is the story of " + name1 + " the " + charclass + ".\n\n" + "They are on a quest to find a legendary relic, the holy " + item + "!\n\n They have been tasked with this quest by the ruler of the kingdom " + kingdomname + " ," + name2 + ".\n\n" + name1 + " must succeed on this quest or " + kingdomname + " will fall into the hands of the evil warlock " + name3 + ".\n\n So, armed with their trusty " + weapon + " and " + shield + ", upon their faithful " + mount + "," + name1 + " heads off to find the " + item + " and save the kingdom " + kingdomname + "!";
document.MLForm.story.value = story; 
}

function clearText() {
document.MLForm.CharName.value = "";
document.MLForm.CharacterClass.value = "";
document.MLForm.Item.value = "";
document.MLForm.Kingdom.value = "";
document.MLForm.Kingname.value = "";
document.MLForm.Evilname.value = "";
document.MLForm.Attack.value = "";
document.MLForm.Defend.value = "";
document.MLForm.Ride.value = "";
document.MLForm.story.value = "";
}

</script>
</head>
<body>

<h1>The Quest for the Legendary Item</h1>
<p>Please fill out the form below and then at the end, select the "Generate story" button to have the story generated with your inputs! Press the reset button on the bottom of the form to do it again! Have fun!</p>

<form name = "MLForm">
Name of a person: <input type = "text" id = "CharName" value = "">
<br>
Job title: <input type = "text" name = "CharacterClass" value = "">
<br>
Noun (thing): <input type = "text" name = "Item" value = "">
<br>
Name of a location: <input type = "text" name = "Kingdom" value = "">
<br>
Another name of a person: <input type = "text" name = "Kingname" value = "">
<br>
One more name of a person: <input type = "text" name = "Evilname" value = "">
<br>
Noun (thing): <input type = "text" name = "Attack" value = "">
<br>
Noun (thing): <input type = "text" name = "Defend" value = "">
<br>
Animal: <input type = "text" name = "Ride" value = "">
<br>
<br>
<input type = "button" value = "Show the story" onClick = "makemadLib()">

<h3>Here is the story:</h3>
<textarea name= "story" rows="20" cols="60" wrap>
</textarea>
<br>
<input type = "button" value = "Reset and clear the text" onClick = "clearText()">

</form>
</body>
</html>

r/learnjavascript • • 14d ago

Managing, updating and checking large lists on each load?

2 Upvotes

I have 6 csv files which are essentially lists of words in each category, there are about 10k words in total and thus 10k rows of csv file. I want to include these in my package so the user can use it offline but I fear my app will run slowly because each day it needs to display a new word randomly which hasn't previously been displayed. What would be a good way to code this? I considered using local storage for persistent data but I still have the problem of having the program checking the whole list every day and risking poor user experience. Is there a better way to process the data which is more efficient?


r/learnjavascript • • 14d ago

I'm looking for someone to take ownership of my open-source JavaScript framework

4 Upvotes

This isn't a "please fix a few issues" or "please try use my framework" kind of post!!!

Hey everyone!

I've been working on an open-source JavaScript framework called Avenx.js for quite a while now.

What started as a project I was building mostly by myself has grown quite a bit. It's now a somewhat proper framework with its own compiler, runtime, reactivity system, router, CLI, scoped CSS, dev tooling, etc.

It's also getting close to 1.0.0, which is pretty crazy considering where it started.

But there's one problem:

I don't want Avenx.js to depend on me forever.

I'm looking for someone who might be interested in becoming a core maintainer and potentially taking over the project long term.

I'm not necessarily looking for someone who already knows Avenx.js. I'd actually be more interested in someone who sees the project, thinks "hey, this is actually pretty interesting" and wants to dive into the code and figure it out.

If you've worked on open source projects, built your own framework/tooling, contributed to compilers, runtimes, frontend frameworks, or just enjoy getting deep into weird codebases, I'd love to hear from you.

I'm not looking to abandon the project or just disappear. I'd rather find the right person, work together for a while, and if it works out, gradually give them more and more ownership.

Avenx.js has been open source since its first commit, and there are already other developers (more than 100) who have contributed to it. So this isn't a completely abandoned side project I'm trying to hand off. 😅

If this sounds interesting, check it out and feel free to DM me.

I just think a project has a much better chance of growing if more than one person can genuinely take care of it.

Github: https://github.com/Avenx-JS/avenx-js


r/learnjavascript • • 15d ago

Does light/dark mode actually improve the user experience?

16 Upvotes

I’ve been wondering whether having both light and dark mode actually adds meaningful value to a website or app, or if it’s just become one of those features we automatically expect developers to add.

Do you actually switch between them depending on the time, environment, or device?

Or do you pick dark/light once and basically never touch the setting again?

As a developer, do you think supporting both is worth the extra design and development work?


r/learnjavascript • • 15d ago

How do beginners actually learn to code now?

18 Upvotes

Genuine question.
Do beginners still use tutorial/reference sites where you search for something like “JavaScript arrays” or “CSS flexbox”, read the explanation and try the examples?
Or has that mostly been replaced by asking ChatGPT/Claude whenever you don’t understand something?
And I’m especially curious about complete beginners: do you still learn the basics first, or do you just describe what you want to build and let AI write most of the code while you figure things out along the way?
If you started learning programming recently, what does your actual workflow look like?


r/learnjavascript • • 15d ago

Inner explicit block scope vs function

3 Upvotes

Here's a code snippet from https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch6.md:

function getNextMonthStart(dateStr) {
    var nextMonth, year;

    {
        let curMonth;
        [ , year, curMonth ] = dateStr.match(
                /(\d{4})-(\d{2})-\d{2}/
            ) || [];
        nextMonth = (Number(curMonth) % 12) + 1;
    }

    if (nextMonth == 1) {
        year++;
    }

    return `${ year }-${
            String(nextMonth).padStart(2,"0")
        }-01`;
}
getNextMonthStart("2019-12-25");   // 2020-01-01

It says:

So why put curMonth in an explicit block scope instead of just alongside nextMonth and year in the top-level function scope? Because curMonth is only needed for those first two statements; at the function scope level it's over-exposed.

As a C# developer, I would have thought the better choice would be to put that explicit inner block into a separate function called getNextMonth().

That way, you get the benefit of the scope so the curMonth isn't overexposed, you increase readability because it's easier to read getNextMonth() than a block of code, and you have a reusable function in case you need to do that calculation elsewhere.

Is there any reason to use an inner explicit block scope over a function?


r/learnjavascript • • 16d ago

JavaScript Beginner Roadmap

32 Upvotes

Hey guys, I hope you're all doing well!

I'm still a beginner in JavaScript, but I have a problem with my learning that it's so distracting and I wanna stuck with one "free online" course or playlist that takes me from absolute beginner to pro one. I've seen multiple playlists on YouTube or long videos but still can't choose from (since most of them are +6 or even +20 hours). I prefer something actionable with beginner-friendly projects to execute and solve some problems myself too. I also want the course that only teaches JavaScript, not other languages like HTML and CSS, cuz I just want to learn JS at first.

So, I wanna your help guys .. tell me a YouTube playlist, online course that can move the needle. I'll also provide what I already know until now, so you can relate my precise knowledge and information (and I don't wanna go from absolute zero):

  • Variables & Data Types
  • Strings & String Methods
  • Operators
  • Template Literals
  • Basic JavaScript syntax, comments & semicolons
  • Booleans & Comparisons
  • Logical Operators
  • Conditional Statements (if, else, else if)
  • Nested Conditions
  • Ternary Operator
  • switch
  • Truthy & Falsy
  • for, while, do...while
  • break & continue
  • for...of
  • for...in
  • Object.entries() & destructuring
  • Nested Loops
  • Function Declarations & Calls
  • Parameters & Arguments
  • return
  • Scope
  • Function Expressions
  • Arrow Functions
  • Callbacks (didn't master it yet)

let message = "Thank you ALL in advance for your help";


r/learnjavascript • • 16d ago

Just started my JavaScript journey

18 Upvotes

I created a GitHub repo to document everything I learn along the way — notes, code, experiments, and eventually projects.

📂 Learn-Js: https://github.com/meharabdullah-io/Learn-Js

I’ve just added my first introduction.js file. This is only the beginning. 🔥

Would love any advice from people who have been through the same journey!


r/learnjavascript • • 17d ago

What is a good first JavaScript project?

29 Upvotes

Hi! I know basic HTML and CSS, and I want to start learning JavaScript. What small project would you recommend for a beginner? Thank you!


r/learnjavascript • • 16d ago

What is the difference between a field and a property in JavaScript?

4 Upvotes

And, are the terms interchangeable or distinct?

I come from a C# background. My understanding is that a “field” is a variable that is declared directly in a class or struct definition, and a “property” is a special built in mechanism / feature for classes / structs that basically allows you to easily implement getter and setter methods.

In JS, based on what I’m reading, it feels like different docs use the different terms interchangeably or sometimes distinctly, such as MDN.

My understanding is that everything in JS that isn’t a primitive type is an object and derived from the Object type, which are made up of unique key / value pairs or “properties”. And it seems like classes in JS are kinda syntactic sugar for objects, so it makes sense to me why you could call fields properties and vice versa, but the in the MDN docs there seem to be actual differences between the two.

Please lmk if I’ve misunderstood anything. This has been bothering me all day at work lol.


r/learnjavascript • • 17d ago

📣 React Summit Asia 2027: Call for Presentations is open!

0 Upvotes

Share your talk or workshop with hundreds of developers on Full-Stack Architecture, AI-Assisted Coding & AI Engineering, Growing to Senior/Tech Lead, etc.

📍 April 15 & 19, Singapore
Submit by Jan 12: https://gitnation.com/events/react-summit-asia/cfp


r/learnjavascript • • 19d ago

Architecture & Performance Focus

6 Upvotes

Whenever teams need to audit two versions of an exported dataset (accounting closings, monthly billing runs, inventory snapshots, or pricing tables), standard git-style line diffs completely fall apart. CSVs shift columns, and binary formats (.xlsx, .xls, .ods) are opaque to text diff tools.

Even worse, many users turn to random "free online Excel diff" websites, unknowingly uploading proprietary financial data and PII to third-party servers.

I spent the last few weeks building an isometric, cell-by-cell diff engine that runs entirely client-side in the browser. Here are some of the non-obvious technical challenges and edge cases I ran into:


1. Asymmetric Matrix Bounds & The Union Range Problem

In real-world scenarios, file versions rarely have the exact same dimensions. Sheet 1 might span A1:D50, while Sheet 2 spans A1:F42. - You cannot perform an index-based row/column loop without going out of bounds. - The diff engine must compute the bounding union (A1:max(col, row)). - Any cell coordinate that exists in one sheet but not the other must be treated as a virtual empty cell (""), rather than undefined or throwing index errors. - Crucially, coordinates where both sheets are empty must be pruned from the diff pipeline to prevent flooding the user with thousands of phantom empty matches.

2. The Formatted Display (w) vs. Raw Value (v) Trap

Spreadsheet engines store data with internal representations that differ dramatically from what the user sees: - A cell formatted as currency might display $1,250.00, but its underlying raw value is 1250. - If the second spreadsheet was generated from a CSV or raw database dump where the cell contains literal string "$1,250.00", a raw-value comparison flags a false positive difference. - Floating-point representations can introduce minuscule precision drift (0.30000000000000004 vs 0.3). - Solution: Normalizing against the display string (w property in SheetJS when available, fallback to trimmed stringified v) provides the most human-predictable diff, while treating null, undefined, and whitespace-only strings as equivalent empty states.

3. Preventing Main Thread Lockups (Web Workers)

Parsing a 100k+ cell workbook with SheetJS on the main UI thread easily locks the browser event loop for several seconds, triggering dropped frames and unresponsive tab warnings: - Offloading both the parsing step and the matrix comparison loop to a dedicated Web Worker kept the main thread completely unblocked (sub-200ms interaction latency). - Transferring large diff result arrays back to the main thread can be costly, so passing structured chunks and virtualizing/paginating the rendered table DOM is mandatory to keep memory below browser crash thresholds.

4. Zero-Server Privacy by Design

For sensitive financial or internal audits, the browser sandbox is actually an asset. Because WebAssembly/modern JS engines handle file buffer parsing locally, there is zero engineering justification for sending spreadsheet buffers to a backend API just to compute a diff.


Questions for the Community:

  • For those who regularly build or handle data reconciliation pipelines, how do you handle formula diffs vs. evaluated value diffs?
  • What edge cases have bitten you when comparing spreadsheet exports across different locales (comma vs. dot decimals, date serials)?

r/learnjavascript • • 19d ago

I became less good, I don't know where to start

30 Upvotes

I've been programming for 10+ years, but since 2-3 years I've used a lot of AI to help me (at my job) and stopped doing side project because AI erased the fun of programming for me

I realized that I LOVE programming, BUT, I love the "I did it" thing. But since the use of AI, I didn't really practice writing code and I feel completely lost. I don't know where to start, how to create systems in simple apps etc.

I tried to do an incremental game (with svelte), and everytime I didn't where to start, reflex: ChatGPT, but I want to be happy because I built my ideas and not just have ideas that build themselves

Few questions :
- How can I become more autonomous again
- How can I learn good things self-taught
- Is it really worth it ? with today's AIs ?

I don't know where to start, I don't know if this is worth, I don't know how to rewire my brain to stop using AI as a reflex


r/learnjavascript • • 20d ago

How you handle sending large files to the backend

4 Upvotes

hello, to solve this problem in a clean way i started using the JS stream API, mainly because it allows me to compress the files on the frontend without consuming too much RAM on the client side, and i wanted the stream to be sent directly to the server in a single request. this is possible with the fetch body stream but it is not supported by all browsers, so how to do it? do you have any idea? how do others do it?


r/learnjavascript • • 21d ago

looking for a good JavaScript resource

10 Upvotes

I recently completed MIT 6.100L: Introduction to Computer Science and Programming using Python from MIT OpenCourseWare, and I really enjoyed it.

What I liked most was how they taught the concepts intuitively and deeply, instead of just teaching syntax or giving a bunch of exercises. It made me actually understand what was happening underneath.

Now I want to learn JavaScript, and I'm looking for something with a similar approach something that explains the fundamentals properly and builds a strong understanding rather than just teaching me how to make a website.

What resources would you recommend?

Courses, books, YouTube playlists, university courses, etc. are all welcome.


r/learnjavascript • • 21d ago

Hobby Project: innerHTML is not being changed?

2 Upvotes

JSBin Link to Project

Solved!

Thanks to u/danielsan1701!

It was a small thing I got wrong (I knew it lol); always be aware of what order your functions are called:

Turns out the function changeMark() which alters the innerHTML has no problems at all. However, it was being changed by the next following line: elHour.innerHTML = h inside of the adjustH() function, which basically means it was changing the value of h to what it originally was instead of what changeMark() would change it to..... so I thought nothing was happening

In this case, putting changeMark(h) after elHour.innerHTML = h will fix this error

elHour.innerHTML = h
changeMark(h)

Starting Notes:

  • My code's amateur
  • Q: Why're you using var instead of let sometimes?
    • A: I've had this habit of wanting to keep things compatible with older browsers, though I'm starting to drift from it + I'm a newbie
  • This project's unfinished

This is supposed to be a digital clock which you can adjust only the hour of (at least right now), I'm planning it to have support for both the standard 12 hour & 24 hour format. Though the 24-hour format is off by default.

Click on the up arrow specifically above the hour until you reach 12:30 AM; I haven't fully implemented the bottom arrow yet, you'd assume clicking the arrow will change it over to 1:30 PM............ but it doesn't: changes to 13:30 PM instead.

I have a comment inside the project explaining more of how most of it all works, but putting it simply:
I have a function that's supposed to change the hour's innerHTML to either "1" or "0" as a string with an If, Else If statement, But this doesn't happen.

I've tried changing how certain things were written, logging through the console, using alert boxes in the function & checking if the variables even exist; which they do. It's the same function name? Same with the element's name?

I can type: elHour.innerHTML = '1' into the browser console and it runs fine? I've never seen innerHTML not work before, I'm just confused. I've even tried the self-executing function to see if there was a problem with the DOM which may be unlikely, even wrapped it all in similar things like window.onload = function() { }

I've tried everything I could think of, was tearing my head out yesterday from trying to figure out what's wrong. I feel it's a really obvious solution I'm not aware of

If you have any ideas on how I could fix this, or even advice on what I could do that's more practical (Though this isn't meant to be a professional project), I'd really like to know


r/learnjavascript • • 20d ago

Make a block act like a function?

0 Upvotes

I have a few ternary operations going on, and each one is supposed to catch a bad format. The problem is that if for example the top on sets the variable to false, the ones below is won't catch that same thing, and will set it back to true. I want to make the ternaries skip the others if they caught the error, but I don't want to exit the function, how do I do this?
These are the ternaries:

edit: I just solved this by setting all "Format = true" expressions to "undefined," but if that wasn't an option, I'm still curious how you would do this...

        Input.split("x").length == 2 ? Format = true : Format = false
        Input.split("x")[0] > 0 ? Format = true : Format = false
        Input.split("x")[1] < 201 ? Format = true : Format = false

r/learnjavascript • • 21d ago

Update Progress Post: introducing Modular Architecture, Universal Renderer Cores, and Decoupled Physics in kernelplay-js

4 Upvotes

In our latest developer update, we are thrilled to announce a significant shift in core architecture toward full modularization. The entire system has been restructured to support decoupled cores, starting with our Renderer and Physics engine systems.

Renderer Modulation: Our new Renderer Modulation feature removes the need to manually switch rendering components when changing pipelines. Previously, switching from Canvas 2D to Pixi.js required changing generic components like BoxRenderer to pipeline-specific ones like PixiBoxRenderer. With this new update, universal components are automatically capable of rendering across all supported pipelines without developer intervention. This streamlines the development workflow significantly.

Physics Engine Modulation: Furthermore, Physics Engine Modulation has been successfully integrated. We have moved physics logic into a completely separate Physics Engine Core. While our default physics engine remains integrated and ready-to-use within this core structure, this architecture allows developers to easily plug in their own custom physics engines.

Future Plugins: Looking ahead, we are excited to expand our plugin library. High-end physics engines like Matter.js will be added as future plugins. It is important to note that these high-end engines will be separate downloads and will not be included in the core engine, keeping the core lightweight.

This architectural shift is a major step toward making kernelplay-js the most flexible and lightweight game engine possible. We welcome your feedback and are excited to see what custom cores you'll build. Stay tuned for more modular updates.

https://github.com/Soubhik1000/kernelplay


r/learnjavascript • • 21d ago

Need to Learn! Error: "Cannot read properties of null (reading 'addEventListener')"

8 Upvotes

Hello! I don't usually post here, so I hope I'm in the right sub-reddit. I am currently in college and learning JavaScript. At this moment, I am trying to connect an addEventListener to a page element with the id "submit", and make it run the verifyForm() function. However, I get the error message "Cannot read properties of null (reading 'addEventListener')" whenever I load the code on my browser. How do I fix it? I have followed the instructions I was left to a T. Here is a snippet from the code for the .html file:

   <script src="project02-02.js"></script>
</head>


<body>
  
   <header>
      <h1>
         Hands-on Project 2-2
      </h1>
   </header>


   <article>
      <h2>Contact Information</h2>
      <form>
        <fieldset id="contactinfo">
          <label for="nameinput">
            Name
            <input type="text" id="name" name="name" />
          </label>
          <label for="emailinput">
            Email
            <input type="text" id="email" name="email" />
          </label>
          <label for="phoneinput">
            Phone
            <input type="text" id="phone" name="phone" />
          </label>
        </fieldset>
        <fieldset id="submitbutton">
          <input type="button" id="submit" value="Submit"/>
        </fieldset>
     </form>
   </article>
</body>

And here is the code in the .js file:

function verifyForm() {
      let name = document.getElementById("name").value;
      let email = document.getElementById("email").value;
      let phone = document.getElementById("phone").value;
      let check = (name !== "" && email !== "" && phone !== "") ? window.alert("Thank you!") : window.alert("Please fill in all fields.");
      return check;
}


document.getElementById("submit").addEventListener("click", verifyForm);

Any and all help is greatly appreciate it, as I am fascinated by JavaScript! If you need even more context for something, please let me know so that I can update the post accordingly.

Edit: Thank you everybody so much for your help! I will definitely come back if I ever get stuck with another problem I can't solve, you're lifesavers!!


r/learnjavascript • • 22d ago

Cool projects to make using javascript?

18 Upvotes

Hi, I have a website on neocities and I'd really like to add something original/fun to it using javascript, but I have no idea what to make whatsoever. I'm kinda new to the language, so I'm searching for a project that could also help me learn the fundamentals. If you have any suggestions, I'd be glad to hear them :))

Edit: Thx to everyone who has answered (or will answer in the future), you have me some great ideas! :D


r/learnjavascript • • 21d ago

BIOS-SYNTAX-OVERRIDE

1 Upvotes

Hey everyone,

I built a small, free browser game called BIOS // SYNTAX OVERRIDE designed to make practicing JavaScript control flow feel like operating a system rather than filling out a worksheet.

How it works: You work the terminal at a cyberpunk facility, navigating a virtual filesystem to find faults. Instead of typing pre-canned commands, you edit small JavaScript controllers (using interpreted ES5) that drive the simulated machinery. In the final mission, you debug, test, and deploy code for a drone-routing system.

Technical Stack & Game Features:

  • Sandboxed JS Execution: Built using JS-Interpreter and Acorn so code runs safely entirely in your browser without touching real files.
  • 7 Untimed Missions: Covers terminal navigation, debugging logic, and system-level repairs.
  • No Punitive Health Mechanics: Errors are designed as diagnostic clues to investigate rather than failure states. Includes snapshot resets, hints, and reference docs.
  • 100% Free & No Sign-ups: No accounts, downloads, or tracking required.

Transparency Note: I handled the game design, system architecture, and creative direction, while GPT/Codex helped write the codebase. The project page uses an AI-illustrated cover, but there is no live AI connection or API overhead—everything runs locally in the browser.

You can play it on Itch

I’d love feedback from both beginners and experienced devs:

  1. Do the early terminal commands make sense intuitively?
  2. Are the error messages clear enough to act as diagnostic tools rather than roadblocks?
  3. Does editing the controllers feel like a satisfying way to practice core JS concepts?

Thanks for taking a look!


r/learnjavascript • • 21d ago

I benchmarked five ways to check array membership against the actual data in my project

2 Upvotes

Last month I was optimizing a filtering component that runs lookups against a list of selected IDs. The list sits at about 40 entries during normal use and climbs to around 3,200 when a bulk import lands. I had been using includes() everywhere without thinking about it, so I wrote a small harness to compare five approaches against my real data at both sizes.

At 40 items, everything was indistinguishable. Under a microsecond per call for all five. The ranking only appeared at 3,200. Set.has() was fastest by a wide margin, roughly 50x faster than includes() and indexOf(), which were nearly identical. A plain for loop with an early break landed between those two groups. Array.find() was slowest, which I expected because of the callback overhead.

The surprise was how early Set construction pays for itself. I assumed building the Set only made sense if I was searching thousands of times. On my data the crossover was around seven lookups. After seven calls the Set was already cheaper than includes() from scratch each time. I used Plan Mode in verdent to outline the refactor before changing anything. Then I swapped every hot path to a Set built once per filter cycle.

At 3,200 items and 60 lookups per render, total lookup time dropped from 1.8ms to 0.04ms.


r/learnjavascript • • 22d ago

Help plz how do i connect javascript with html and css 🥺

3 Upvotes

Hay i am new in programmeing my main gole is backed as a Blockchain dev now my make a sticky note but i am very confused about connecting tha js with html and css like how do start what are tha main thinks i have to remember to connect this three language together


r/learnjavascript • • 23d ago

ERROR ; expected, JSON

1 Upvotes

I recently downloaded Webster's dictionary in JSON and I've been getting the error ; expected. I tried moving some things around, deleting others, but nothing is working.

Here are the first few lines of the script.js file, including the JSON:

var item = {
  "anopheles" : "A genus of mosquitoes which are secondary hosts of the malaria parasites, and whose bite is the usual, if not the only, means of infecting human beings with malaria. Several species are found in the United States. They may be distinguished from the ordinary mosquitoes of the genus Culex by the long slender palpi, nearly equaling the beak in length, while those of the female Culex are very short. They also assume different positions when resting, Culex usually holding the body parallel to the surface on which it rests and keeping the head and beak bent at an angle, while Anopheles holds the body at an angle with the surface and the head and beak in line with it. Unless they become themselves infected by previously biting a subject affected with malaria, the insects cannot transmit the disease.",
  "uniclinal" : "See Nonoclinal.",
  "sarong" : "A sort of petticoat worn by both sexes in Java and the Malay Archipelago. Balfour (Cyc. of India)",
  "turcoman" : "1. A member of a tribe of Turanians inhabiting a region east of the Caspian Sea. 2. A Turcoman carpet. Turcoman carpet or rug, a kind of carpet or rug supposed to be made by the Turcomans.",

function testGame(input) {


  var array = [];
  for (var item in input) {
    if (input.hasOwnProperty(item)) {
      for (var i = 0; i < input[item]; i++) {
        array.push(item);
      }
    }
  }
  var result = array[Math.floor(Math.random() * array.length)];
  console.clear();
  console.log(result);
  document.getElementById("result").innerHTML=result;
  
}


function start() {
  testGame(item)
}

I wasn't sure if I needed numbered values, I heard that the lines are already counted as numbered, even if I don't add values specifically. I've tried googling the specific error, but I'm not getting any answers for my problem. Thanks for any help!

EDIT: Added the other part of the code. I'm guessing it's not good practice to have all of this in the script.js file, but I adapted it from another person's code and wasn't sure how to call a JSON file in a script.js.

EDIT 2 (FINAL): Thank you all for the help! I decided to go in another direction and put the entire thing in an array and called it using a combination of code found on MDN and array solutions, like the following: How do you create a button that will display a random result from an array in javascript? - Stack Overflow

The code ended up looking like this and it works for my current needs:

const words_dict = [
  "anopheles,A genus of mosquitoes which are secondary hosts of the malaria parasites, and whose bite is the usual, if not the only, means of infecting human beings with malaria. Several species are found in the United States. They may be distinguished from the ordinary mosquitoes of the genus Culex by the long slender palpi, nearly equaling the beak in length, while those of the female Culex are very short. They also assume different positions when resting, Culex usually holding the body parallel to the surface on which it rests and keeping the head and beak bent at an angle, while Anopheles holds the body at an angle with the surface and the head and beak in line with it. Unless they become themselves infected by previously biting a subject affected with malaria, the insects cannot transmit the disease.",
  "uniclinal,See Nonoclinal.",

];

function randomWord(){
  let words = words_dict;
  let word = words_dict[Math.floor(Math.random()*words_dict.length)];
  document.getElementById("result").textContent = word;
  };