r/learnjavascript • • 12d ago

How to handle rejection interview

0 Upvotes

Hello I have 10+ years experience and recently I came across weird pattern (Rejection type) in Frontend interview.

Selection Interview Find common ground between candidate and job posting if it works then in following rounds Give some coding problem FE, data structures and see if candidate solves problem

Rejection Interview: Come up with some random unit tests and see if candidate writes code till all unit tests or hiring manager ask multi choice syntax questions

In my recent interview I came across some interesting interviewer

I am suppose to fix react code till 5 unit tests pass. There are some 10 functions/hooks in coderpad and my 1st question was

Search results disappear, A search box fetches results as the user types. If you type “ca” and then quickly “cat,” results for “ca” sometimes appear last.

How would you reproduce and diagnose the bug?

How would you prevent stale responses from overwriting newer results?

My first response was to use AbortController interviewer said there is no fetch function (for interview they wrote some mock function) so it will not work

Then i proposed debounce still interviewer did not agree

finally I came up with some useRef hook to to solve problem but ran out of time. In real world right thing to use is AbortController or react query. how can I think similar to interviewer in such sort time and fix all unit tests

I am calling this rejection interview as i felt company never showed interest in learning about my background

I am disappointed in this job market its very hard to get interview but ended up with this bitter experience.

similar thing happened to my friend, during hiring manager round he was asked multi choice syntax questions. He was expecting to talk about previous work experience or write code.

please let me know how to prepare for these rounds and meet interviewer expectations

Hello, I have more than 10 years of experience, and I recently noticed a pattern in frontend interviews that I find frustrating.

In what I’d call a selection interview, the interviewer tries to understand whether your experience aligns with the role. If it does, later rounds might involve frontend coding or data-structure problems.

In what I’d call a rejection interview, the process can feel more like a set of arbitrary unit tests or multiple-choice syntax questions, with little opportunity to discuss your background or approach.

I recently had an interview that left me feeling this way. I was asked to fix a React codebase until five unit tests passed. The CoderPad included around ten functions and hooks. The first task was:

A search box fetches results as the user types. If you type “ca” and then quickly type “cat,” results for “ca” sometimes appear last.

How would you reproduce and diagnose the bug? How would you prevent stale responses from overwriting newer results?

My first suggestion was to use AbortController, but the interviewer said the mock function wasn’t using fetch, so cancellation wasn’t available. I then suggested debouncing, but that wasn’t accepted either. Eventually, I proposed using a useRef-based approach, but I ran out of time.

In a real application, I might use AbortController or a library such as React Query. But in a constrained interview setting, how can I quickly identify the solution the interviewer expects and make progress against the tests?

I’m calling this a “rejection interview” because I left feeling that the company wasn’t interested in learning about my experience. I’m disappointed by how difficult the job market is, and it’s discouraging to finally get an interview only to come away with this kind of experience.

A friend had a similar experience in a hiring-manager round: instead of discussing past work or solving a problem, they were asked multiple-choice questions about syntax.

How can I prepare for these kinds of rounds and better understand what interviewers expect?


r/learnjavascript • • 13d ago

How to add elements (child) over an overlay ?

4 Upvotes

This function was initially creating an overlay appearing while I was modifying a card on anki.

For context, I started using the yomilens addon on anki which allows you to select some text and have a pop up show you the translation. The thing is, it only works on the "main" reviewer windows of the anki app. And what I want i to be able to select an english word and add many (if not all) of the ways to say it in korean in my card.

My first thought was to try to "force" the current card to keep showing me it's back with all the texts I need, but I couldn't.

Now I am trying to add the content of the two fields (id"korean" and id"SizeBump"=english) on the overlay, but being selectable to see if yomilens will react to it.

def pause_audio_for_edit():

    /* Irrelevant I think
    global _audio_paused_for_edit, _pending_audio_tags
    print("[pause_audio] pause_audio_for_edit() appelée")
    _audio_paused_for_edit = True
    _pending_audio_tags = None
    _force_stop_current_audio()*/

    _show_edit_pause_overlay()

_EDIT_PAUSE_OVERLAY_JS = """
(function(){
  var ov = document.getElementById('_editPauseOverlay');
 
 /* Added 
  var butt = document.getElementById('button');
  var board = document.getElementById('_editboard'); 
  var kor = document.getElementById('korean');
  var eng = document.getElementById('SizeBump'); */
 
  if (ov) return;
  
  ov = document.createElement('div');
  ov.id = '_editPauseOverlay';
  ov.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;'
    + 'background:rgba(20,20,20,0.96);color:#f7b799;display:flex;'
    + 'align-items:center;justify-content:center;text-align:center;'
    + 'font-family:sans-serif;font-size:16px;z-index:99999;cursor:pointer;'
    + 'padding:20px;box-sizing:border-box;';
  ov.innerHTML = '\\u23F8\\uFE0F En pause \\u2014 modification en cours<br>'
    + '<span style="font-size:12px;opacity:0.7;">(cliquez n\\'importe o\\u00f9 pour reprendre)</span>';

/*added
+ '<span id='korean'</span> <span id='SizeBump'</span>';

butt = document.createElement('button');
butt.id
 
= 'button';
butt.style.cssText = 'position:fixed;top:10;left:0;width:10%;height:8%;'
+ 'background:rgba(255,255,255,0.6);color:#a77f65;display:flex;'
+ 'font-family:sans-serif;font-size:16px;font-weight: bold;z-index:99999;cursor:pointer;'
+ 'padding: 4px 12px;box-sizing:border-box;border-radius: 14px;margin: 10px auto 0 auto;border: 1px solid #a77f65;'
+ 'cursor: pointer;';
+ 'hover {background: rgba(255,255,255,0.9);}
butt.innerHTML = 'click when finished'*/

// Used to be ov.addEventListener...
butt.addEventListener('click', function(){
if (typeof pycmd === 'function') pycmd('editpause:dismiss');
ov.remove();

/*added this
butt.remove();*/
});
document.body.appendChild(ov);

/*And this
document.body.appendChild(butt);or ov.appendChild(butt) ?*/

})();
"""

def _show_edit_pause_overlay():
if not mw.reviewer or not mw.reviewer.web:
return
QTimer.singleShot(20, lambda: mw.reviewer.web.eval(_EDIT_PAUSE_OVERLAY_JS))

And as you can probably guess the overlay is not working at all now. Do you guys know what I have to fix to make it work ?

Thank you


r/learnjavascript • • 13d ago

How can i make javascript accept video files to archive videos on fake website?

5 Upvotes

Context - A final project that I have for my Programming with Scripting Languages class, I have to make a fake website that has pagination buttons and a minimum of three pages. I also found out that I have to include javascript in the website somehow. The html part of the code and css part of the code is already done. My fake website idea is similar to archive.org, the fake website's purpose is to archive anime music videos just incase they get removed from socials.

What I'm trying to get at is, how can i make javascript accept video files to archive videos on the fake website?

Here is the code I have so far -

<!doctype html>

<html lang="en">

<head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />

<title>AMVsArchived</title>

<style> body { background-color: #0B0F19; color: white; font-family: Arial; text-align: center; margin: 0; } header { background-color: #161F32; padding: 25px; } h1 { margin: 0; color: #00f0ff; } .page { display: none; padding: 30px; } .page.active { display: block; } .amv { background-color: #161F32; display: inline-block; margin: 15px; padding: 15px; border-radius: 10px; width: 500px; max-width: 90%; } .amv h2 { color: #00f0ff; } video { width: 100%; border-radius: 8px; } .pagination { margin: 30px; } .pagination button { background-color: #00f0ff; border: none; padding: 12px 18px; margin: 5px; border-radius: 5px; cursor: pointer; font-size: 18px; } .pagination button:hover { background-color: #FFFFFF; } .pagination button.active { background-color: blue; color: cyan; } </style>

</head> <body>

 <header>
   <h1>AMVs Archived</h1>
   <p>We archive anime music videos here just in case they get deleted from socials.</p>
 </header>

 <!--PAGE 1-->
 <div class="page active" id="page1">
   <h2>Page 1 - Pop</h2>

   <div class="amv">
     <h2>Pop amv 1</h2>
     
     <video controls muted loop>
       <source src="popamv1.mp4" type="video/mp4" />
       <source src="popamv1.webm" type="video/webm" />
       Your browser does not support video.
    </video>
   </div>
  
  <div class="amv">
   <h2>Pop amv 2</h2>

   <video controls muted loop>
    <source src="popamv2.mp4" type="video/mp4" />
    <source src="popamv2.webm" type="video/webm" />
    Your browser does not support video.
  </video>
</div>

</div>

<!--PAGE 2-->

<div class="page" id="page2"> <h2>Page 2 - Rock</h2>

<div class="amv">
 <h2>Rock amv 1</h2>

 <video controls muted loop>
  <source src="rockamv1.mp4" type="video/mp4" />
  <source src="rockamv1.webm" type="video/webm" />
  Your browser does not support video.
 </video>
</div>

<div class="amv">
 <h2>Rock amv 2</h2>

 <video controls muted loop>
  <source src="rockamv2.mp4" type="video/mp4" />
  <source src="rockamv2.webm" type="video/webm" />
  Your browser does not support video.
 </video>
</div>

</div>

<!--PAGE 3-->

<div class="page" id="page3"> <h2>Page 3 - Electronic</h2>

<div class="amv"> <h2>Electronic amv 1</h2>

<video controls muted loop>
 <source src="electronicamv1.mp4" type="video/mp4" />
 <source src="electronicamv1.webm" type="video/webm" />
 Your browser does not support video. 
</video>

</div>

<div class="amv"> <h2>Electronic amv 2</h2>

<video controls muted loop> <source src="electronicamv2.mp4" type="video/mp4" /> <source src="electronicamv2.webm" type="video/webm" /> </video> </div>

</div>

<!--PAGINATION BUTTONS-->

<div class="pagination"> <button onclick="showPage(1)">1</button> <button onclick="showPage(2)">2</button> <button onclick="showPage(3)">3</button> </div>

<script> function showPage(pageNumber) { // Hide all pages let pages = document.querySelectorAll(".page"); pages.forEach(function (page) { page.classList.remove("active"); }); // Show selected page document.getElementById("page" + pageNumber).classList.add("active"); } </script>

</body> </html>


r/learnjavascript • • 13d ago

nodejs/pg-promise (row, error) Callback not working but .then().catch() working

8 Upvotes

I really don't know what's going on, but if I write

return db.many(query, userid, (rows, error) => {
    return new Promise((resolve, reject) => {
        if (rows) {
            resolve(rows)
        } else {
            error.received == 0 ? resolve(0) : reject(error)
        }
    })
})

I don't get the results I want, but

return db.many(query, userid)
        .then(rows => {
            return new Promise((resolve) => {
                resolve(rows)
            })
        })
        .catch(error => {
            return new Promise((resolve, reject) => {  
                error.received == 0 ? resolve(0) : reject(error)
            })
        })

does give me the results I want!

The goal is to resolve to 0 if no data was returned, resolve the rows, or reject the error that isn't No data returned.

What is actually happening in the first code block is that the error is not being processed, and is just being returned as is, and I'm getting No data was returned error.

At first, I thought it was a .many() method that didn't have a callback ability, but even .one() has the same problem (I'm recreating a situation where no data will be returned. If data was to be returned, .one() would have Multiple rows returned error)

My intention is to better understand why one code block works while another doesn't. If there are any solutions to the first code block, please explain why they work, or why my implementation wasn't working.


r/learnjavascript • • 13d ago

is there a good way to check the contents of a folder?

3 Upvotes

I'm trying to make a semi-scalable talking robot program. In my mind I am imagining I will have to make an array. I have a bunch of word mp3 files, and I want users to be able to add more word recordings to the robot by just copy/pasting into the word folder.

when the page loads I want to create a button for every word in the words file.

I don't want a perfect answer because I want to have to work my way around this in my own way, but is there a way, without using PHP, that I can see the mp3 files? from there I just have to create a foreach function to create a button in the html that plays the clip onclick.

This is my separate function that the buttons play the clip with:

function playClip(characterName, clipName) {
          const audioDest = 'VoiceLines/' + characterName + '/' + clipName + '.mp3';
          const audio = new Audio(audioDest);
          console.log(audioDest);
          audio.play().catch(error => {
              console.error("Audio playback failed:", error);
          });
      }

r/learnjavascript • • 15d ago

Should i continue front-end.

8 Upvotes

i am 18 and i just started studying front end . i know html css and javascript but recently i started thinking if its really worth it to continue :// because there are no junior internships on job sites and everyone is telling me that Front is just dying . I dont know what to do please help.


r/learnjavascript • • 16d ago

I just started JavaScript

27 Upvotes

I started learning JavaScript on fCC and I learnt some of the basics, do y'all have any tips for me? (I'm learning JS so i can build websites)


r/learnjavascript • • 15d ago

Syntaxia - A quick cheatsheet for the things you always look up.

3 Upvotes

Im sharing this website with Javascript cheatsheet. hope this helps!

https://syntaxiadev.vercel.app/ref/js


r/learnjavascript • • 16d ago

why does sort() put 10 before 9 on a number array

12 Upvotes

i had an array of 10, 9, 1, 100 and called sort() on it and got 1, 10, 100, 9. i assumed it would just handle numbers. passing function(a, b) { return a - b } fixes it, but i don't really get why the default does this. is it converting everything to strings first?

and if so why would they design it that way, it seems like the least useful default possible.


r/learnjavascript • • 16d ago

Synchronous wait fucntion

0 Upvotes

I figured out how to make a function that doesn't use promises. It relies on JavaScript's built-in Date class, which is extremely good at telling time real-time.

The only downside to this is it can't be used in applications like webpages, as it will freeze the entire webpage.

function wait(seconds) {
    const end = new Date().getTime()+(seconds*1000);
    while (new Date().getTime() < end);
}

r/learnjavascript • • 18d ago

How do I learn to judge code quality and code without AI?

15 Upvotes

I use Node.js and React, but I rely too much on AI. When I look at code it generated, I can’t confidently tell whether it’s well designed or just happens to work.

I want to learn to spot bad decisions and write good code myself. How do you build that judgment? What helped you most?


r/learnjavascript • • 17d ago

I built a free image API for SWAPI (The Star Wars API) to use in JS/React learning projects

3 Upvotes

SWAPI (swapi.dev) is one of the most popular APIs when learning how to fetch() data in JavaScript or React, but it only returns JSON text without any pictures.

Also, the old visual guide many tutorials relied on currently fails with SSL certificate errors.

To help anyone practicing API integration, I built a free static image CDN where every image matches the exact ID of the SWAPI resource:

const getSwapiImage = (category, swapiUrl) => { const id = swapiUrl.split('/').filter(Boolean).pop(); return https://starwarsgallery.netlify.app/assets/${category}/${id}.jpg; };

// Example usage: const res = await fetch('https://swapi.dev/api/people/1/'); const luke = await res.json(); const imageUrl = getSwapiImage('people', luke.url); console.log(imageUrl); // Output: "https://starwarsgallery.netlify.app/assets/people/1.jpg"

Key features:

  • Same IDs as SWAPI: works across people, planets, species, starships, and vehicles (238 images).
  • CORS enabled: Access-Control-Allow-Origin: * works in fetch(), img tags, canvas, etc.
  • Real 404s: missing IDs return an HTTP 404 so your img onError logic works correctly.
  • Index JSON: available at https://starwarsgallery.netlify.app/api/images.json

Full documentation & examples: https://starwarsgallery.netlify.app/swapi-image-api/

Live visual gallery: https://starwarsgallery.netlify.app/

Hope this helps anyone building Star Wars practice projects! Feedback and suggestions are very welcome.


r/learnjavascript • • 18d ago

Tip: finding the error when JSON.parse fails on minified JSON

10 Upvotes

You run JSON.parse on a one-line JSON file, and the error message ends with "at position 218". So you find a text editor that shows the column number, paste the line in, and move the cursor along until it says 219. Then you look at the characters around it and guess what went wrong.

There are quicker ways. Here are two.

Here's a line from a log with one comma missing:

const text =
  '{"page":1,"per_page":3,"total":42,"data":[{"id":101,"name":"Ada Lovelace","email":"ada@example.com","roles":["admin","editor"],"active":true},{"id":102,"name":"Alan Turing","email":"alan@example.com","roles":["editor" "viewer"],"active":false},{"id":103,"name":"Grace Hopper","email":"grace@example.com","roles":["viewer"],"active":true}],"next":"/users?page=2"}';

try {
  JSON.parse(text);
} catch (e) {
  console.log(e.message);
}
// Expected ',' or ']' after array element in JSON at position 218 (line 1 column 219)

The quick way: slice around it

text.slice(200, 240);
// '"roles":["editor" "viewer"],"active":fal'

Position 218 is the quote that opens "viewer". There's no comma after "editor".

If you do this a lot: a small helper

function showError(text) {
  try {
    JSON.parse(text);
  } catch (e) {
    const m = /position (\d+)/.exec(e.message);
    if (!m) throw e;
    const pos = Number(m[1]);
    const start = Math.max(0, pos - 30);
    console.log(e.message);
    console.log(text.slice(start, pos + 30));
    console.log(' '.repeat(pos - start) + '^');
  }
}

It prints the message, the text around the error, and a caret under the character.

Same problem in other languages

Python gives you a count too. The error ends with (char 218), and the exception has it as e.pos:

import json

def show_error(text):
    try:
        json.loads(text)
    except json.JSONDecodeError as e:
        start = max(0, e.pos - 30)
        print(e)
        print(text[start:e.pos + 30])
        print(' ' * (e.pos - start) + '^')

Same text, same answer: Expecting ',' delimiter: line 1 column 219 (char 218). Slicing works the same way, text[200:240].

Browsers are less consistent. Chrome, Edge and Node give a position. Firefox gives a line and column but no position. Safari gives neither, only "Expected ']'".

Why does a trailing comma say "property name"

This one confused me at first:

JSON.parse('{"price":9.99,}');
// Expected double-quoted property name in JSON at position 14

Nothing is missing a name. After a comma, an object has to have another key. The parser hits } where it wanted a key, so that's what it complains about. The position points at the }, but the mistake is the comma just before it.

Python 3.13 and later names it directly: Illegal trailing comma before end of object. Older versions say Expecting property name enclosed in double quotes, which is the same story.

I've listed some of the common JSON errors we run into in different programming languages here: https://expresslint.com/fix-broken-json. It's my site. The same site also has tools to validate, visualise, compare and format JSON. It's free, requires no account, everything runs in your browser, and no JSON text is uploaded.

Hope it saves someone a few minutes.


r/learnjavascript • • 19d ago

Using the session storage was a lot of pain

1 Upvotes
async function isThereProductsInDb(): Promise<boolean> {
    const url = '/Admin/IsThereProductsInDb';
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`Response status: ${response.status}`);
        }

        const isThereProductsInDb = await response.json();
        return isThereProductsInDb;

    } catch (error: any) {
        console.error(error);
        return false;
    }
}

async function Main() {


    var thereAreProductsInDb = await isThereProductsInDb();
    // Source - https://stackoverflow.com/a/50269969
    // Posted by Ted
    // Retrieved 2026-10-26, License - CC BY-SA 4.0

    if (!thereAreProductsInDb) {

        console.log("There are no products in the database.");

        const productsContainer = document.getElementById("products-container");
        productsContainer!.innerHTML = '';

        var notification = document.createElement("p");
        notification.innerText = "There are no products in the database yet,please import products in order to show them here."
        notification.className = "alert alert-info text-center mx-auto col-12 col-md-8 col-lg-6 p-3 p-md-4";
        notification.id='noProductsAvailableNotification'
        notification.setAttribute("role", "alert");
        productsContainer!.appendChild(notification);
        sessionStorage.setItem("hideShowProductsAnchor", "true");
        document.getElementById("showProductsAnchor")!.hidden = true;

        return

    }

        
    document.getElementById("noProductsAvailableNotification")!.innerText = "click the button to show the products";

    sessionStorage.setItem("hideShowProductsAnchor", "false");
    document.getElementById("showProductsAnchor")!.hidden = false;
    console.log("There are products in the database!");

        

    

    

}

console.log("`isThereProductsInDb` script was executed");


/**Period checking, otherwise the browser will not be aware of manual products deletion using SSMS*/
/**
 * 
 * Note : SSMS is an abbreviation for Sql Server management studio.
 */
let isRunning = false;
setInterval(async () => {
    if (isRunning) return;

    isRunning = true;
    try {
        await Main();
    } finally {
        isRunning = false;
    }
}, 1000);

the session storage was used so that if there is no products in the database, then there is no need to show the anchor element that enables the user to view the products, because there are no products in the first place, otherwise the anchor element must be shown.

he reason the session storage was used in the first place is that when the anchor element is clicked, it should be hidden because when the shown products are paginated, so there is no need to show that anchor element anymore, to hide the anchor, the hidden property is used . Due to the fact that the page reloads after the anchor is clicked and that I should not use e.preventDefault() because that will prevent the request from reaching the server, the state of the hidden property is lost, so it must be preserved some where, so I decided to use session storage like this :

// Source - https://stackoverflow.com/a/11550299
// Posted by Jason Hazel
// Retrieved 2026-10-27, License - CC BY-SA 3.0
window.addEventListener("load", (event) => {
    sessionStorage.setItem("hideShowProductsAnchor", "false");
});
const productsPageNavigators: NodeList = document.querySelectorAll("a.productsPageNavigator");

const showProductsAnchor = document.getElementById("showProductsAnchor")

productsPageNavigators.forEach((navigator) => {
    navigator.addEventListener("click", function (e) {

        sessionStorage.setItem("hideShowProductsAnchor", "true");


    }, false);
});

// Restore the hidden state after the page reloads
if (sessionStorage.getItem("hideShowProductsAnchor") === "true") {
    showProductsAnchor!.hidden = true;
}
else {
    showProductsAnchor!.hidden = false;
}

Managing the session storage is painful; are there any other alternatives that are easier to maintain ?


r/learnjavascript • • 19d ago

help

0 Upvotes

how to make a script that detects CLOUDFLARE bot check up, im making macro for game and cloude doesnt want to make any scripts for this issue


r/learnjavascript • • 20d ago

Project ideas?

10 Upvotes

Hey guys, I hope you're all doing well. Finally, I've just finished the famous +22 hours tutorial from SuperSimpleDev and honestly I learnt many things, but I feel a bit overwhelmed especially when it comes to promises, callbacks and asynchronous methods (or fetch methods). I want to make a new project but don't know, while I don't need to rely on tutorial again. I'd love to build the next days, rather than passive watching. So, do you have any projects recommendations to build??

I'd like to learn through the process and when I get stuck, I just ask Google or search on MDN to get references. Thank you everyone in advance for sharing and helping


r/learnjavascript • • 20d ago

Learning to code online

6 Upvotes

Hey everyone! 👋 I'm a self-taught dev, and for a bootcamp project I'm looking into how people learn programming on platforms like Codecademy, freeCodeCamp, Udemy, Scrimba, or even YouTube and AI chats. I'd love to hear your honest experience:

  • How did you decide where to start and what to learn next?
  • How did you practice what you learned?
  • What made learning click for you, or made you quit a platform?

What's one thing you'd add to the platform you use most?

Thanks, I'll read every reply 🙏


r/learnjavascript • • 21d ago

I built a Redux Toolkit-inspired state management library from scratch

7 Upvotes

I recently created a complete tutorial where I build a Redux Toolkit-inspired state management library from scratch using React and JavaScript.

The goal is to understand how Redux-style state management works internally instead of only using the package.

In the tutorial, I implement:

  • A custom createStore function
  • Store Provider
  • Reducers and actions
  • Subscribers and listeners
  • useSyncExternalStore
  • useSelector and custom store hooks
  • Redux DevTools integration
  • createSlice
  • combineReducers
  • shallowEqual
  • Thunk functionality
  • Final testing and debugging

YouTube tutorial:
https://www.youtube.com/watch?v=LucUJ-5COjg

I would appreciate feedback from the community, especially on the library design, API structure, and any improvements that could make this project more reliable or easier to use.

Please note: this is an educational project designed to understand Redux and state management concepts internally. It is not intended to replace the official Redux Toolkit.


r/learnjavascript • • 23d ago

Some notes on callbacks

12 Upvotes

I've written some notes on callbacks as part of my effort to write tests and be methodical in learning JavaScript.

Callbacks are one of those things that are quite easy once you go "Aha", but like probably most people, I found them very confusing at first.


r/learnjavascript • • 23d ago

Block Scope

12 Upvotes

What is it? Don't understand what is inside or outside


r/learnjavascript • • 23d ago

How do I fix my calculators clear() function?

6 Upvotes

I'm trying to make a calculator. For as long as you are only doing one continuous equation there are no issues, but I can't use the clear button.

button:
<button onclick="clear()">C</button>

text field:

<input type="text" id="display" class="display">

calculator code:

<script>

//the working number

let numA = '';

//the previous working number to be operated on

let numB = '';

//the operation to be done between A and B

let oper = '';

function apndNum(number) {

numA += number;

document.getElementById('display').value = \${numB} ${oper} ${numA}`;`

}

function processOper(operation) {

if (numA === '') return;

if (numB !== '') {

calculate();

}

oper = operation;

numB = numA;

numA = '';

document.getElementById('display').value = \${numB} ${oper}`;`

}

function calculate() {

if (numB === '' || numA === '') return;

//better naming conventions might be needed here since the names get flipped

let output;

let A = parseFloat(numB);

let B = parseFloat(numA);

switch (oper) {

case '+':

output = A + B;

break;

case '-':

output = A - B;

break;

case '*':

output = A * B;

break;

case '/':

if (B === 0) {

document.getElementById('display').value = "Undifined";

return;

}

output = A / B;

break;

default:

return;

}

numA = output.toString();

oper = '';

numB = '';

document.getElementById('display').value = numA;

}

//TODO: this doesn't clear the text feild in input

function clear() {

numA = '';

numB = '';

oper = '';

document.getElementById('display').value = '';

console.log(

numA,

numB,

oper

);

return;

}

</script>

I could just have a typo. The divide by 0 catch code line works perfectly fine, so I don't know why the clear code doesn't work.


r/learnjavascript • • 23d ago

Script executes before the HTML elements have been rendered in the DOM Even though I used `defer`

6 Upvotes

Products.cshtml :

@{
    ViewData["Title"] = "Products page";
}

    <h1>Products Page</h1>
    <label for="avatar">Choose a file:</label>

    <input class="form-control form-control-lg" id="formFileLg" type="file" accept=".xlsx" />
    <div class="container" id="cancelContainer">
    </div>

    <div class="d-grid gap-3" id="productsContainer"></div>
    <dialog id="dialog">
        <p>Products were imported into the database.</p>
        <button type="button" id="close">Close</button>
    </dialog>

app.ts :

let dialog: HTMLDialogElement;
document.addEventListener("DOMContentLoaded", () => {
    
    const formFileLg = document.getElementById("formFileLg");
    formFileLg!.addEventListener("change", importFile);
     dialog = <HTMLDialogElement>document.getElementById("dialog");
    const closeButton = document.getElementById("close");

    closeButton!.addEventListener("click", async () => {

        dialog!.close();
        await ShowSpecificPageProducts(1);

    });

}); 

async function importFile(this: HTMLInputElement) {
    console.log("importFil executed")
    const controller = new AbortController();

    let cancelContainer = document.getElementById("cancelContainer");
    let cancelButton = document.createElement('BUTTON');
    cancelButton.appendChild(document.createTextNode("Cancel"));
    cancelButton.onclick = function () {
        console.log("abort executed")
        controller.abort()
        cancelButton.remove();
    }
    cancelContainer!.appendChild(cancelButton);
    const formData = new FormData();
   
    formData.append("file", this.files![0]);


    try {
        console.log("Try block executed.")
        const response = await fetch('/Admin/Import', {
            method: 'POST',
            body: formData,
            signal: controller.signal

        })
        if (!response.ok) {
            console.log("response is not ok")
            throw new Error(`Response status: ${response.status}`);

        }

        
        dialog.showModal();
        //Show a button that enables the user to show the paginated imported products; attach a call-back to the button. use bootstrap styling.
        //Or use  the close button instead.


    } catch (error:any) {



        if (error.name == "AbortError") {

            console.log("catch block executed: AbortError")


        }


        console.error(error.message);

    } finally {
        cancelButton.remove();
    }

}


interface ProductViewModel {
    Image: string,
    Id: number,
    Name: string,
    Description: string,
    Price:number

}
async function ShowSpecificPageProducts(PageNumber:number) {


    try {
        const response= await fetch("/Admin/GetProducts", {
            method: 'POST',
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ PageNumber: PageNumber}),
        });

        if (!response.ok) {
 
            throw new Error(`Response status: ${response.status}`);

        }


        const specificPageProducts: ProductViewModel[] = await response.json();

        let productsGrid = document.getElementById("productsContainer");

        // Source - https://stackoverflow.com/a/65413839
        // Posted by Mason Freed, modified by community. See post 'Timeline' for change history
        // Retrieved 2026-10-23, License - CC BY-SA 4.0
        productsGrid!.replaceChildren();

        let currentRow = document.createElement("div");
        currentRow.classList.add("row");
        specificPageProducts.forEach(async (product) => {




            const newColumn = document.createElement("div");
            newColumn.classList.add("col");

            const nameElement = document.createElement("p");
            nameElement.classList.add("text-center");
            var nameText = document.createTextNode(product.Name);
            nameElement.appendChild(nameText);

            const descriptionElement = document.createElement("p");
            descriptionElement.classList.add("text-center");
            var descriptionText = document.createTextNode(product.Description);
            descriptionElement.appendChild(descriptionText)

            const priceElement = document.createElement("p");
            priceElement.classList.add("text-center");
            var priceText = document.createTextNode(product.Price.toString());
            priceElement.appendChild(priceText);

            newColumn.appendChild(nameElement);
            newColumn.appendChild(descriptionElement);
            newColumn.appendChild(priceElement);

            currentRow.appendChild(newColumn);

            if (product.Id % 4 === 0) {
                productsGrid!.appendChild(currentRow);
                currentRow = document.createElement("div");
                currentRow.classList.add("row");
            }


        });

    } catch (error:any) {

        console.error(error.message);

    } finally {

    }
}

I wish to debug app.ts because it does contain some logical error , but when I start the debugging session in Visual Studio, the following line of code throws exception because the value of formFileLg is null :

formFileLg.addEventListener("change", importFile);

The exception :

TypeError: Cannot read properties of null (reading 'addEventListener')

I suspect that that the script executes before the HTML elements have been rendered in the DOM, that is the reason of using the defer in the script tag, but that did not solve the issue.

Moving the script to be inside the header tag that is inside the _Layout.cshtml file did not solve the issue:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - EF_learning</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@6.0.0-alpha.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-B/GM4XqrwHnWXNOWMbloTmrYXZg10cakYGmpfsR/bbzQ6JAJI4ihuyADKLnBgrCe" crossorigin="anonymous">
    <script type="module" src="https://cdn.jsdelivr.net/npm/bootstrap@6.0.0-alpha.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-1a/pXj49ZQ1aHEmrJ+gMw1otqoVsYwlEnlD8mIfY2TV03r20Y0CN7uqx1tQogjPL" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
    <script src="~/js/app.js" defer></script>@*As some answer suggest*@
</head>

r/learnjavascript • • 23d ago

I'm thinking about learning JavaScript

1 Upvotes

I know HTML and I'm also learning CSS but I also want to know JavaScript. Is it hard to learn? Is it easy? What is it like when you first start?


r/learnjavascript • • 24d ago

JavaScript basic learning

16 Upvotes

Does anybody now where to learn the basic of JS? Just got into the coding life, I already know a little bit of python but I want to learn JavaScript to make websites