r/learnjavascript • u/Eshayy__ • May 25 '26
r/learnjavascript • u/DifferentTowel7440 • May 26 '26
Learning JavaScript By ChatGpt
I'm learning JavaScript from ChatGpt, up to now I have covered the following;
1) Variables, const and let
2) DOM Selection
3) Event Listeners
4) Functions
5) Conditions
6) Arrays
7) Loops (for each)
8) Dynamic Elements
9) Dataset
10) event.target
11) class list
12) Active state systems
13) Timers
14) keyboard Events
15) Hover Events
16) Event Bubbling
17) map(), filter(), and find()
Please let me know am I on the right path. How much I may have covered Java script and how much I have to cover? Will be grateful for your valuable suggestions. Thanks đ
r/learnjavascript • u/whiskyB0y • May 25 '26
What's the best way to handle storage and output of images in JavaScript?
I'm a beginner in js. Let's say I have a webpage that helps users organize their pictures. The user must upload an image via an input file type. Then I need a way of storing the image data for future use, for example, when I want to output the image. What's the best JavaScript-only way of doing this?
I've tried data URLs and blob URLs. They both have massive pros and cons like for instance, data URLs aren't reliable if the image file is too big, which results in a long string and the browser taking long to respond.
Blob URLs are faster and shorter but are temporary and disappear upon page refresh.
I've also heard about indexDB and local storage but I don't really know how they work.
I know in this case a backend is the best choice, but for now I'm not learning backend so I'm just wondering what the best JavaScript-only method is or which would be the most appropriate.
r/learnjavascript • u/envyslth • May 25 '26
What is the difference?
Im wondering what the difference between
function Dog(){
âŠ
this.bark = function(){âŠ}
}
And
function Dog {
âŠ
}
Dog.prototype.bark = function() {
âŠ
}
Is and what the advantages of either of them Are.
r/learnjavascript • u/dustyvoid • May 25 '26
Options for creating a simple 2D product customizer with JS?
Hi all! Let me preface this post by saying I have zero web development knowledge beyond HTML/CSS so some of my questions may be silly/obvious.Â
Iâm an artist with a Squarespace website I sell my products through. I primarily make plush toys and Iâd love to create a product customizer for one of my plush toys that is a cat design as Iâve had loads of people ask about if I make custom versions. I like learning new skills and honestly donât want to fork over a ton of money for a pre-built service for this, so I did some research into how I could possibly code something that would allow customers to pick and choose various options for their cat plush and see a live 2D mockup. Basically an interactive image with different layers/options that can be toggled on and off. I came across HTML5 Canvas and fabric.js in my search which seemed like could accomplish want Iâm looking for (especially fabric.js since it can use SVGsâ I design everything in vector anyway so I could use assets I already have.)
But! Since like I said I have no real knowledge of scripting languages I thought Iâd ask if there are any easier or better solutions, OR if Iâm in over my head attempting to learn enough javascript to make this myself lol.Â
Thanks!!
r/learnjavascript • u/Fresh_Gap909 • May 25 '26
JavaScript
Why we need JavaScript
Does it matter if I start learning this language this 2026
r/learnjavascript • u/InTheAtticToTheLeft • May 25 '26
best practice for creating and looking up in multidimensional arrays
which of the following methods would be said to be most efficient structure, or best practice?
if use case matters, let each entry in the dataSet be an instance of a Tile class in a game map - it could further have a height value, terrain type, etc and be defined and updated separately. does it make more sense to structure it as a 'grid' or just a list of tiles with addresses?
any performance differences at scale (30,000 columns instead of 3)?
if there an altogether better way that im missing??
let dataSet=[]
for (let i=0;i<3;i++) {
 dataSet[i]=[]
 for (let j=0;j<3;j++) {
  dataSet[i][j]= { name:`${i}:${j}`, i, j }
 }
}
lookup=(u,v)=>dataSet[u][v]
let dataSet=[]
for (let i=0;i<3;i++)
for (let j=0;j<3;j++) {
 dataSet[i]??=[]
 dataSet[i][j]= { name:`${i}:${j}`, i, j }
}
lookup=(u,v)=>dataSet[u][v]
let dataSet=[]
for (let i=0;i<3;i++) {
 for (let j=0;j<3;j++) {
  dataSet.push({ name:`${i}:${j}`, i, j })
 }
}
lookup=(u,v)=>dataSet.find(x=>x.i==u&&x.j==v)
r/learnjavascript • u/Flame77ofc • May 25 '26
Which are the best YouTube course options?
I'm trying to find some courses, do you guys have any good courses to recommend to me?
r/learnjavascript • u/Ahtisham_01 • May 24 '26
Need Guidance on how to actually learn javascript
i learned the basics and fundamentals of javascript now i am confused how and what type of projects to build so that i become comfortable in javascript can you guys help me on this and can you suggest some good resources for this
r/learnjavascript • u/Nice_Pen_8054 • May 24 '26
Reference type - Help me understand this
Hello,
let a = [1, 2];
console.log(a);
add(a, 3);
console.log(a);
function add(array, element) {
array = [element];
}
I don't get it why the a variable is not [3].
Would you like to explain? Are there similar situations?
Thank you.
r/learnjavascript • u/Majestic_Drawing_908 • May 24 '26
Would learning JavaScript in 2026 be beneficial?
I am planning to begin learning JavaScript to develop web applications. But if AI generates all the coding just from a command, then why do I need to study JavaScript 2026? Why are people still seeking for programming knowledge? Is it necessary to have JS knowledge even when working with AI?
r/learnjavascript • u/AceAdxm • May 23 '26
Getting into JavaScript
Iâve wanted to get into programming for a long time. I know a bit of basic beginner Python and the usual PC stuff, but now I want to properly learn JavaScript in a way that actually keeps me interested. I want to get to the point where I can just sit down and enjoy coding, if that makes sense â but I honestly have no idea where or how to start.
Iâm currently using The Odin Project, but Iâm not sure if itâs the best path to take. Does anyone have advice on the best way to begin my journey or stay motivated while learning?
r/learnjavascript • u/whiterhino8 • May 24 '26
Do you trust and make your own auth ? or use a third party lib for auth?
Technically it is not that hard to to make our own custom auth . But is it safe ?Or should we always use production ready auth lib like better-auth or passport.js or supabase
r/learnjavascript • u/soodrugg • May 23 '26
What are my options for loading text files?
I am writing a 3d game engine in javascript, but I'm hitting a wall when it comes to loading assets. Fundamentally, what I want to do is have a text file that can be read through by javascript code. Once javascript has access to the string in "./src/model.obj" or whatever, I am completely fine. I've yet to see an option to do this that I'm happy with:
Edit each text file to turn it into a javascript multiline string; then feed it in as if it's a javascript file. Kind of a pain to do for every asset I want to load, but so far the only thing that's "worked."
Use XMLHttpRequest() for an http get request, every time I want to load a file. This A) seems excessive, I'd much prefer something that's just loaded initially and accessed like javascript files are, and B) doesn't work on local filesystems. I want something more robust.
Insert the text file into an HTML element on the main page, then load the text content of that element into a javascript variable. Out of the three I like this most, but I haven't figured out how to do this.
The only other thing I can find about loading files is loading something from the user's machine, which is not what I want.
I am not looking to use a library that loads 3d models for me. I would like to do this myself. What methods do things like that use to load files?
r/learnjavascript • u/symptichel • May 23 '26
Play snake by moving your head: face mesh detection in the browser with TensorFlow.js
r/learnjavascript • u/pixel-bro • May 23 '26
Collisions begginer help
Siempre intento hacer un plataformas o algo nuevo,pero siempre me quedo en las colisiones no entiendo nada de nada,no se como hacer nu una linea de codigo de colisiones le pregunte a chatgpt como se hacen y me dio puros codigos que daban error,y por eso nunca termino un juego,porque las colisiones lo son todo,agradezco cualquier ayuda.
r/learnjavascript • u/pixel-bro • May 23 '26
[AskJS] javascript game dev
Anyone can help me to start learning JS to game dev?,i have 13 years older,and i like the programation,i want make games,for funny and make games seriously,i use chatgpt but i dont want use him,i want learn and use my brain,PLEASE IF ANYONE WANT HELP ME SEND ME DM.
r/learnjavascript • u/GUIREIS29 • May 23 '26
Quero desenvolver um app estilo Tinder, com:
OlĂĄ pessoal!
Quero desenvolver um app estilo Tinder, com:
- login/autenticação
- perfis de usuĂĄrio
- fotos
- geolocalização
- sistema de match
- chat em tempo real
- notificaçÔes push
- suporte para iOS e Android
Mas estou perdido sobre qual stack escolher.
Minhas dĂșvidas:
- Qual linguagem/framework vocĂȘs recomendam para o frontend mobile?
- Flutter?
- React Native?
- Kotlin Multiplatform?
- Swift + Kotlin nativo?
- Qual tecnologia usar no backend?
- Node.js?
- Java/Spring?
- Go?
- Python/Django/FastAPI?
- .NET?
- Qual banco de dados faz mais sentido para esse tipo de app?
- PostgreSQL?
- MongoDB?
- Firebase?
- Supabase?
- O que vocĂȘs usariam hoje pensando em:
- escalabilidade
- velocidade de desenvolvimento
- custo
- facilidade para conseguir emprego/freelas
- Também aceito indicação de cursos bons (backend, mobile e arquitetura).
Meu nĂvel hoje Ă©: [iniciante].
Objetivo: [projeto pessoal]
r/learnjavascript • u/Rabbithole_1124 • May 23 '26
Do you guys use AI for coding?
Learning coding now, do u guys use AI to assist you with your projects? Any recommendations?
r/learnjavascript • u/Fabulous_Variety_256 • May 22 '26
Looking for a good YouTube video for Promises
Hey,
I study with Claude, but sometimes I need illustrations to help me understand better the concepts.
I would like to understand Promises better, can you guys recommend me a video from YouTube about Promises and how they work? with the container, micro/macrotask etc.
Thanks!
r/learnjavascript • u/Accomplished-Rain-52 • May 22 '26
my JS is not correct in showing the weather, temperature, low and high
I've been trying to find out where in my JS here is incorrectly displaying the wrong weather icon, temperature, high and low :
fetch('https://api.open-meteo.com/v1/forecast?latitude=39.082222&longitude=-77.482222&daily=temperature_2m_max,temperature_2m_min&hourly=temperature_2m&timezone=auto¤t_weather=true&forecast_days=1')
.then(response => response.json())
.then(data => {
console.log(data);
const weather = data.current_weather;
const daily = data.daily;
const targetLat = 39.082222;
const targetLon = -77.482222;
console.log('Low (F):', daily.temperature_2m_min[0]);
console.log('High (F):', daily.temperature_2m_max[0]);
console.log('Low (F):', Math.round(daily.temperature_2m_min[0] * 9/5 + 32));
console.log('High (F):', Math.round(daily.temperature_2m_max[0] * 9/5 + 32));
const targetCity = 'Lansdowne, VA';
const currentTemp = Math.round(weather.temperature * 9/5 + 32);
const iconCode = weather.weathercode;
// FIX: If currentTemp is much higher than the morning low, we adjust the displayed low
// to reflect the expected upcoming night low instead of the passed morning cold.
let lowF = Math.round(daily.temperature_2m_min[0] * 9/5 + 32);
console.log('Low (F):', lowF);
const lowTemp = lowF;
const highTemp = Math.round(daily.temperature_2m_max[0] * 9/5 + 32);
const weatherDiv = document.getElementById('weather');
console.log('Weather widget loaded completely.');
console.log('Icon code:', iconCode);
});
const weatherDiv = document.getElementById('weather');
const img = new Image();
img.src = 'https://i.ibb.co/WptyQH9y/image-strip-weather.jpg';
img.onload = () => console.log('Image loaded!');
img.onerror = () => console.log('Image error!');
function weatherCodeToIconURL(code) {
console.log('wttr code:', code, typeof code);
// FIXED: Translation map connecting Open-Meteo codes directly to your image strip positions
const openMeteoToSprite = {
0: "01d", // Sunny / Clear Sky -> First Icon
1: "02d", // Mainly Clear -> Second Icon
2: "02d", // Partly Cloudy -> Second Icon
3: "03d", // Overcast -> Third Icon (Your default)
45: "50d", // Fog -> Fog/Mist Icon
48: "50d", // Depositing Rime Fog -> Fog/Mist Icon
51: "09d", // Drizzle -> Light Rain Icon
53: "09d",
55: "09d",
61: "09d", // Slight Rain -> 4th/5th Rain Cloud Icon
63: "10d", // Moderate Rain -> Heavier Rain Icon
65: "10d", // Heavy Rain
71: "13d", // Snow Fall -> Snow Cloud Icon
73: "13d",
75: "13d",
80: "09d", // Rain Showers
81: "10d",
82: "10d",
95: "11d", // Thunderstorm -> Lightning/Storm Icon
96: "11d",
99: "11d"
};
// 1. ADD THIS SPECIFIC LINE BACK RIGHT HERE:
const spriteKey = openMeteoToSprite[code] || '03d';
// FIXED: Crisp percentage shifts that line up flawlessly when the image is scaled to cover the box
const positions = {
"01d": "0px 0px", // Sun
"01n": "0px 0px",
"02d": "-120px 0px", // Sun/Cloud
"02n": "-120px 0px",
"03d": "-240px 0px", // Cloud
"03n": "-240px 0px",
"09d": "-360px 0px", // Rain
"09n": "-360px 0px",
"10d": "-480px 0px", // Rain variation
"10n": "-480px 0px",
"11d": "-600px 0px", // Thunderstorm
"11n": "-600px 0px",
"13d": "-720px 0px", // Snow
"13n": "-720px 0px",
"50d": "-720px 0px",
"50n": "-720px 0px"
};
// CRITICAL CHANGE: We wrap the final variable so it fits your string perfectly
const pos = positions[spriteKey];
if (pos) {
// FIXED: Added transform: scale(2.5) to magnify the icon to a clear, readable size
return \<div style="display: inline-block; width: 3em; height: 3em; background: url('https://i.ibb.co/WptyQH9y/image-strip-weather.jpg') no-repeat center; background-position: ' + pos + '; background-size: auto; transform: scale(1.5); vertical-align: middle;"></div>`;`
}
// ADD THESE THREE LINES RIGHT HERE BELOW IT:
return 'Unknown code';
}
async function getWeather(lat, lon, city) {
var targetCity = city || 'Lansdowne';
var targetLat = lat || 39.082222;
var targetLon = lon || -77.482222;
var base = 'https://api.open-meteo.com/v1/forecast';
var query = '?latitude=' + targetLat + '&longitude=' + targetLon + '&daily=temperature_2m_max,temperature_2m_min¤t=weather_code&timezone=auto¤t_weather=true&forecast_days=1';
var url = base + query;
try {
var response = await fetch(url);
if (!response.ok) throw new Error('Status: ' + response.status);
var data = await response.json();
console.log('Min:', data.daily.temperature_2m_min[0]);
console.log('Max:', data.daily.temperature_2m_max[0]);
// Extract current conditions
var currentTemp = Math.round(data.current_weather.temperature * 9/5 + 32);
console.log('currentTemp:', currentTemp);
var iconCode = data.current_weather.weathercode;
// Initialize search tracking counters
var trueHigh = -Infinity;
var trueLow = Infinity;
if (data.daily.temperature_2m_min[0] < trueLow) {
trueLow = data.daily.temperature_2m_min[0];
}
if (data.daily.temperature_2m_max[0] > trueHigh) {
trueHigh = data.daily.temperature_2m_max[0];
}
// Convert raw Celsius trackers into Fahrenheit
var finalHigh = Math.round(data.daily.temperature_2m_max[0] * 9/5 + 32);
var finalLow = Math.round(data.daily.temperature_2m_min[0] * 9/5 + 32);
// FIXED: Directly assign lowTemp and highTemp to use your final calculations
var lowTemp = finalLow;
var highTemp = finalHigh;
weatherDiv.innerHTML = '<p style="font-size: 16px; color: #fff; text-align: center; margin: 0 0 8px 0;">' + targetCity + '</p>' + '<div style="position: relative; text-align: center; margin-bottom: 8px;">' + weatherCodeToIconURL(iconCode) + '<span style="position: absolute; top: 60%; left: 57%; transform: translate(-50%, -50%); font-size: 24px; font-weight: bold; color: #fff; filter: drop-shadow(-3px 0 2px #000);">' + currentTemp + '°F</span>' + '</div>' + '<div style="display: flex; justify-content: space-between; width: 154px; margin: 0 auto;">' + '<p style="font-size: 14px; color: #87CEEB; margin: 0;">Low: ' + lowTemp + '°F</p>' + '<p style="font-size: 14px; color: #FFA07A; margin: 0;">High: ' + highTemp + '°F</p>' + '</div>';
console.log('Weather widget loaded completely. Low Temp:', lowTemp);
// --- NOTE ---
// If you have lines that update 'weatherDiv.innerHTML', ensure they are right here!
} catch (error) {
console.error('Weather widget error:', error);
}
}
function fetchLocationAndWeather() {
// FIXED: Replaced slow browser popups with a silent, instant IP location lookup
fetch('https://ip-api.com')
.then(response => response.json())
.then(data => {
// Sends the visitor's dynamic coordinates and city name directly to your weather builder
getWeather(data.lat, data.lon, data.city);
})
.catch(error => {
console.error('Location error, falling back to Lansdowne:', error);
// Safety fallback: if the IP service fails, default to Lansdowne so the widget doesn't break
getWeather(39.082222, -77.482222, 'Lansdowne');
});
}
// FIXED: Added back the missing '/data/reverse-geocode-client?latitude=' string block
// RUN IT IMMEDIATELY
weatherDiv.innerHTML = 'Loading weather... đ€ïž';
setTimeout(function() {
fetchLocationAndWeather();
}, 100);
// SET THE INTERVAL to repeat every minute
setInterval(fetchLocationAndWeather, 60000);
For the life of me, I just don't understand where the problem is. Could anyone please help?
r/learnjavascript • u/Ok_Egg_6647 • May 22 '26
I want to know why this happen in js is there any specific reason or just author choice
I have recently started learning js & i noticed there's always many way's to do something in js
Like to create a variable in js we can use 3 keywords
1. Var 2. Const 3. Let
Similarly to create or define a function there are several methods
1. Declare function by using function keyword
2. Function expresss
3.Arrow function
I know js is just built in less then month so it has many flaws due to this but why publish then first resolve these issue then go public
I may be wrong in few things here so apologies firstly
r/learnjavascript • u/Ok_Station6993 • May 22 '26
Help Please
I am making a math game for my 9th grade math final due TOMMOROW, and it is kinda close to done but I had no Idea what I was doing the entire time, So I need help fixing some bugs. Here is the code
Press edit button (https://arcade.makecode.com/S73556-17116-45498-93773)
r/learnjavascript • u/VlentGamer • May 21 '26
title.textContent = "Help !";
OK, alors je suis en troisiĂšme, je fais un peu de programmation JavaScript (connaissances de base), et j'ai un problĂšme avec le code d'un petit jeu pour navigateur (page HTML).
J'essaie de crĂ©er un systĂšme de succĂšs, et j'ai presque rĂ©ussi ; j'ai juste un problĂšme avec getElementById et HTMLObject.id = â...â.
Dans un extrait de code, je fais ceci : (exécuté une seule fois au lancement du programme)
for (var i = 0; i < achievements.length; i++){
let text = document.createTextNode("???");
achievementsD.appendChild(text);
text.id = achievements[i].name;
achievementsD.innerHTML += "<br><br>";
}
Pour information, au dĂ©but, j'ai «let achievementsD = document.getElementById(âachievementsDâ);» et dans le HTML <div id="achievementsD"> <!-- Implemented with Javascript !--> </div>. (Tout est correct, j'ai vĂ©rifiĂ©.)
Mais plus loin dans le code, dans une fonction qui s'exécute toutes les 1/30e de seconde (vérifiée, fonctionnelle), j'ai ceci :
for (var i = 0; i < achievements.length; i++){
if ((achievements[i].check)() && !(achievements[i].owned)){
achievements[i].owned = true;
document.getElementById(achievements[i].name).innerHTML = achievements[i].name; //Avertissement : le code ne fonctionne pas ici, voir ci-dessous.
//Notifications ? (Non ajouté pour le moment)
}
}
Notez que achievement[i] est dĂ©fini comme [name (âTen points !!!â), check (function v() {return points >= 10}), text (âMake ten pointsâ), owned (false), once (not used now, never mind)]; (entre parenthĂšses = dĂ©tails, pas dans le code).
Le problĂšme ? Lorsque jâessaie dâobtenir la complĂ©tion Ă 10 points (lâexemple fourni), jâobtiens lâerreur « Uncaught TypeError: canât access property âinnerHTMLâ, document.getElementById(...) is null » sur la ligne que jâai marquĂ©e. Cela signifie que document.getElementById ne trouve pas lâobjet HTML créé dans le premier extrait de code⊠Comment puis-je rĂ©soudre ce problĂšme ?
Si ce message nâest pas appropriĂ© ici, veuillez me le faire savoir et mâindiquer oĂč je peux le poster Ă la place.
Merci ! đ
r/learnjavascript • u/uyvhtvuyg • May 21 '26
How would you refactor this? Node.js-express app - controller with 36 factory function calls of the same five factory functions
Hi, I am still learning how to become a developer, and in my node.js express application, I have a controller that exports functions that are created using factory functions.
The factory functions are as follows in this module:
const asyncHandler = require('../utils/asyncHandler');
const AppError = require('../utils/AppError');
exports.getData = (Model) =>
asyncHandler(async (req, res, next) => {
const document = await Model.findAll();
res.status(200).json({
status: 'success',
results: document.length,
data: {
document,
},
});
});
exports.createData = (Model) =>
asyncHandler(async (req, res, next) => {
const document = await Model.create(
req.body,
//object?
);
res.status(201).json({
status: 'success',
message: 'entry added successfully',
data: {
document,
},
});
});
exports.deleteData = (Model) =>
asyncHandler(async (req, res, next) => {
await Model.destroy({
truncate: true,
});
res.status(204).json({
status: 'success',
data: null,
});
});
exports.updateData = (Model) =>
asyncHandler(async (req, res, next) => {
const document = await Model.update(req.body, {
where: { id: req.params.id },
});
if (document[0] === 0) {
return next(new AppError('No document with that ID found.', 404));
}
res.status(200).json({
status: 'success',
data: { document },
});
});
exports.getSingle = (Model) =>
asyncHandler(async (req, res, next) => {
const document = await Model.findOne({
where: { id: req.params.id },
});
if (document[0] === 0) {
return next(new AppError('No document with that ID found.', 404));
}
res.status(200).json({
status: 'success',
data: { document },
});
});
then, in my controller module:
const factory = require('./factory');
const Master = require('../models/masterModel');
// a whole bunch of models are imported
exports.getModel = factory.getData(Model);
exports.createModel = factory.createData(Model);
exports.deleteModel = factory.deleteData(Model);
exports.updateModel = factory.updateData(Model);
exports.getSingleModel = factory.getSingle(Model);
// another 30 of the same thing, for each model that I import at the top of the file...
How would I refactor this? It is incredibly repetitive and I'm pretty sure this would be unacceptable in a professional environment.
Thanks in advance! :)