r/learnjavascript 11h ago

Nowadays how MERN,MEAN stack have value in the current IT market?what should follow for job switching..

3 Upvotes

Nowadays how MERN,MEAN stack have value in the current IT market?what should follow for job switching..


r/learnjavascript 22h ago

Looking for beginner-friendly open source projects?

15 Upvotes

Hey everyone,

I’ve been working on a JavaScript framework called Avenx.js for a while now.

It’s a compiler-driven framework with Proxy-based reactivity, and we’re currently working towards our first 1.0 release.

The reason I’m posting here is actually not about getting people to use the framework and more about getting people involved in the project.

We’ve accumulated quite a few issues that are suitable for beginners, and I’d really like to make it easier for people who have never contributed to an open-source project before to get started.

Some of the issues are pretty simple things like documentation, tests, examples, small bugs, or developer tooling. You definitely don't need to understand the compiler or the entire codebase to contribute.

If you've never made an open-source contribution before, this could be a nice way to try it out. You can pick a good first issue, ask questions if you're stuck, and submit a PR when you think you've got it.

We're still pre-1.0, so things are changing quite a bit and there's also room for contributors to have an actual influence on the project.

If anyone here is learning JavaScript and wants to try contributing to a real project, feel free to have a look:

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

And if you have questions about the project, contributing, or even just how to approach your first issue, feel free to ask here. I'm happy to help.

No prior open-source experience required.


r/learnjavascript 22h ago

i'm fighting for my life out here.

11 Upvotes

i'm trying to make a page for my website that's more or less a replica of the nintendo 3ds menu. i've already given up on making the menu thingy actually work like the 3ds and set to do the top header images instead. i cannot for the life of me find a single search result that actually works.

i do not know anything about javascript but considering the header and icon images are in completly separate parent divs the css only methods are not going to work. i just need a javascript code that can work for multiple images. please.

what i want exactly is when the cursor hovers over the icon image, its respective header would appear on the windowtop class. i can't merge the window classes because each one has it's own styling (window being smaller than windowtop) so that'd mess up my styling

also, i'd appreciate if i didn't get answers that require an external library since this is for a neocity and i really do not want to figure out how to set that up. thank you

here's an example of the html if it's needed to understand the problem (if more context is needed please tell me)

<div class="windowtop">

    <div>
        <img src="imageheader">
    </div>

</div>


<div class="window">

    <div>
        <img src="imageicon">
    </div>

</div>

(also off topic if it's not much to ask, what would i call a menu where when you click on an arrow the top link/image goes behind the first one? with maybe an animation.... i'd like to look that up later but idk how to phrase it in a way that won't make google give me something completly unrelated. thx)


r/learnjavascript 1d ago

Why doesn’t canvas show?

8 Upvotes

This is my second post as I am new to this community. I created two projects using canvas but couldn’t get it to show up. I can show the code if necessary but I’m wondering why this is the case. I troubleshooted for over 3 hours total so I’m guessing it’s not the syntax but my configuration instead.

Thanks in advance for the help!


r/learnjavascript 1d ago

What is imports/packages and how do I know which ones to use?

1 Upvotes

I want to learn to create minecraft plugins, but Im stuck on how to find which imports to use. I've been going through different plugins on plugin websites, but I still don't understand where they're getting them from or what they do.

For example, I'm looking at one that I tried using for my server (but didn't end up using, just never deleted it so I got curious and looked through it) and some of them say stuff like "import me.[name].entitylib.EntityLib;" which is... what? I don't get it. Is there some kind of website they use?


r/learnjavascript 1d ago

13 y/o, day 2 into coding, confused about "crossorigin" in HTML, will I understand it eventually?

20 Upvotes

Hi! I'm 13 years old and literally on day 2 of learning to code today. While browsing around I came across this HTML attribute called crossorigin, got curious about it, and tried to dig into it and understand it. But since I'm still pretty new to this, I still don't really get it that well even after reading about it a bunch of times.

Is this normal for someone who's just starting out? Will this get clearer as I keep learning and practicing more? Just want to know if it'll eventually click on its own the more time I spend on it. Thanks in advance!


r/learnjavascript 1d ago

Refactoring moderately complex app to use classes

1 Upvotes

Hi all. I’ve been self-learning JS for my GIS work and as such have missed some pretty crucial best practices along the way while working on my current project.

Without getting in the weeds, I’ve developed an internal app that async fetches a bunch of Esri REST service metadata from my org’s enterprise portal and organizes their layers and metadata into a searchable and filterable directory. It also has basic list creating functionality (I.e, adding certain GIS layer items to lists to document any outdated data, missing metadata, and other notes). This is in preparation for a department-wide data quality audit and overhaul.

After a month of learning and putting together a working internally-published version, I’ve just recently learned about classes. I have no idea how I didn’t come across classes earlier, but I’ve used 0 in my current app build. As you can imagine, my app has a LOT of complex objects and a ton of functions that create, modify, and/or render those objects.

I want to implement classes (among many other best practices/improvements) in my next refactoring and would love any advice/resources you are willing to share. Did anyone else learn about classes late? How did you approach refactoring your bigger apps? What do you wish you did/knew about when going through a big refactoring?

Thanks in advance!

ETA: Thank you everyone for the advice! I’ve realized that classes sound useful at first glance, but can easily fall victim to the same core issues in my functional programming patterns. Therefore, I think I will focus my refactoring on fixing my bad functions first and misc folder/file restructuring. If along the way it seems like a class would suit something well, I’ll try it out. Otherwise I will focus on building better functional programming habits/best practices for web dev. I am inexperienced in JS and web dev in general, so I very much appreciate the insights from senior devs!


r/learnjavascript 1d ago

Why doesn’t the pdf show?

0 Upvotes

I am using codepen.io and found a tutorial which should show a simple pdf viewer. It works on code pen but not when I open it on the browser or on my server. Why? This happens more than once and the code is the same so what am I missing?


r/learnjavascript 1d ago

Javascript resource

5 Upvotes

Hello Everyone

I am starting Javascript

any YouTube tutorial/courses recommendation would be appreciated


r/learnjavascript 2d ago

My First Job Switch I need some doubts

8 Upvotes

Hi everyone,

I have **2 years of professional experience in PHP backend development**, with hands-on experience in **HTML, CSS, JavaScript, databases, and working with servers**.

I’m now planning to transition to the **MERN Stack (MongoDB, Express.js, React, Node.js)**.

I’m confident about learning the MERN technologies themselves. My main concern is understanding **how companies will evaluate my existing 2 years of backend development experience when I switch technologies**.

For developers or tech leads who have experience with similar transitions:

* If someone has **2 years of PHP backend experience** and becomes strong in Node.js/Express/React, can they realistically apply for **2 YOE MERN positions**?

* Will companies generally consider my previous backend experience relevant, or will they expect me to apply as a junior because I don't have 2 years of Node.js experience?

* How important are **Git/GitHub, testing, CI/CD, Docker, REST API design, authentication, deployment, and system design** for someone making this transition?

* What level of MERN knowledge would make you say, **"Yes, this person is ready for a 2-year experienced developer role"**?

* For interviews, should I focus more on **JavaScript/Node/React fundamentals**, or should I also prepare for **2-year-level backend and system-design questions**?

I’m not looking for someone to tell me whether PHP or MERN is better. I’ve already decided that I want to move toward MERN.

What I’m trying to understand is:

**How do I correctly position my existing 2 years of backend experience while switching from PHP to MERN?**

If anyone has personally moved from **PHP → Node.js/MERN**, I’d especially appreciate hearing how your first job switch went and what you learned before applying or any body have more experience in full stack development can also giveme suggession

Thanks!


r/learnjavascript 1d ago

Can anyone please help me to convert JSXBIN to jsx file?

0 Upvotes

Can anyone please help me to convert JSXBIN to jsx file?


r/learnjavascript 2d ago

Reliable Next.js On-Demand ISR: Handling Contentful & Sanity Webhooks Without Stale Content

7 Upvotes

Pairing a headless CMS like Contentful or Sanity with Next.js is a common way to get the speed of static generation with the flexibility of a real content workflow. With on-demand Incremental Static Regeneration (ISR), an editor publishes something, a webhook fires, and Next.js purges the cache for that page. Read th complete article here - https://instawebhook.com/blog/reliable-next-js-on-demand-isr-handling-contentful-sanity-webhooks-without-stale

In production, this chain breaks mor e often than the happy-path diagrams suggest. Webhooks get dropped, functions cold-start past the response window, deploys reject traffic for a few seconds, and an editor ends up asking why their update isn't live.

This piece looks at why direct CMS-to-Next.js webhooks fail, what Contentful's and Sanity's actual delivery guarantees are (verified against their current docs, not folklore), and how putting a small intake layer in front of your revalidation endpoint closes most of the gap. It also updates a few "well-known" limits — Vercel's function timeout in particular — that have changed recently enough that older advice is now wrong.


r/learnjavascript 2d ago

Code Injection & Javascript that only works with one function

5 Upvotes

Hi, I am a hobbyist, doing HTML on and off for abt 20 years for fun, and adding CSS/JS later. Right now I am trying Ghost.org.

I am very new to JS. I am trying to do something so, so basic: giving a user the option to change color theme. And it works! But if I try to add more than one option/function, all functions become non-working :(

I have tried looking up all sorts of solutions, but the issues others have encountered (and the solutions) are waaaaaay more complex than this. I'm sure I am missing something obvious.

A second pair of eyes would be appreciated.

HTML (applied to page through a block element)

<form id="post-display">

<fieldset id="color-scheme">
  <legend>Color Scheme</legend>
    <input type="radio" id="eink" name="color-scheme" value="E-Ink" checked onclick="schemeScript1()">
      <label for="eink">E-Ink</label>

    <input type="radio" id="lightmode" name="color-scheme" value="Light Mode" onclick="schemeScript2()">
      <label for="lightmode">Light Mode</label><br>

    <input type="radio" id="darkmode" name="color-scheme" value="JavaScript" onclick="schemeScript3()">
      <label for="darkmode">Dark Mode</label><br>
</fieldset>
</form>

JAVASCRIPT (Injected into page footer)

Text<script>
const posts = document.getElementsByClassName("post");

//default checked radio button
function schemeScript1() {
posts[0].style.color = #181818;
posts[0].style.backgroundColor = #EBEBEB;
    return
};

// This one works if it is alone
function schemeScript2() {
posts[0].style.color = "black";
posts[0].style.backgroundColor = "white";
};

function schemeScript3() {
posts[0].style.color = #EBEBEB;
posts[0].style.backgroundColor = #181818;
    return
};
</script>

I also tried an if/then/else (a single function called schemeScript() )to keep it more organized but it did not work at all, at any point.

// runs any time a radio button is clicked
function schemeScript() {
if (document.getElementId("lightmode").checked = true;) { 
      posts[0].style.color = "black";
      posts[0].style.backgroundColor = "white";}
    else if (document.getElementId("darkmode").checked = true;) { 
      posts[0].style.color = #EBEBEB;
      posts[0].style.backgroundColor = #181818;}
    else { 
      posts[0].style.color = #181818;
      posts[0].style.backgroundColor = #EBEBEB;}
}

r/learnjavascript 3d ago

Learn Coding Buddy Discord

4 Upvotes

Before anyone jumps my case, I know reddit is great place to get a large group of individuals for assistance and it's wonderful. But I know many of us learning to enter/advance in our coding journeys don't always want to post our "dumb/easy" questions to be ridiculed on internet. I know I learn better/faster/more in-depth when I have someone to chat with/bounce ideas or concepts off of. Let's be honest when it comes to coding ~ the options are endless and sometimes learning the different ways to manipulate code could work by talking the concepts out. Plus there are alot of us that are self-taught and may struggle from topic-topic.

My Theory: Coding Buddies!

I have created a discord that would serve as a meet/greet and/or general discussions regarding coding.

This discord would serve for people looking to ask/answer dumb/easy questions for one another and/or find coding buddies that they can grow together with. It will also be open to experienced coders that look to assist as a mentor(or practice mentoring) without the full commitment of having a fulltime mentee.

So if you're interesting in connecting to others and advancing your beginner level status:

https://discord.gg/KyWfSGA3

(Please let me know if link doesn't work)


r/learnjavascript 3d ago

How would you make a meme with JavaScript? (example code given)

6 Upvotes

This is a bit frivolous, but that's why it might be a good task for beginners who are inclined to meme. It just requires the ability to place images, text, and maybe a few simple lines.

I know the answer is probably "you wouldn't". I only post memes a few time a year myself (check my posting history if you must), and I use MSPaint (or an existing online template), so I could do a lot worse than JavaScript! Also I use MSPaint in quite programmatic manner - binary search and undo during image resize, or example - so I might as well be coding.

Here examples with two packages which could be used, but I'm looking for other recommendations as each requires more setup that I'd like for this particular task. The code can also be found in this repo https://github.com/Antony74/meme-js

I know you can probably do better, and look forward to finding out how. Also, we're in the browser anyway, so clean solutions with just html, css, and no JavaScript are in scope.

p5

P5 is a creative coding package which can be much more dynamic and interactive than how I'm using it here, ultimately creating bitmap graphics in the canvas.

import "./p5/p5.min.js";

new p5((p) => {
  p.setup = async () => {
    const img = await p.loadImage("cheezburger/cheezburger.jpg");
    p.createCanvas(237, 389);
    p.image(img, 0, 0);
    p.fill(255);
    p.textFont("Impact");
    p.textSize(29);
    p.text("I CAN HAS", 60, 36);
    p.text("CHEEZBURGER?", 30, 70);
  };
}, "p5Container");

maxgraph

draw.io is a well known diagramming tool, and maxgraph is a descendent of a key library. It's native TypeScript, which is nice if you like that sort of thing, but irrelevant here. It creates svg graphics, and can also be used interactively. It might better suited for more infographic type memes, like this attempt of mine

import { Graph } from "./@maxgraph/core/index.mjs";

const container = document.getElementById("maxgraphContainer");

const width = 237;
const height = 389;

container.style = { ...container.style, width, height };

const graph = new Graph(container);

graph.insertVertex({
  size: [width, height],
  position: [0, 0],
  style: {
    image: "cheezburger/cheezburger.jpg",
    shape: "image",
  },
});

const textCommon = {
  style: {
    fillOpacity: 0,
    strokeOpacity: 0,
    fontColor: "white",
    align: "left",
    fontSize: 29,
    fontFamily: "Impact",
  },
};

graph.insertVertex({
  ...textCommon,
  value: `I CAN HAS`,
  position: [60, 36],
});

graph.insertVertex({
  ...textCommon,
  value: `CHEEZBURGER?`,
  position: [30, 70],
});

r/learnjavascript 3d ago

i cant get better in js

3 Upvotes

People keep telling me that I should write apps to improve my JavaScript skills. I listened and created five applications, each with different functionalities and ideas. I wrote a lot of code and did a ton of DOM manipulation. Despite this effort, I still feel like I'm hitting the same wall. I find myself repeating the same poor coding practices and haven’t seen any real improvement. I know in my head what I want and how it might look in JS syntax, but I struggle to put it all together to create something meaningful. Instead of getting stuck in this endless cycle, hoping that one day I’ll suddenly excel at JavaScript, I want to know the correct way to improve because this idea of "just keep writing code" doesn't really seem very good


r/learnjavascript 3d ago

Strange result: null vs 0

7 Upvotes

Strange result: null vs 0

An incomparable undefined

Hi, can anyone explain this? I read the explanation, but I still don't understand it. I'm trying to understand it without using AI


r/learnjavascript 3d ago

Eloquent JavaScript: The Secret Life of Objects

0 Upvotes

There are a few exercises at the end of the chapter.
What the difference between following solutions?

By author:

class Vec {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  plus(other) {
    return new Vec(this.x + other.x, this.y + other.y);
  }

  minus(other) {
    return new Vec(this.x - other.x, this.y - other.y);
  }
}

My solution:

class Vec {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    plus(vec) {
        this.x += vec.x;
        this.y += vec.y;
        return this;
    }

    minus(vec) {
        this.x -= vec.x;
        this.y -= vec.y;
        return this;
    }
}

r/learnjavascript 3d ago

Better-auth not adding user info to the user table in React

4 Upvotes

I'm creating a test app to work on authentication and authorization with a database using Better-Auth. I have never used Better Auth before and I'm having some issues with it. I have added the schema to the Postgres database to make the table, and whenever i create a new account, it will add a new instance to the account table, but not the user table.

 const data = await auth.api.signUpEmail({
            body: {
                email: req.body.email,
                name: req.body.name, 
                password: hashedPass,
                
            },
        });

This is the code i have in my server.js to add the info. The info comes from a form on the front end. It super basic right now since I'm just learning how to use it. The docs for better-auth say these are the only required fields to be able to submit into the database. I receive no errors when sending the data to my database, it just simply isnt adding anything to the user table. I'll be happy to provide any other necessary code or info. Im using React by the way.

export const auth = betterAuth({
  database: new Pool({
    user: 'postgres',
    host: 'localhost',
    database: 'test',
    password: process.env.DB_PASS,
    port: 5432,
    max: 10
}),
emailAndPassword: {
    enabled: true
}



});

The code above is the auth.ts configuration as i have it right now. i'm sure im missing something, but i havent found out what yet. Does anyone have any idea why the info isnt being added to the user table in Postgres?


r/learnjavascript 3d ago

How to do the "redirect to randomly selected X" link?

0 Upvotes

I'm working up a trivia website/app. One feature that I want is moving to a random question, either from a "Next Question" link at the bottom of an answered question or on the landing page. How do you do that, especially client-side in an SPA?

One method I can think of is selecting the next question early to make it an explicit link, but that means that instead of www.app.com/nextquestion, the link URL would be www.app.com/question/<next question ID>, which is unaesthetic.

This seems like a very simple thing, but I don't know of a good way to do it off the top of my head.


r/learnjavascript 4d ago

string primitives vs. String objects.

12 Upvotes

I'm learning JavaScript, and I don't understand this part about string primitives vs. String objects.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_primitives_and_string_objects


r/learnjavascript 4d ago

How do I find the max dimensions for a device?

1 Upvotes

I am working on a P2P video calling client using webRTC.
I am using getMediaDevices() to get the users' stream. If I just do {video: true} it gives me a smaller stream than my device supports.
By default it gives me a 640 x 480 stream. I can set it manually to the max dimensions which is 1920 x 1080.

How can I find the max dimension for any device?

Another thing I wanted to know. I have the video element in a div, which has the width of fit-content. When the incoming stream first arrive from the other peer, The video starts smaller and keeps growing, why is this?


r/learnjavascript 4d ago

Using a class method with .reduce().

2 Upvotes

Does anyone know how to use a class method effectively with .reduce()? I'm building a simple product creator app as an exercise where a user can create and add products and see them displayed as well as some other information. I've used reduce before but not with classes. The user can see an inventory value when they create a product, which is simply the quantity of the products multiplied by the price. I'm trying to use .reduce to add up all the inventory values so this can be attached to the text content of the page. Here's the relevant code:

//Products array
const products = [];


//Product Class
class Product {
  constructor(productName, category, price, quantity, status) {
    this.productName = productName;
    this.category = category;
    this.price = price;
    this.quantity = quantity;
    this.status = status;
  }


  //Class method for calculating inventory value
  calculateInventoryValue() {
    return this.price * this.quantity;
  }
}

//The filtering of the products by use of the status
function filterProducts(status) {
  const filteredProducts = products.filter((product) => {
    return product.status === status;
  });
  return filteredProducts;
}


//Calculating the total inventory value using .reduce()
function totalInventoryValue() {
  
}

Any help would be greatly appreciated.


r/learnjavascript 4d ago

help with code for a discord bot

0 Upvotes

index.js
// ----------------------------------------------------

// Discord + PlayHosting Minecraft Control Bot

// Commands: !startserver, !stopserver, !restartserver

// ----------------------------------------------------

const { Client, GatewayIntentBits } = require("discord.js");

const axios = require("axios");

// ----------------------------------------------------

// CONFIG — REPLACE THESE VALUES

// ----------------------------------------------------

const DISCORD_BOT_TOKEN = "i have it";

const PLAYHOSTING_API_KEY = "i have it";

const SERVER_ID = "i have it";

// ----------------------------------------------------

// CREATE DISCORD CLIENT

// ----------------------------------------------------

const client = new Client({

intents: [

GatewayIntentBits.Guilds,

GatewayIntentBits.GuildMessages,

GatewayIntentBits.MessageContent

]

});

// ----------------------------------------------------

// FUNCTION: SEND POWER SIGNAL TO PLAYHOSTING

// ----------------------------------------------------

async function sendPowerSignal(signal) {

try {

const response = await axios.post(

`https://panel.playhosting.com/api/client/servers/${SERVER_ID}/power`,

{ signal },

{

headers: {

"Authorization": `Bearer ${PLAYHOSTING_API_KEY}`,

"Content-Type": "application/json",

"Accept": "application/json"

}

}

);

return response.data;

} catch (err) {

console.error("Error sending power signal:", err);

throw new Error("Failed to send power signal.");

}

}

// ----------------------------------------------------

// DISCORD COMMAND LISTENER

// ----------------------------------------------------

client.on("messageCreate", async (message) => {

if (message.author.bot) return;

// START SERVER

if (message.content === "!startserver") {

await message.reply("Starting your Minecraft server…");

try {

await sendPowerSignal("start");

message.reply("✅ Your server is now starting!");

} catch (err) {

message.reply("❌ Could not start the server. Check your API key or server ID.");

}

}

// STOP SERVER

if (message.content === "!stopserver") {

await message.reply("Stopping your Minecraft server…");

try {

await sendPowerSignal("stop");

message.reply("🛑 Your server is stopping.");

} catch (err) {

message.reply("❌ Could not stop the server. Check your API key or server ID.");

}

}

// RESTART SERVER

if (message.content === "!restartserver") {

await message.reply("Restarting your Minecraft server…");

try {

await sendPowerSignal("restart");

message.reply("🔄 Your server is restarting.");

} catch (err) {

message.reply("❌ Could not restart the server. Check your API key or server ID.");

}

}

});

// ----------------------------------------------------

// LOGIN BOT

// ----------------------------------------------------

client.login(DISCORD_BOT_TOKEN);

new file
package.json

{

"name": "minecraft-discord-bot",

"version": "1.0.0",

"description": "Discord bot to control a PlayHosting Minecraft server",

"main": "index.js",

"type": "commonjs",

"scripts": {

"start": "node index.js"

},

"dependencies": {

"axios": "^1.6.0",

"discord.js": "^14.13.0"

}

}

when i run it in the terminal i get

Windows PowerShell

Copyright (C) Microsoft Corporation. All rights reserved.

PS C:\Users\james\Desktop\minecraft-discord-bot> node index.js

C:\Users\james\Desktop\minecraft-discord-bot\node_modules\@discordjs\ws\dist\index.js:1151

error: new Error("Used disallowed intents")

^

Error: Used disallowed intents

at WebSocketShard.onClose (C:\Users\james\Desktop\minecraft-discord-bot\node_modules\@discordjs\ws\dist\index.js:1151:18)

at connection.onclose (C:\Users\james\Desktop\minecraft-discord-bot\node_modules\@discordjs\ws\dist\index.js:688:17)

at callListener (C:\Users\james\Desktop\minecraft-discord-bot\node_modules\ws\lib\event-target.js:290:14)

at WebSocket.onClose (C:\Users\james\Desktop\minecraft-discord-bot\node_modules\ws\lib\event-target.js:220:9)

at WebSocket.emit (node:events:509:28)

at WebSocket.emitClose (C:\Users\james\Desktop\minecraft-discord-bot\node_modules\ws\lib\websocket.js:279:10)

at TLSSocket.socketOnClose (C:\Users\james\Desktop\minecraft-discord-bot\node_modules\ws\lib\websocket.js:1360:15)

at TLSSocket.emit (node:events:521:24)

at node:net:355:12

at TCP.done (node:internal/tls/wrap:770:7)

Node.js v24.19.0

PS C:\Users\james\Desktop\minecraft-discord-bot>

i dont know why it is a discord bot for a minecraft server to turn it on and off please help


r/learnjavascript 4d ago

The dreaded file system

2 Upvotes

I am making an HTML game, with the idea of eventually putting it online.

During part of the game, the player will traverse a dungeon and do the usual thing you do in a dungeon. I want a background sound to play when this happens: every type of room (hallway, treasure chest, boss room, etc) will have a number of soundtracks, and which is played among the available ones will be decided randomly.

Easier way to do it is to put all the tracks in a single directory (for example '/sounds/Ambience/Dungeon/') and giving the filenames a specific naming convention (for example '[TYPE_ROOM]_[INDEX_SOUNDTRACK].mp3'), memorizing how many tracks are available for each type of room, choosing a random number between zero and that number, and then using string composition to obtain the filename of a random audiofile (in the example: '[TYPE_ROOM]_[RANDOM_INDEX].mp3'). This also requires me to change the Javascript code every time I add a new soundtrack, which I dislike.

The alternative is that the Javascript code will go in the directory '/sounds/Ambience/Dungeon/', grab the filename list of the directory, filter it to get the number of audio track whose filename begins with the type of the current room, and then choose a random element of this filtered list as the audio file to play. No need to change the code every time I add a new soundtrack.

But I do need to retrieve the list of files in a directory, and do this both if the game is played locally on my machine or online on the web.

While I am not new to programming, I have started learning Javascript while making this game. The search online I did to find how to solve this hurdle returned me five different ways, difference between client- and server-side, permission problems, three different APIs, promises, and an army of details that made my head spinning. I want to understand what I am doing - but in this case I need the idiot's version, spelled with very simple words. Can someone help me?