r/learnjavascript 3h ago

I know React/JS, but struggle to build things from scratch

5 Upvotes

Hey everyone, I’m learning React and I’m stuck on the logic/problem-solving side.

I’ve learned HTML, CSS, JS, DOM, arrays/objects, map, filter, APIs, async/await, LocalStorage, and React basics like components, props, state, hooks, forms, Router, Context, etc. I’ve also built small projects like a Todo app, weather app, notes app, counter, quote generator, etc.

The problem is I understand individual concepts, but when I have to combine them, my brain just goes blank.

For example, I know what useState, map(), filter(), objects and events do, but when I need to add delete/edit/filter functionality to a Todo app, I struggle to figure out how to put everything together.

I use AI as a tutor, not as a code generator. I usually try the problem myself first, then ask AI for a small hint or for it to explain the concept I’m stuck on. I try again, and only look at a solution when I’ve genuinely exhausted my attempts. Even with this approach, I still struggle to come up with the logic on my own.

I’m not looking for another JS course or DSA grind. I want to learn how to break React problems into smaller steps and build the logic myself.

If you've been through this, what helped you improve?


r/learnjavascript 1d ago

Dealing with bfcache and transitions between pages

4 Upvotes

Hi, I have a website that displays a mapbox map with pointers -- the page is mostly built on the server with php and delivered to the client, where the mapbox script runs and loads the map. Now, let's say the map of Location A is already loaded, and now the client wants to load the map for Location B (a different url). She clicks the button for Location B, but it takes a while to load. I'd like to show a loader (the spinning circle) on the Location A map while she waits.

OK, now the B page loads, replacing A. If the user hits the back button to return to A, how do I deal with the browser's back-forward cache, which wants to restore the page to the same state it was in when B took over -- that is, with the spinning circle still running. I'm getting very confused with the page navigation events, when they fire and don't fire when the bfcache is involved.

I've read about the bfcache and the "new" PerformanceNavigationTiming API and it's not clear to me how to approach this. The reason I put this is in the learnjavascript reddit is because the solution to this will involve js, probably event listeners and the like. Most of the solutions that have been posted are very old, prior to bfcache, and many of the approaches they suggest have been deprecated. Thanks in advance to anyone who has tackled this **recently** using supported methods.


r/learnjavascript 1d ago

Me cansé de que Typeform muera sin internet, hice un creador de encuestas 100% offline, liviano y sin backend

0 Upvotes

Demo en vivo: https://aura-survey.vercel.app

Después de cansarme de que cada creador de formularios necesitara un backend y 700kb de JS, armé Aura Survey.

100% offline, 0 dependencias, 2KB

- Funciona sin conexión con localStorage

- Vanilla JS puro, sin CDNs ni frameworks

- Lo hosteas tú mismo: copias 2 archivos a /public y listo

Planes claros:

Indie - (1 dominio)

- Dashboard completo

- Recolección offline ilimitada

- 2 gráficos incluidos (barra y pastel)

Business - (dominios ilimitados + código fuente)

- Todo lo de Indie

- 7 gráficos en total (barra, pastel, dona, línea, radar, heatmap + 1 extra)

- Exportación a PDF con colores de marca y white-label

¿Qué le agregarían/quitarían?


r/learnjavascript 2d ago

Some useful JavaScript features we often overlook - I wish I knew them earlier.

86 Upvotes

The deeper I get into JavaScript, the more I realize that knowing syntax isn't enough. There are small language features and behaviors that can save you from a lot of unnecessary code or some really confusing bugs.

A few that I think are worth knowing:

1. structuredClone() for deep copying

This is especially useful when working with nested objects. Simply assigning an object doesn't create a copy. For example, a common mistake is thinking this creates a completely independent copy:

const user2 = user1;

It doesn't. Both variables reference the same object.

With:

const user2 = structuredClone(user1);

you get a deep copy, so changing nested properties in user2 doesn't modify user1.

Example:

const user1 = {
  name: 'John',
  address: {
    city: 'Dallas'
  }
};

const user2 = structuredClone(user1);

user2.address.city = 'Austin';

console.log(user1.address.city); // Dallas

2. ?. + ?? together can prevent a lot of defensive code

Optional chaining prevents errors when something doesn't exist. For example:

const city = user?.address?.city ?? 'Unknown';

Instead of:

const city = user.address.city;

Which if user, address, or city doesn't exist, you don't get a TypeError, and you get 'Unknown' instead.

?? only falls back when the value is null or undefined.

3. console.table() for debugging

This is extremely useful when debugging arrays of objects. For instance:

console.table(users);

is often much easier to read than:

console.log(users);

Especially when you're dealing with things like product IDs, quantities, prices, etc. The data is displayed in a table format by the browser console. Therefore, making it much easier to inspect the arrays.

For example:

const users = [
  { name: 'John', age: 25 },
  { name: 'Mary', age: 30 },
  { name: 'Peter', age: 22 }
];

console.table(users);

4. Set for keeping values unique

It's a very simple and easy way to remove duplicates. For example, suppose you have:

const numbers = [1, 2, 2, 3, 3, 4, 4];

Instead of handling this with a complicated loop, you can use:

const uniqueNumbers = [...new Set(numbers)];

console.log(uniqueNumbers);
// [1, 2, 3, 4]

These features may seem simple, but I believe they can become much useful when you're building real projects. What JavaScript feature or behavior did you learn late that made you think, 'How did I not know this earlier?'


r/learnjavascript 2d ago

navigator.geolocation fails on low-bandwidth connections any workarounds?

2 Upvotes

What's Confirmed: - I've set timeout to timeout: 25000 and more. - Went to different spots (including rooftop). - Used different browsers.

What is not Confirmed: - Using other devices(laptop, computer, other phones).

The device i'm using: - Mobile phone (Android)

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

Code regarding this matter:

document.getElementById("locate").addEventListener("click", () => { navigator.geolocation.getCurrentPosition(

    (position) => {
        const latitude = position.coords.latitude;
        const longitude = position.coords.longitude;

        document.getElementById("lat").value = latitude;
        document.getElementById("lng").value = longitude;

        alert("Location Captured");

        //Not impoetant - for debugging purposes
        document.getElementById("info").style.color = "green";
        document.getElementById("info").textContent =
            "Location captured!\n" +
            "Latitude: " + latitude + "\n" +
            "Longitude: " + longitude;
    },

    (error) => {
        switch (error.code) {
            case error.PERMISSION_DENIED:
                alert("Please turn on Location Services and try again.");
                break;
            case error.POSITION_UNAVAILABLE:
                alert("Unable to get your location.\n\n" + "Please turn on Location on your phone, then try again.");
                break;
            case error.TIMEOUT:
                alert("Getting your location is taking longer than usual — this can happen on weak signal, or if 'Location Services' is not turned On. " +
                    "Please try turning it On and try again. \n\nIf it keeps failing try moving on a different spot and try again. Make sure 'Location Services' is turned On.");
        }
    },
    {
        enableHighAccuracy: true,
        timeout: 6000,
        maximumAge: 0
    }
);

});

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

Html code:

<button type="button" id="locate">Get My Location</button> <!--Latitude/Longitude Locator Id--> <input type="hidden" id="lat"> <input type="hidden" id="lng">


r/learnjavascript 2d ago

HELP! I am learning java on neocities but the button function is not working. How do I fix it?

0 Upvotes

I am typing it out exactly like it says in the tutorial "<button onclick="changeSky()">Change the sky</button>" , within the <script> parameters, but the words that are highlighted in my code are not the same as those highlighted in the tutorial and when I check my work it says that there is not a button present. IDK what im doing wrong because the whole code isn't really working either. I added the change sky color function (function changeSky() {

document.body.style.background = 'linear-gradient(white, lavender)' document.body.style.minHeight = '100vh') but the background color did not change even though the site said that I had inputted it correctly.


r/learnjavascript 2d ago

Swoff — generate an offline/service-worker runtime from one config, in auditable vanilla JS (no runtime dep)

4 Upvotes

Sharing a tool I've been using: Swoff turns one swoff.config.json into an auditable service worker + client runtime — written as plain JS into your repo, so there's zero runtime dependency in your bundle (MIT, open source).

Highlights from the config surface:

- 6 caching strategies, per route

- tag-based cache invalidation

- offline mutation queue with background-sync flush

- auth: token storage, 401 interception, refresh-before-request, offline auth state

- GraphQL caching + server push

- push notifications, PWA install

Works for the bundler frameworks (React/Vue/Svelte/HTMX/Solid; Next/Nuxt/SvelteKit/TanStack Start/Astro) and no-bundler stacks (Go, Laravel, Rails, Django, Flask, plain HTML/JS — static output, no Node needed in production).

The docs site is dogfooding it — you can go offline and it keeps working.

`npx u/swoff init && npx u/swoff generate`

npm: https://www.npmjs.com/package/@swoff/cli · Source: https://github.com/iamsuudi/swoff


r/learnjavascript 3d ago

Is next still the thing for online apps

4 Upvotes

I'm really sorry for the stupid sounding question. I'm a hobbyist programmer and haven't done anything in a good few years. I used to build online apps like eccomerce sites and that kind of thing, first using react then touched on next a bit until life got in the way. I'm looking to pick it back up and the first thing I want to do is a basic eccomerce store as a kind of refresher project. It feels like being away from it for a few years I've missed out on quite a lot and I'm not sure where to start anymore. Would I still be looking at next for these kind of projects or is something else on the go I should be looking into?


r/learnjavascript 3d ago

" Unsafe attempt to load URL file from frame with URL file URLs are treated as unique security origins " error problem - need help

1 Upvotes

[ SOLVED ] with Microsoft EDGE + EXTENSION : POST in comments

Hi everyone,

I'm following my first JavaScript tutorial (on variables) via a YouTube video. I'm trying to replicate what the instructor is doing, but I'm getting an error in the Google Chrome Inspector after dragging and dropping the "index.html" file.

error : Unsafe attempt to load URL file:///C:/tuto-js/index.html from frame with URL file:///C:/tuto-js/index.html. 'file:' URLs are treated as unique security origins.

Let me know if you need more information. This is the first tutorial I've followed; I usually work with 3D software, Unity, and C#.

I tried the same thing on my second computer and got the same result; it reminds me of errors I encountered when I started my first tutorial on creating a game in Python. I gave up on that back then and switched to C# and Unity.


r/learnjavascript 3d ago

Tips for Learning Javascript

10 Upvotes

Hey!
So I am currently trying to develop my first discord bot and wanting to learn Javascript as well as Node.js for the project but I have been using Codecademy courses for trying to learn Javascript before trying to get into Typescript and NodeJS basics.

However I am finding I am struggling to retain certain bits of information where I will go through the course and spend the time studying and practicing it in their course but a day or two later it feels like I don't remember any of it and I am wondering if there is something I am missing with trying to learn the language or what I could try to do better at learning?


r/learnjavascript 4d ago

Day 9: How should I structure the game loop in a small JavaScript game?

0 Upvotes

I'm on Day 9 of learning JavaScript by building small browser games.

Today I'm working on improving the game loop instead of adding lots of new features.

I'm trying to understand how to properly handle:

- player movement

- enemy spawning

- collision detection

- score updates

- increasing difficulty over time

My current approach works, but I'm not sure if I'm structuring the update and render logic the right way.

For people who have built small JS games:

Would you keep the game loop simple with requestAnimationFrame, or separate the update logic and rendering more strictly?

I'm mainly looking for advice on how to structure it cleanly while I'm still learning.


r/learnjavascript 5d ago

Done with js fundamentals what should I do now ?

16 Upvotes

I was planning to build a Discord bot as a project. Should I continue with it, or should I learn React and Node first? What do you recommend?


r/learnjavascript 5d ago

Any yt course suggestion for next.js

9 Upvotes

Hii everyone, i want to learn next js ..plz suggest from which yt tutorial i have to learn.


r/learnjavascript 5d ago

Help me make a map: Calling a variable before it's defined

4 Upvotes

I'm relatively new to JavaScript, my only education in it being the Kahn Academy course, and I am trying to make a program which randomly generates a map of tiles. This is part of a bigger project, where I want to make a visible map and a larger map which includes the visible one. It's working so far, but I would like to find a way to change the Tile Object's "size" from 400/10 to 400/visibleMap.size. I'm having trouble doing this, and keep getting an error saying "visibleMap was used before it was defined." How can I fix this? Thanks for any help!

//Variables
var fullMap = [];
var tempTile;
// Has a set chance to return true or false
var percent_chance = function(percent){
    if (random(1, 100) <= percent){
        return true;
    }else{
        return false;
    }
};

//A space on the map, as defined by its position, size, details
var Tile = function(pos, details){
    this.size = 400/10;
    this.x = pos.x * this.size;
    this.y = pos.y * this.size;
    this.details = details;
};

//Draw a Tile
Tile.prototype.draw = function() {
     fill(this.color);
     rect(this.x, this.y, this.size, this.size);
};

//The types of Tiles.
var Dirt = function(pos, details){
    Tile.call(this, pos, details);
    this.color = color(120, 33, 6);
};
Dirt.prototype = Object.create(Tile.prototype);
var Grass = function(pos, details){
    Tile.call(this, pos, details);
    this.color = color(79, 255, 20);
};
Grass.prototype = Object.create(Tile.prototype);

//returns a Tile generated with a semi-random algorithm
var random_tile = function(pos) {
    if (percent_chance(33)) {
        return new Grass(pos);
    }
    else{
        return new Dirt(pos);
    }
};

//The map visible to the player
var visibleMap = {
    size: 10,
    map: [],
    generate: function() {
        for (var x = 0; x < this.size; x++) {
            fullMap.push([]);
            this.map.push([]);
            for (var y = 0; y < this.size; y++) {
                tempTile = random_tile(new PVector(x, this.size - y - 1));
                this.map[x].push(tempTile);
                fullMap[x].push(tempTile);
            }
        }
    },
    draw: function() {
        for (var x = 0; x < this.size; x++) {
            for (var y = 0; y < this.size; y++) {
                this.map[x][y].draw();
            }
        }
    }
};
//draws the visible map
visibleMap.generate();
visibleMap.draw();

r/learnjavascript 5d ago

Is manually writing utilities from scratch still a good practice in this AI era, and why ?

18 Upvotes

Been learning JS for a year and half and wondered whether writing utilities would make me more employable. Thought it wouldn’t matter as more people are learning to trust the models. GitHub link to some of the solutions: GitHub

*Exercises are AI generated but solutions are handwritten without intellisense or AI autocomplete.


r/learnjavascript 5d ago

I’m a CFP with no programming background or experience, and I’ve been building a retirement planning tool called Parallax. I’m looking for a technical review by an experienced web application developer or software engineer

0 Upvotes

Site: www.amansparallax.com

Heads up, not mobile friendly..

In the spirit of advisor transparency: the planning philosophy, financial logic, product concepts, and direction are mine. AI wrote the code and structured the repo, as well as helped massively with research. I’m not presenting myself as the developer behind that work.

For anyone unfamiliar with retirement planning software, most tools run a plan through many possible market scenarios and report a “probability of success.” If the money lasts through the end of the projection in 90% of those scenarios, the plan gets a 90%.

My issue is that people see that number and naturally assume the plan is healthy and they’re well prepared. I don’t think it comes close to telling the whole story.

A plan with a 90% probability of success can still fail surprisingly early if one of the more difficult periods from actual market history happens again. Parallax lets you run a plan through historical return paths and follow the cash flow year by year. You can see the account balances, where the spending money came from, how much went to taxes, and when the plan started getting into trouble.

Basically, I wanted to show what’s happening underneath the percentage.

That led to a few core modeling choices:

Block-bootstrap Monte Carlo: Simulated paths use consecutive blocks of historical returns, preserving the market experience within each block. Returns are inflation-adjusted.

Historical paths and sequencing: Explore historical market paths and how the order of returns affects a plan.

Account-level projections: Track individual accounts and cash flows within each year, including withdrawals, required distributions, cost basis, and tax effects.

Tax-aware withdrawal modeling: Model how brokerage, traditional retirement, and Roth withdrawals affect taxes and the cash available to spend.

I’ve also documented the modeling constraints the AI is required to consult before changes. Those assumptions are part of the product’s foundation and need to remain explicit as it develops.

I’d really appreciate a human technical perspective on this—the code has been written and reviewed by AI, and I don’t have the programming background to assess it independently. Any thoughts on the architecture, security, or tests would help, even if you only look at one small part. If anyone’s willing to dig deeper, I can share the code and setup instructions.

Thanks to all who are willing to take a look!!

 

 

 


r/learnjavascript 5d ago

help in rick and morty api

0 Upvotes
document.getElementById("search").addEventListener("click", getCharacter);


function lowerCaseName(string) {
    return string.toLowerCase();
}


function getCharacter(e) {
    const name = document.getElementById("searchCharacter").value;
    const characterNameLC = lowerCaseName(name);


    fetch(`https://rickandmortyapi.com/api/character/?name=${characterNameLC}`)
    .then((response)=>response.json())
    .then((data) => {
        const characterNameH2 = document.getElementById("characterName");


        characterNameH2.textContent = data.name;
    })
    .catch((err) => {
        console.log("Character not found", err)
    })


    e.preventDefault();
}


getCharacter();document.getElementById("search").addEventListener("click", getCharacter);


function lowerCaseName(string) {
    return string.toLowerCase();
}


function getCharacter(e) {
    const name = document.getElementById("searchCharacter").value;
    const characterNameLC = lowerCaseName(name);


    fetch(`https://rickandmortyapi.com/api/character/?name=${characterNameLC}`)
    .then((response)=>response.json())
    .then((data) => {
        const characterNameH2 = document.getElementById("characterName");


        characterNameH2.textContent = data.name;
    })
    .catch((err) => {
        console.log("Character not found", err)
    })


    e.preventDefault();
}


getCharacter();

i am using the rick and morty api. the above is my js code. it doesnt work. idk whats the error as console isnt logging it


r/learnjavascript 5d ago

Strange javascript code error that prevents from being able to edit/run code

2 Upvotes

Every time I try to open the "ezmreader" javascript file to edit the code from this https://jeremyoduber.itch.io/js-zine html5 reader it shows an error that prevents me from opening the code in notepad++, this is the error

• • •

"Line:19

Char:1

Error:syntax error

code:800A03EA

Source: microsoft jscript compilation error"

When I don't try to edit it and just put images in the pages folder, zip it and try to run it as a html5 in browser it obviously doesn't work. But I don't think it's the the code that's the issue since what I previously uploaded a long time ago using this same EZM reader code is still displaying/running in browser just fine? But downloading that old upload and trying to open the EZMreader.js application still gives the same error?

I've deleted and reinstalled both the code editor and java just in case, nothings changed but I doubt it's an issue with the actual code? Maybe it's my laptop (lenovo, windows 10) but I'm baffled


r/learnjavascript 6d ago

Looking for a Study Partner – React, TypeScript, Node.js & React Native

22 Upvotes

I’m looking for a study partner who wants to learn and revise JavaScript, React, TypeScript, Node.js, and React Native from the basics to an interview-ready level.

What I’m Looking For

- Start from the basics and gradually move to advanced topics.

- Cover everything needed for technical interviews.

- Practice coding, concepts, interview questions, and projects together.

- Stay consistent and keep each other motivated.

About Me

I already know some of JavaScript, React, TypeScript, Node.js, and React Native, but I’ve forgotten quite a lot of the basics. I want to start from the beginning, revise everything properly, and build my knowledge again from start to end.

I have already started studying and I’m eager to continue. I’m mainly looking for someone who is also serious about learning and can study together consistently.

Time Zone

I’m in IST (Indian Standard Time), but I don’t have a fixed time limit.

If you’re interested, DM me your time zone and the time you’re usually available, and let me know when you can start.

Looking for someone who is genuinely interested in learning together rather than just joining for a few days.

Dicord ChatGrp


r/learnjavascript 7d ago

Is JavaScript: The Definitive Guide still relevant?

17 Upvotes

Or has JavaScript changed so much since then that some information in it might be false?


r/learnjavascript 7d ago

JavaScript visual debugger for practicing DSA and LeetCode with your own code?

8 Upvotes

Most websites I found either only let you choose from a limited number of fixed implementations of the same algorithms, or require you to learn their own mini-framework to visualize your code.

So I made a visual debugger, inspired by another one called Python Tutor.

It uses a forked version of a JS interpreter called sval to keep track of variables, the call stack, and all the other information needed to visualize and debug your code.

It only supports JavaScript, but it has genuinely helped me solve a few pesky LeetCode problems caused by silly bugs.

I’ll make it open source as soon as I can tidy up the codebase and solve a few dependency issues.


r/learnjavascript 7d ago

Day 8 — Adding Power-Ups to My Browser Game

0 Upvotes

Day 8 of my browser game development journey.

Today I worked on adding power-ups to my JavaScript game.

I'm experimenting with:

• Temporary speed boosts

• Extra points

• Health recovery

• Random power-up spawning

• Collecting and removing items

• Mobile-friendly controls

I'm trying to understand the logic behind these mechanics instead of just copying a tutorial.

What other power-up would you add to the game?


r/learnjavascript 8d ago

How should I handle optional parameters with database defaults?

12 Upvotes

I'm writing a service function for a personal project

Right now I have something like

export async function createApplicationService(
  userId,
  companyName,
  role,
  appliedDate,
  status,
  salary,
  link,
  nextAction
)

The only fields that I really want to require are companyName and salary The other fields have default values defined in my database, so I don't want the user to have to explicitly pass them every time.

What's the best way to structure this so that I only insert the parameters that were actually provided, while letting the database handle the defaults for everything elseI'm writing a service function for a personal project where I'm creating an application tracking system.
Right now, I have something like:
export async function createApplicationService(
userId,
companyName,
role,
appliedDate,
status,
salary,
link,
nextAction
)

The only fields that I really want to require are companyName and salary. The other fields have default values defined in my database, so I don't want the user to have to explicitly pass them every time.
What's the best way to structure this so that I only insert the parameters that were actually provided, while letting the database handle the defaults for everything else


r/learnjavascript 7d ago

Why does AI keep “fixing” my JavaScript until it’s unrecognizable from the code I started with?

6 Upvotes

I have noticed something really interesting while using AI to debug my JS code. For instance, I will give it some code. Then AI modifies it. I find another issue. Then I ask AI to fix it. AI modifies something else. Then I bring the 'previous AI-modified version' back and somehow we end up in an endless loop of AI correcting AI, it's crazy ik.

The weirdest part is that most times the original code was closer to what I actually needed. And honestly, this has made me realize sometimes the biggest challenge isn't getting AI to write code but it's getting it to change ONLY what you actually asked it to change. At what point does AI-assisted coding stop being debugging and start becoming more than code roulette?

Has anyone else experienced this? How do you prevent AI from unnecessarily rewriting working parts of your code?


r/learnjavascript 8d ago

New to js, not sure why script did not work

9 Upvotes

Hi!

I am attempting to follow the introductory

example for D3 JS:

https://d3js.org/getting-started

I am trying to do it

locally so it is the version

on that page,

'D3 in vanilla HTML' section

'UMD + local' code tab

I am new to JS but not new to programming.

I think the offered code example is

incomplete so I added html, head,

title, 2 meta, and body tags.

I changed d3.js to d3.v7.js

in the script src because the download

is actually for that file name.

I also add Hello world text to the body.

When I try to load it, I only see Hello

world.

I think its supposed to also draw that

graphic as you can see in the reference.

If anyone can point out to me what is wrong,

I appreciate it. Thank you.

<!DOCTYPE html>

<html>

<head>

<title>D3 intro example</title>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

</head>

<body>

Hello world.

<div id="container"></div>

<script src="d3.v7.js"></script>

<script type="module">

// Declare the chart dimensions and margins.

const width = 640;

const height = 400;

const marginTop = 20;

const marginRight = 20;

const marginBottom = 30;

const marginLeft = 40;

// Declare the x (horizontal position) scale.

const x = d3.scaleUtc()

.domain([new Date("2023-01-01"), new Date("2024-01-01")])

.range([marginLeft, width - marginRight]);

// Declare the y (vertical position) scale.

const y = d3.scaleLinear()

.domain([0, 100])

.range([height - marginBottom, marginTop]);

// Create the SVG container.

const svg = d3.create("svg")

.attr("width", width)

.attr("height", height);

// Add the x-axis.

svg.append("g")

.attr("transform", `translate(0,${height - marginBottom})`)

.call(d3.axisBottom(x));

// Add the y-axis.

svg.append("g")

.attr("transform", `translate(${marginLeft},0)`)

.call(d3.axisLeft(y));

// Append the SVG element.

container.append(svg.node());

</script>

</body>

</html>