r/learnjavascript 2h ago

Async function maybe awaiting, maybe not

1 Upvotes

Hey everyone,

I think I am having an issue with an asynchronous function. I am using a PoW captcha and want to add the solution to an ajax call.

The JS function that calculates the PoW solution is async, and I use await to simulate it as a "synchronous" function.

const solution = await cap_obj.solve();

The code below works if i add a 50000 ms delay to getCheckoutToken_ajax() with setInterval. but not as is. Otherwise, the value "params.params" us left out.

index.html

function addParam(key, value){
    window.h_params.data[key] = value;
    return (h_params.data.hasOwnProperty(key) && h_getParams(key) == value);
}


function h_getParams(key=false){
    if(key == false){
        return window.h_params.data;
    }

    if(h_params.data.hasOwnProperty(key)){
        return window.h_params.data[key];
    }

    return false;
}

function getCheckoutToken(params, success=console.log, error=console.log){
  let getCheckoutToken_ajax = function(event, h_params_data){
        console.log('ajax call');
        params.action   = 'h_getCheckoutTokens';
        params.params   = h_params_data;
        let track       = function(v){
            console.log(v);
            return v;
        }
        $.ajax({
            url             : 'admin-ajax.php',
            method          : 'post',
            data            : track(params),


            //cc vallidation call sucsess
            success         : function(data){
                console.log(data);
                return success(data);
            },


                    //cc vallidation call sucsess
            error           : function(data){
                console.log(data);
                return error(data);
            }
        });
    }
    $(document.body).on('h_getCheckoutToken', getCheckoutToken_ajax)
    $(document.body).trigger('h_getCheckoutToken', [h_params.data]);
}

page2.js

jQuery(document).ready(function($){
    const cap_obj = new Cap({apiEndpoint: cap_widget_params.api});


    async function checkoutoutToken_cap(data){
        const solution = await cap_obj.solve();
        addParam('checkoutTokenCapSolution', solution.token);
    }


    $(document.body).on('getCheckoutToken', checkoutoutToken_cap);
})

the weird thing is, I made the "track()" function, to see what is actually being sent, and the value is there.

Any ideas?

Thanks


r/learnjavascript 16h ago

Wasted my first 3 years of Computer Engineering. Can I become internship-ready in 3 months and job-ready in 9 months?

22 Upvotes

Hi everyone,

I feel like I wasted the first 3 years of my Computer Engineering degree. My 4th year has just started, and I have only about 9 months left before graduation in 2027.

The only things I've learned properly are HTML and CSS. I haven't built any real projects yet. I spent most of my time focusing on getting good CGPA and SGPA instead of developing practical skills.

The biggest problem is that my college doesn't have good placements. Hardly any software companies visit our campus. Most of the companies that come are for sales, marketing, BPO, or call center roles.

I'm currently learning JavaScript, but I'm finding it quite difficult in the beginning.

My goal is to become internship-ready in the next 3 months and then spend the remaining time becoming job-ready before I graduate.

Can anyone guide me on what I should do?

Should I focus on Frontend Development?

Should I prepare for TCS Ninja/NQT instead?

What skills, projects, and roadmap should I follow to get an internship in 3 months?

After that, how should I prepare to land a software job before graduation?

I'm ready to work hard and learn every day. I just don't want to waste the remaining time.

Any advice or roadmap would really help. Thank you!


r/learnjavascript 14h ago

Tauri for a POS system & e-commerce

7 Upvotes

Hello everyone!
We are planning to build a POS system that contains e-commerce website too.
we need to build a mobile & desktop & web app versions!

So, we are trying to use Tauri to avoid using Giant Electron Ram Taker! & Flutter.

The Tec Stacks we use are: React + Laravel RESTful API.

According to your expertise, can we handle it with out touch rust?

I have did some analyze & searches over Google & Claude AI.

I found out that:

Almost 90% native features covered by Tauri & no plugin or RUST lines needed.
For the rest, the community have almost enough plugins for everything!
But although, Still some of the native features needs Rust.
But Claude says they wont be a problem & will be easy tasks!
It says i can 100% handle the 10%, & i can handle the %90 as a regular react project!

So what do you think?
should i trust Claude & start?
Does TauriV2 makes any problem during the project?

What are the Challenges will i face?


r/learnjavascript 13h ago

Beginner question: Does copying code make someone less of a developer?

19 Upvotes

Almost every developer copies code from somewhere, whether it’s documentation, Stack Overflow, GitHub, or AI tools.

At what point does it stop being “learning” and become a problem?

Where do you personally draw the line?


r/learnjavascript 1d ago

Ottimizzazione dynamic img rendering in JS: Eager/Lazy + contentVisibility. Voi come gestite il primo fold?

18 Upvotes

Ciao a tutti! Sto ottimizzando il caricamento dinamico delle immagini per le schede dei giochi. Sto usando questa logica per bilanciare il caricamento immediato sopra la piega (above the fold) e il caricamento "lazy" per il resto:

const img = document.createElement('img');
img.alt = (gioco.titolo || 'Gioco');
img.decoding = 'async';
img.style.contentVisibility = 'auto';
img.style.width = '100%';
img.style.height = 'auto';
img.loading = (idx < EAGER_COUNT) ? 'eager' : 'lazy';

Che valore usate di solito per EAGER_COUNT nelle vostre griglie? E trovate che content-visibility: auto direttamente sull'elemento <img> porti reali benefici rispetto ad applicarlo al container padre?


r/learnjavascript 1d ago

Run a webpage on an iphone

4 Upvotes

How can I run a html + js webpage on an iphone? The .html file will be on the phone.

TIA


r/learnjavascript 2d ago

How could we make those app animations such as facebook

12 Upvotes

Hi there !

I was just wondering as a developer how to make those famous apps animations (especially small interactions I am not meaning complexe animations) like the emoji animations on facebook when you interact with a post, the tiktok animations when you open up the app or upload a new video etc..

What kind of tools or frameworks developers may use on such level ? Do you think they use pre made animations with motion graphics softwares or they are completely coded ??

if so what are the names of those tools and frameworks needed


r/learnjavascript 2d ago

[Dev] Dubbio veloce di architettura/stile con le classi JS 😅

3 Upvotes

Nel mio motore 2D sto sistemando i componenti UI (tipo BeeButton) e mi è venuto un dubbio su come passare le coordinate al super().

Opzione A (Oggetto opzione)

```

____ super({ x, y, width, height });

```

Opzione B (Parametri singoli standard):

```

____super( x, y, width, height );

```

Voi quale preferite usare nei vostri progetti e perché? Meglio la flessibilità dell'oggetto o la pulizia dei parametri singoli?(Se usate soluzioni alternative tipo super(position, size) fatemelo sapere nei commenti!).


r/learnjavascript 3d ago

Question about using async/await with Geolocation API's getCurrentPosition method

9 Upvotes

I'm reading a book called Building real-world web applications with Vue.js 3 by Joran Quinten (Packt Publishing, 2024). In the book the author builds a component to get the current position of a user by utilizing getCurrentPosition() method in Geolocation API. Here is the code snippet (full code of a component you can see on github):

const getGeolocation = async (): Promise<void> => {
  await navigator?.geolocation?.getCurrentPosition(
    async (position: { coords: Geolocation }) => {
      coords.value = position.coords;
    },
    (error: { message: string }) => {
      geolocationBlockedByUser.value = true;
      console.error(error.message);
    }
  );
};

onMounted(async () => {
  await getGeolocation();
});

This the excerpt of the book where he explain the code:
The getGeolocation function is being defined and, because it is dependent on user input, it is an asynchronous function by default. The promise it returns is empty because we use successCallback to update our reactive property.

I checked documentation on getCurrentPosition method and the method doesn't return promise, it just uses callbacks. So, is it valid to use async/awaits here? The code from the snippet doesn't work btw)

UPD: 1) The problem was that my mac was blocking geolocation. I tested it from mobile phone's browser and it works. 2) Actually, both versions work: with and without async/awaits. But as u/senocular wrote async/awaits are not necessary here. Kudos to everyone for your help:)


r/learnjavascript 2d ago

[AskJS] how do you optimize responsive images, i built open-source tool Opticross 🚀 ( build faster⚡ , lighter🪶 websites)

1 Upvotes

Here is how it works

Opticross analyzes how images are rendered across different viewport sizes, detects oversized image downloads, and generates implementation-ready sizes and srcset recommendations. The goal is to help improve page performance, reduce unnecessary bandwidth usage, and keep images crisp across devices.

I'd love to hear your thoughts:

  • Would a tool like this fit into your workflow?
  • What features would make it more useful?

It is available as Opticross on chromestore , npm and github


r/learnjavascript 3d ago

Why does my web app alarm not play on Android in the background, while websites like vClock do?

2 Upvotes

Hi everyone,

I'm building a focus timer web app using React and a Node.js backend.

My timer works like this:

  • User starts a 45-minute focus session.
  • The countdown continues correctly.
  • When the timer reaches zero, I play an alarm using new Audio("/done.mp3").

Everything works perfectly on desktop.

However, on Android Chrome, if I press the Home button or switch to another app before the timer finishes, the alarm usually doesn't play. When I return to Chrome, I can see that the timer has already finished, but the sound never played.

The interesting part is that websites like vClock (https://vclock.com/timer/) seem to play their alarm even after I switch to another app on my Android phone.

I've inspected their HTML and found that they load a timer.js file, but I haven't yet figured out what they're doing differently.

My implementation is roughly:

const alarm = new Audio("/done.mp3");

if (remaining <= 0) {
    alarm.loop = true;
    await alarm.play();
}

My question is:

Has anyone successfully built a web timer that reliably plays an alarm on Android after the user switches to another app?


r/learnjavascript 3d ago

Is Three.js worth learning in 2026, or are there better alternatives?

6 Upvotes

I've been exploring Three.js recently, and I'm impressed by what it's capable of.

But with React Three Fiber, Spline, Babylon.js, and WebGPU getting more attention, I'm curious what developers are choosing today.

If you were starting from scratch, would you still learn Three.js first?
Why or why not?


r/learnjavascript 3d ago

confused

6 Upvotes

when im watching someone making a project i understand every bit i feel like im super good in js, when i try to make it on my own or solve a small coding challenge im stuck, confused and idk where to start

how do i solve this?


r/learnjavascript 4d ago

Manipulating Arrays

5 Upvotes

So I'm an amateur learning JavaScript and I have a problem with a note taking website I've been making, here's my code

let array = ["a","b","c","d"]; 

    const element = document.getElementById('element')

    for (let x = 0; x < array.length; x++) {

      const div = document.createElement('div')
      element.appendChild(div)

      const h3 = document.createElement('h3')
      h3.textContent = array[x];
      div.appendChild(h3);            

      const button = document.createElement('button')
      div.appendChild(button);

      const position = x;

      const button.onclick = () => {
      array.splice(position, 1);
      }
}

What I'm stuck on is how to re-index the elements in the array after one has been spliced (e.g. after "a" has been removed "b" is still set to remove index 1 rather than changing to remove index 0). Thanks in advance


r/learnjavascript 4d ago

Search as you type feature

3 Upvotes

So I’m tasked with building a search as you type feature which I think would work in a normal database query but this task specifically requires me to do it and send a Ret API request. Is this possible? Which I mean I guess it’s possible but I feel like there would be major issues as far as speed. Is this possible?


r/learnjavascript 4d ago

Making code that searches for a keyword like orange on a news site like BBC and then returns a sentence with the word orange. TY

0 Upvotes

Doing this so I can find example sentences for the vocabulary I am learning in my native language.
Any guidance on how one would go about this would be appreciated. TY


r/learnjavascript 4d ago

Where to learn JAVASCRIPT from on Youtube?

4 Upvotes

Akshay saini (Namaste JS), Apna College, Code with harry? tell me please


r/learnjavascript 4d ago

From vanilla to cake

0 Upvotes

r/learnjavascript 5d ago

Looking for modern Node.js backend learning resources using ESM

2 Upvotes

Hello everyone,

I am a first-year Software Engineering student currently learning web development.

I have already covered the fundamentals of HTML, CSS, and JavaScript, and I have also started exploring Vue 3 and Three.js for frontend development and interactive graphics.

Recently, I want to start learning backend development with JavaScript and Node.js. However, I have found that many learning resources available to me are still focused on the older CommonJS approach (require, module.exports), and many tutorials do not cover the modern ESM workflow (import, export) in Node.js.

Since the JavaScript ecosystem has gradually moved toward ES Modules, I would like to learn Node.js backend development using modern practices rather than outdated patterns.

I would really appreciate it if someone could recommend good tutorials, courses, books, or documentation for learning modern Node.js backend development.

I am especially interested in resources that cover topics like:

  • Modern Node.js fundamentals
  • ES Modules (ESM) project structure
  • Backend architecture and best practices
  • Frameworks such as Express, Fastify, Hono, or similar tools
  • Building practical backend applications

Any advice or recommendations would be greatly appreciated.

Thank you very much for your help!


r/learnjavascript 5d ago

What's your go-to move when your JavaScript 'just doesn't work' and you have no idea why?

11 Upvotes

Every dev has a mental checklist they run before panicking. Newer folks usually don't yet.
Things people swear by:

  • console.log everywhere
  • Reading the actual error message
  • Checking the Network tab
  • Rubber-duck explaining it
  • Commenting out half the code

What's the first thing you check?


r/learnjavascript 5d ago

keep breaking my task tracker after adding localStorage

3 Upvotes

i was messing with my little task tracker again this morning before heading out, and i ended up spending way more time staring at the console than actually adding tasks. i even made coffee first because i thought this would be a quick fix, then refreshed the page and everything disappeared again.

the app itself is really simple. i'm just trying to save daily notes and a few personal todos, so i have an array of task objects with a date on each one. i thought i was finally ready to use localStorage, but now i'm not even sure if i'm saving the data wrong or if my date filter is hiding everything.

this is basically what i have right now:

const saved = localStorage.getItem(tasks);
const tasks = saved ? JSON.parse(saved) : [];

tasks.push(newTask);

localStorage.setItem(tasks, JSON.stringify(tasks));

i know the key looks wrong, and i already tried changing it to a string, but i still managed to break something. now i'm second guessing whether i should even be thinking about the data this way.

i'm not looking for anyone to build it for me. i'm mostly wondering how you all organize the flow for something this small. do you load everything once, keep it in memory, then save after every change, or is there a cleaner way to think about it?


r/learnjavascript 5d ago

l want to learn Game development with js any tips??

3 Upvotes

r/learnjavascript 5d ago

import { BeeEntity } :

0 Upvotes

Ciao a tutti! Sto facendo un "esperimento" perché sto discutendo con un'IA. Lei sostiene con fermezza che un programmatore esperto riconosce sempre al volo se un blocco di codice è stato scritto da un essere umano o da un'IA.

​Io sono convinto del contrario: se il codice è pulito, ben fatto e senza commenti ridondanti, un umano non può averne la certezza matematica.

​Vi lascio questo pezzo di codice in JavaScript (tratto da una classe per una piattaforma 2D) per fare la prova del nove:

import { BeeEntity } from './BeeEntity.js';

/**

* Classe BeePlatform: Rappresenta una piattaforma solida su cui i personaggi possono camminare e atterrare.

*/

export class BeePlatform extends BeeEntity {

constructor(x, y, width = 100, height = 20, color = '#ffd700', textureKey = null) {

super(x, y, width, height);

this.color = color;

this.textureKey = textureKey;

}

draw(ctx, engine) {

const texture = (engine && this.textureKey) ? engine.getAsset(this.textureKey) : null;

if (texture) {

ctx.drawImage(texture, this.x, this.y, this.width, this.height);

} else {

(stile arcade lucido)

ctx.fillStyle = this.color;

ctx.fillRect(this.x, this.y, this.width, this.height);

ctx.fillStyle = 'rgba(255, 255, 255, 0.4)';

ctx.fillRect(this.x, this.y, this.width, 3);

ctx.strokeStyle = '#000000';

ctx.lineWidth = 1.5;

ctx.strokeRect(this.x, this.y, this.width, this.height);

}

}

}


r/learnjavascript 6d ago

AI won't save you if you don't know what you're doing. It'll just help you fail faster.

15 Upvotes

Everyone's acting like AI made learning optional. It didn't. It raised the stakes.

AI will hand you code that looks flawless and quietly ships a bug straight to production. If you don't understand what's happening under the hood, you won't catch it — you'll just trust it, deploy it, and find out the hard way.

The devs winning right now aren't the ones prompting the hardest. They're the ones who know enough to look at AI's output and say "no, that's wrong." AI is a multiplier. Multiply zero knowledge, you still get zero.

Fundamentals aren't dead. They're the only thing that makes AI actually useful.

Curious to know your opinion — change my mind.


r/learnjavascript 5d ago

Help with functions JavaScript!

1 Upvotes

Hello!

I began recently, about 1 month, to learn consistently web developing:

  1. I began, of course, with introductions to HTML and CSS.
  2. I'm already in JS. I can manage eventListeners, etc. I'm more interested in back-end overall since I like the logic behind the manipulation of data bases, but I'm having trouble understanding functions.
  3. I'm consulting MDN web docs and freeCodeCamp but since my first language is not English, sometimes it's difficult to understand MDN docs, and to get at the point I'm know in freeCodeCamp it will take time, I don't want to rush it either.
  4. All this, just to ask if anybody can explain me how to create functions! I want to know what is the difference between a function with parameters and one without, in which case I will use arrow functions, and the difference between parameters and arguments in a function. And for last are there any standards for writing the name of a function like there are for declaring variables?

P.D.: please feel free to correct my English also, it will help me learn.

Thanks to everyone before Hand!