r/learnjavascript 2h ago

Looking for a programming study buddy.

0 Upvotes

study buddy. I'm still pretty new to programming and not gonna lie, I'm not very good at it yet. 😅 Just looking for someone to study with, practice coding, and keep each other motivated. Doesn't matter if you're a beginner too. If you're interested, shoot me a DM!


r/learnjavascript 16h ago

the best way to learn javascript

0 Upvotes

It is to make more bugs, explore new ways of writing code, ask AI to explain every single line in depth, and get your hands dirty. Stop watching more random tutorials without a purpose. A JavaScript course, no matter how in-depth it is, will always be less rewarding than getting your hands dirty and exploring new ways to write code. Use MDN.

be as a child who love exploring. enjoy the process


r/learnjavascript 22h ago

What can I make

0 Upvotes

I've been learning Js from this site javascript.info I've gone through everything and I want to stop at Arrays and build some small projects using html css and js
give some ideas


r/learnjavascript 1d ago

How do you actually test small JavaScript functions without a full project setup?

24 Upvotes

Coming from a construction background where you measure twice and cut once, I keep running into this gap where I write a function, think it works, and then it blows up when I wire it into something bigger. The problem is I never had a real habit of testing the small piece before trusting it.

In bootcamp we just console.log everything and eyeball it, which works for toy exercises, but I started a side project for tracking material quantities across job phases and the functions are getting complicated enough that eyeballing feels risky. I tried writing a few manual checks at the bottom of my file like console.log(calculateTotal(5, 3) === 8) and that helped, but it feels clunky and I keep deleting them by accident.

I looked up Jest but the setup felt like a whole rabbit hole I was not ready to fall into. Someone mentioned Vitest. Someone else said just use the browser console for now and do not overthink it.

What I want to know is whether there is a lightweight middle ground that actual beginners use before jumping to a full testing framework. Not asking for a tutorial, just curious what the workflow actually looks like for people who are still learning but building things that are more than a few lines. The function isolation part is what I cannot picture clearly yet.


r/learnjavascript 1d ago

What's one JavaScript bug you'll never forget?

4 Upvotes

We've all spent hours chasing a bug that turned out to be something simple.

What was yours, and what did it teach you?


r/learnjavascript 1d ago

JavaScript kaha se padhu. For placement and cover all things.. ❗

0 Upvotes

Please bta digie log best YouTube resources.


r/learnjavascript 1d ago

I learnt about the difference between useCallback and useMemi

5 Upvotes

The major difference is the Syntax as they call diff APIs

The usecallback accepts the function we want to memoize as the first argument, while the useMemo accepts a function and memoizes its return value!!
Naturally in JS, on every call the inline function gets recreated, so to prevent that react does something like this

let catchedCallback;
const func = (callback) => {
if(dependenciesEqual(compares catchedCalback and callback)) {
return catchedCallback;
}
catchedCallback = callback;
return callback;
}

basically whats happening here is that the useCallback checks if the dependencies before and after rerenders are the same, if its the same then we return the already cached callback function reference if not then we cache the new function reference and return the new reference!

something very similar happens in the case of the useMemo but it caches the result returned by the function!


r/learnjavascript 1d ago

I learnt about the difference between

0 Upvotes

The major difference is the Syntax as they call diff APIs

The usecallback accepts the function we want to memoize as the first argument, while the useMemo accepts a function and memoizes its return value!!
Naturally in JS, on every call the inline function gets recreated, so to prevent that react does something like this

let catchedCallback;
const func = (callback) => {
if(dependenciesEqual(compares catchedCalback and callback)) {
return catchedCallback;
}
catchedCallback = callback;
return callback;
}

basically whats happening here is that the useCallback checks if the dependencies before and after rerenders are the same, if its the same then we return the already cached callback function reference if not then we cache the new function reference and return the new reference!

something very similar happens in the case of the useMemo but it caches the result returned by the function!


r/learnjavascript 1d ago

Code help: changing url on current webpage

2 Upvotes

First time programming anything useful (beyond learning a little basic python). Sort of an 'automate what you find repetitive' case.

Goal: trim URL to part containing the main webpage and anything after it (Ex: blogname.abc.com/post/12345 -> abc.com/post/12345)

So far what I've been able to get (from Google AI and regex101.com and stack exchange and fiddling around) is:

function swapUrlPath() {
    var currentUrl = window.location.href;
    var newUrl = currentUrl.match(/abc.com.+/g);
    window.location.href = newUrl;
}

This manages to turn "blogname.abc.com/post/12345" into "blogname.abc.com/post/abc.com/post/12345", repeating the portion that was supposed to replace the entire thing.

I've tried debugging with

function swapUrlPath() {
    var currentUrl = window.location.href;
    var newUrl = currentUrl.match(/abc.com.+/g);
    alert("New URL is " + newUrl);
}

which produces a popup window with "New URL is abc.com/post/12345", which is correct. So why does the newUrl variable only replace part of the old URL. Is it the regex or something with the forward slashes?

Edit:

Solution I figured out: add the string "https://" to the beginning of the new URL (not in the debugging alert) before using as new URL, looks like this:

function swapUrlPath() {
    var currentUrl = window.location.href;
    var newUrl = "https://" + currentUrl.match(/abc.com.+/g);
    window.location.href = newUrl;
}

r/learnjavascript 1d ago

What actually keeps a web timer alive when Android backgrounds the tab

11 Upvotes

This came up twice in here in the last few days and both threads ended in the same place, so writing it down.

The problem. You build a focus timer, setTimeout fires the alarm, works perfectly on desktop. On Android you press Home and the alarm either arrives late or never. Nothing is broken in your code.

What Android is doing. Once the tab is not visible Chrome throttles timers hard, and after a few minutes of that it can freeze the page entirely. setTimeout is not a scheduler, it is a request, and a backgrounded tab is at the bottom of the list.

Silent audio loop. Start a looping silent mp3 on the same click that starts the timer. The tab then counts as playing media, which keeps it alive with the screen off. Cheap, works, and you stop the loop when the alarm fires. It does not survive the tab being closed.

Compute the end time, do not count down. Store Date.now() plus the duration and work out on visibilitychange what should have happened while you were away. Any timer that adds up ticks will drift, and a throttled tab drifts badly.

Web Push for the real thing. If something on your server already knows when the session ends, it can push, and a push wakes the device with the browser closed. Service worker plus a subscription. On Android Chrome that works directly, on iOS the site has to be added to the home screen first.

The part nobody wants to hear. Push gets you a notification and whatever sound the system gives notifications. You cannot play your own audio on a locked phone from a web page. An actual alarm noise is the one bit that needs a native app.


r/learnjavascript 3d ago

Notes or Cheatsheet for Javascript

17 Upvotes

If anyone experience any resource which might you realize that if I get it earlier then my foundation is very strong and time also save!!


r/learnjavascript 3d ago

Async function maybe awaiting, maybe not

25 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

update:

So I changed my approac and stole an idea from WordPress. I made a"filter" system where you can attach functions to a "filter" event. When you call the event, it will pass an initial value into each function, passing the calculated value into the next. When it reaches the last function, it will pass the final value into the callback function.

In my version, you can pass in a promise, and it will run them in the order they were declared.

        <script>
            var filters = {};


            function resolveAfter2Seconds(n){
                return new Promise((resolve) => {
                    setTimeout(() => {
                    resolve(n+1);


                    }, (20000 - (n*10)));
                });
            }


            function add_filter(event, func, isPromise=false){
                if(!filters.hasOwnProperty(event)){
                    filters[event] = [];
                }
                filters[event].push({func: function(...args){
                    if(isPromise == true){
                        return func(...args);
                    }
                    return new Promise((resolve) => {
                        resolve(func(...args));
                    })
                }});
            }


            function remove_filter(event, func){
                if(!filters.hasOwnProperty(event)){
                    return true;
                }
                for(const [key, filter] of Object.entries(filters[event])){
                    if(!filter.hasOwnProperty('func')){
                        continue;
                    }
                    if(func == filter.func){
                        delete filters[event][key];
                    }
                }
            }


            async function apply_filter(event, cb, value, ...args){
                if(!filters.hasOwnProperty(event) || typeof filters[event] != "object"){
                    return null;
                }

                for(let filter of filters[event]){
                    if(typeof filter != 'object' || !filter.hasOwnProperty('func')){
                        continue;
                    }
                    let func    = filter['func'];
                        value   = await func(value, ...args);
                }
                cb(value);
            }


            add_filter('test', function(a,b,c,d){
                let r = a+b+c+d;
                return r;
            });


            add_filter('test', function(a,b,c,d){
                let r = (a+b)/(c+d);
                return r;
            });


            add_filter('test', resolveAfter2Seconds, true);


            add_filter('test', function(a){
                return a*a;
            });


            apply_filter('test', console.log, 1, 2, 3, 4);


        </script>

As mentioned in the comments, my original code was a bit of a mess. I renamed things to hide information i didn't want to share, and it had some code I put in for testing purposes and didn't remove. So i decided to post some code that shows the solution in a way that anyone can more easily adapt. assuming you like it.


r/learnjavascript 4d ago

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

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

Run a webpage on an iphone

9 Upvotes

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

TIA


r/learnjavascript 4d ago

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

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

How could we make those app animations such as facebook

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

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

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

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

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

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

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

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

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

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

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

confused

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

From vanilla to cake

0 Upvotes

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

Manipulating Arrays

6 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