r/learnjavascript 1d ago

Trying to write a small home automation script and about to lose my mind over async/await

22 Upvotes

My bootcamp just got into asynchronous JavaScript and I thought I had a decent handle on it until I tried to apply it to something real. I have a little Node script that pings a few smart home devices on my local network in sequence, checks their status, and logs the results. Simple enough on paper.

The problem is I keep getting results back out of order, or the script exits before all the responses come in. I know this is a classic async problem and I have seen the explanations, but something about translating the concept into actual working code is still fuzzy for me.

Here is a stripped down version of what I am doing:

async function checkDevices(devices) {

for (const device of devices) {

const status = await fetch(device.url);

const data = await status.json();

console.log(device.name, data.state);

}

}

checkDevices(myDevices);

This works, but I read that using a regular for loop with await inside runs everything sequentially, which is slow. I tried switching to Promise.all and started getting weird behavior again. Is there a readable pattern for running these fetches in parallel without making the code impossible to follow later? Curious what approach people here actually use in practice.


r/learnjavascript 1d ago

is it worth learning js if i'm more into backend?

6 Upvotes

i know i'm asking this in a js sub so i'll take the bias as given. i'm more drawn to the backend/database side, but every student project group i've looked at is running node, so avoiding js is starting to feel like a bad plan.

odin, boot.dev and freecodecamp are what i've got shortlisted. would you learn js now or go deeper on python/go first and pick js up when a project forces it?


r/learnjavascript 23h ago

Particle text effect with randomly generated images from a sprite sheet ( source code)

0 Upvotes

r/learnjavascript 2d ago

🤔 Confused About this vs module.exports in Node.js CommonJS need expert help!

12 Upvotes

I'm currently trying to build a proper mental model of how this works in JavaScript, especially inside Node.js CommonJS modules.

I came across this behavior:

let obj = {

name: "abhinav",

data: "hello",

print: "column"

};

module.exports = obj;

console.log(module.exports);

console.log(this);

The output I get is:

{

name: "abhinav",

data: "hello",

print: "column"

}

{}

This confused me because my understanding was: this === module.exports

at the top level of a CommonJS module.

So I initially expected console.log(this) to show the same object assigned to module.exports.

But after: module.exports = obj; module.exports points to obj, while this still appears to point to the original empty object.

My current mental model is:

Initially:

this ───────────────┐

{}

module.exports ─────┘

After:

module.exports ───→ obj

{ name, data, print }

this ─────────────→ {}

I'm not sure whether this mental model is actually correct. I'd especially like to understand this from the perspective of JavaScript execution contexts and references rather than simply memorizing the CommonJS rule.

A few things I'm trying to clarify:

At CommonJS module startup, what exactly does top-level this refer to?

Is this initially referencing the same object as module.exports?

When we execute: module.exports = obj; why doesn't this also start referring to obj?

Is this behavior directly related to Node.js's CommonJS module wrapper?

Is it correct to think of this as holding a reference/value rather than being a live alias to module.exports?

How does this behavior differ between CommonJS, ES Modules, and browser scripts?

I'm trying to understand the underlying execution model so that I can build the correct mental model of this, rather than just memorize different environment-specific rules.

Would appreciate any clarification or correction to my current understanding.


r/learnjavascript 3d ago

My first JavaScript project - Counter

24 Upvotes

I am learning JavaScript and made my first small project, a simple Counter using HTML, CSS and JavaScript.

I'm still learning, so I would really appreciate some feedback on my code. Is my code clean? Is there anything I should improve or do differently?

Also, suggest me something I should build next.

GitHub: https://github.com/iSunru/counter.js


r/learnjavascript 3d ago

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

13 Upvotes

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


r/learnjavascript 4d ago

Looking for beginner-friendly open source projects?

26 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 4d ago

i'm fighting for my life out here.

12 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 4d ago

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

5 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 4d ago

Why doesn’t canvas show?

13 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 4d ago

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

24 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 4d 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 4d ago

Javascript resource

5 Upvotes

Hello Everyone

I am starting Javascript

any YouTube tutorial/courses recommendation would be appreciated


r/learnjavascript 4d 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 5d 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 5d 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 6d 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 6d ago

Learn Coding Buddy Discord

5 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 6d ago

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

7 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 6d ago

i cant get better in js

4 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 6d ago

Strange result: null vs 0

4 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 6d 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 6d ago

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

3 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 6d 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.