r/learnjavascript • u/Active-Aspect2654 • 28d ago
I just started JavaScript
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 • u/Active-Aspect2654 • 28d ago
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 • u/Nearby-Percentage-33 • 27d ago
Im sharing this website with Javascript cheatsheet. hope this helps!
r/learnjavascript • u/CelebrityChess • 28d ago
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 • u/Monstar1567 • 28d ago
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 • u/B0NKB0Y • Oct 29 '26
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 • u/SergioCoitino • Oct 29 '26
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:
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 • u/Aggressive_Top_7377 • Oct 29 '26
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 14Nothing 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 • u/kaatarina_zed_talon • Oct 28 '26
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 • u/Kajushhhhh • Oct 27 '26
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 • u/King134643 • Oct 26 '26
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 • u/No_Country8607 • Oct 26 '26
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:
What's one thing you'd add to the platform you use most?
Thanks, I'll read every reply 🙏
r/learnjavascript • u/FigAmbitious9101 • Oct 25 '26
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:
createStore functionuseSyncExternalStoreuseSelector and custom store hookscreateSlicecombineReducersshallowEqualYouTube 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 • u/RobGoLaing • Oct 24 '26
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 • u/username95050 • Oct 23 '26
What is it? Don't understand what is inside or outside
r/learnjavascript • u/Comfortable_Tea_2825 • Oct 23 '26
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 • u/kaatarina_zed_talon • Oct 23 '26
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 • u/Active-Aspect2654 • Oct 23 '26
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 • u/UnitedAirport5964 • Oct 23 '26
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
r/learnjavascript • u/Several_Box4108 • Oct 23 '26
let object = {
YoutubeChannel: {
name: 'Comicverse',
location: 'India,Madhya Pradesh',
Domains: {
Videos: ['Doctor doom final plan', 'Marvel is faling'],
Shorts: ['This is crazy', "Who will appear in Marvel's doomsday"],
}
}
};
(function() {
console.log("Hey! this is an immediately invoked function!!");
}
)();P.S. If you have any suggestions regarding how I can improve the way I ask questions, how to format them, etc., please let me know... :-)
r/learnjavascript • u/RefuseCommercial8024 • Oct 22 '26
--fixed, just hadta remone the "let" at the end : -) --
hii i'm working on a page that lets u cycle through texts by clicking on an arrow but i've got some trouble actually making my js... cycle through.
let fruit = 0;
function next() {
fruit ++;
console.log(fruit)
if (fruit == 0) {
document.getElementById("txt").innerHTML="bananas are fruits that look weird nd stuff";}
else if (fruit == 1) {
document.getElementById("txt").innerHTML="coconuts are cool too i guessssss";
}
else if (fruit == 2) {
document.getElementById("txt").innerHTML="and apples exist also!!!!";
}
else if (fruit > 2) {
let fruit = 0;
}
}i need to set my fruit var back to 0 if it's over 2 but i can't find a way to make it work...i'm pretty new to js too so my code probably isnt optimal lol
r/learnjavascript • u/antonybuilds • Oct 22 '26
I've been finding out the hard way what it takes to build something more involved with Canvas, but I've really enjoyed working on it.
I've had to figure out things like handling interactions, routing connections between nodes and getting signals to propagate through a circuit. I've written up what I've done so far here:
https://antonyjones.org/blog/building-a-logic-gate-simulator-with-type-script-and-canvas/
I'd be interested to hear from anyone who's tackled something similar. Is there anything you'd have done differently, or any pitfalls I should look out for later?
r/learnjavascript • u/Glad_Ground5391 • Oct 22 '26
Hey everyone! I’m currently interviewing for Full Stack Developer roles, but I struggle with JavaScript input/output questions. Just reading concepts isn’t helping much.
Does anyone know of any free websites or quizzes where I can practice these questions with explanations?
Thanks! 🙌
r/learnjavascript • u/Hortaly • Oct 22 '26
I've done web dev for about a year but my JavaScript is still weak. What projects or resources helped you get from basic to confident?"
r/learnjavascript • u/dimeraymundo • Oct 22 '26
esbuild is faster but Webpack offers a larger interface and more fine-grained control. That's my take. What do you recommed. I want real people because AI responses are not enough for me.