Learn Javascript

r/learnjavascript250.9K subscribers13 active
my team still uses ‘var’ and I get triggered

and its more for module imports, which won’t hurt how the code functions but very occasionally I see it within functions too

Am I right to feel this way?

I’m thinking “come on. its 2024” and the problems with var have been known for so long now

I made one of my teammates feel guilty for using var, which wasn’t the intention but I feel like it became some bad habit

I am still new to my company so I do feel weird trying to push for changing every instance of it

I have been slowly changing them to const or let in relevant files I work on for my PRs

188
181
1d
Did you use javascript for learning Data Structures and Algorithms?

Currently, I am learning Data Structures with javascript. Are there any good resource for learning DSA with js/ts. I prefer text over video.

How were dependencies of dependencies downloaded before modules became a part of JS?

Suppose I wanted to use a 3rd party library A.js in my index.html. I'd include that in a <script> tag in my index.html. But what if A.js depended on B.js. Would I have to manually include B.js in my index.html and make sure it is listed before A.js since A.js uses functions from B.js?

I've been studying with FreeCodeCamp and I need advice.

The HTML courses were easy. But the JS courses - I dont understand most of it.

I go 10 steps with no issue, easy instructions. Then I get a question and I cant get anything to write. I can use chatgpt but thats cheating, i can check the forum but most of the people that write are almost there and just miss a dumb dot or something. So what do i do? I skip to the next lesson and I copy the answer and bring it to the previous lesson to finish it.

Should I just quit and find a different way to learn? I'm already creating my own little projects.

How to find voluntary work to increase experience

Hello,
I want to know where I can find voluntary work so I can practice and gain experience while letting me put something more on my resume and make friends who are more experienced and willing to teach me. I hear Linkin can help with that but I can't use that site for the life of me, just opening it up makes me have a major anxiety attack, I know it might sound silly especially when you're not in a good situation and need a job but I have tried and just looking at it makes me physically sick. I just want to know where I can work for free to become a better programmer

Help needed

I want to play this link https://inst3.ignores.top/js/sky-sports-f1-sky-f1/1/playlist.m3u8 on my website but all the player codes fail to play it ive tried Jw Player and other may be im doing something wrong please any one who can help

For loop returns 0

Essentially, I've been wanting to build a distributed social network for a long time. I tried over IPFS but the support just wasn't there. All the tech they developed either became deprecated, wasn't well documented, or they'd decide to take an entirely different direction and a lot of the API features I needed would just disappear.

I'm building everything from the ground up over LAN. Starting with the database module. Strings are dumped into it, and out pops a 32byte hash for the user to share, pointing to that particular string.

Here's the database so far:

``` const { createHash } = require("node:crypto") const {writeFile, mkdir, readFile} = require("node:fs")

const print = console.log

class uid { constructor(s){ this.uid = ""

    if (arguments.length > 0){
        this.data = s
        this.uid = createHash("sha512").update(s).digest("hex").substring(0, 32).toUpperCase()
    }
}

pathify(){
    var p = []
    for(let i = 0; i < this.uid.length/2; i++){
        p.push(this.uid.substring(i*2, i*2+2))
    }
    return p.join("/")
}

}

class database { constructor(path){ this.path = path

    this.cache = [{foo:"bar"}]
}

push(s){
    var uuid = new uid(s)

    for (let item in this.cache){
        print(item)
        if (uuid.uid in item){
            return item
        }
    }

    var filePath = this.path + uuid.pathify()
    mkdir(filePath.slice(0, -2), {recursive: true}, (err) => {
        if(err){console.error(err)}
        else{writeFile(filePath, uuid.data, (err) => {console.error(err)})}
    })

    this.cache.push({uid: uuid.uid, data: uuid.data})

    while(this.cache.length > 100000){
        this.cache.shift()
    }
    return uuid.uid
}

pull(u){
    for (let item in this.cache){
        if (u in item){
            return item
        }
    }

    var uuid = new uid()
    uuid.uid = u
    var filePath = this.path + uuid.pathify()

    var contents = readFile(filePath)
}

}

const db = new database("/home/jesse/Desktop/db/")

var u = db.push("Hello World!") console.log(db.pull(u)) ```

My problem is in database.push(). The item variable returns 0, instead of the expected, {foo: "bar"}.

What am I doing wrong?

0
8
9h
"Head First into JavaScript Programming" Book Help - Battleship

So I'm making the battleship game from the "Head First into JavaScript Programming" learning book.

I've got everything done and complete. The game works great as designed, EXCEPT the <div id = messgageArea></div> part of the HTML

I've compared everything to the correct files in gitHub and its all correct and matches 100%. so why can't I get the in game messages of "Hit", "miss", etc to show up?

Want to process local file with JS, then display result in HTML - problem with node's "require"

So I have a text file on my local disk that I want to process, and then display the resulting modified text on the web. I was able to put together a JS program that reads and processes the file as I want (under node). The problem is that when I try to set it up so that I can display this text on the web using a textContainer, I get an error - it clearly doesn't like the `const fs = require('fs');` needed to read the file.

CountUp_sync.js:11 Uncaught ReferenceError: require is not defined
at openFile (CountUp_sync.js:11:14)
at CountUp_sync.js:144:14

Is there a way around this? Or is there a better way to accomplish this? I'm new to JS and only have very rudimentary knowledge of HTML and CSS (working on improving this by doing some projects of my own)

0
9
12h
Seeking suggestions: Books for JavaScript Proficiency

I'm wanna dive deep into JavaScript and enhance my skills. Could you please suggest some books? I would really appreciate any guidance you can offer.

Where can I practice, make some exercices ?

Hi everyone, I started the odin projetc to learn Javascript and I gave myself 2 hours a day minimum to exercice/practice.

Could you recommand some website/app with javascript exercice for each chapter so I can progress along the things I’m learning.

Thank you !

How to extract parent directory name from .log file in Chrome's File System folder

[SOLVED]

On Chrome browser when Origin private file system, not to be confused with File System Access API is used to create directories and files a folder is created for each entry in the Chrome configuration folder in Default/File System.

The folders are named something like 021 for each entry, so 063, 067 and so forth can also exist within the parent File System directory.

Inside of a given subdirectory there is a folder named t, which includes folders named 00 and Paths.

00 contains the files that were written to the origin private file system using FileSystemWritableFileStream.

Paths contains a file named 000003.log, which is a text/x-log file including chararacters outside of 0-255 code point range.

After removing all except alphanumeric, underscore, dash, forward-slash, dot characters the content of 000003.log looks something like this https://gist.github.com/guest271314/c930dd00388aab20ab66528fad86d8c3:

rM0Ux/LAST_FILE_ID0LAST_INTEGER-1FCHILD_OF:0:persistent-serviceworker1140persistent-serviceworkerUx/LAST_FILE_ID100Ux/TLAST_INTEGER0ZlCHILD_OF:1:README.md224000/00000000README.mdLAST_FILE_ID2KMD140persistent-serviceworkerUx/LAST_INTEGER1fVwCHILD_OF:1:README.md.crswap338400/00000001README.md.crswapLAST_FILE_ID3D140persistent-serviceworkerUx/dCHILD_OF:1:README.md.crswap324000/00000001README.mdInD140persistent-serviceworkerUx/D140persistent-serviceworkerUx/UeKCHILD_OF:1:chromium_extension_web_accessible_resources_iframe_message_event44X@chromium_extension_web_accessible_resources_iframe_message_eventUx....

I am able to get the file names in an Array using the code below.

``` async function parseChromeDefaultFileSystem(path) { var set = new Set([ 32, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 95, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, ]);

return fetch(
  path,
).then((r) => r.text()).then((text) => {
  let str = "";
  for (const char of text) {
    const code = char.codePointAt();
    if (set.has(code)) {
      str += char;
    }
  }
  console.log(str);

  const matches = [
    ...new Set(
      str.replace(/./g, (s) => set.has(s.codePointAt()) ? s : " ").match(
        /00000\d+[A-Za-z-_.0-9\s]+\.crswap/g,
      ),
    ),
  ].map((s) => s.replace(/00000[\d\s]+|\.crswap/g, ""));

  return matches;

}).catch(console.error);

}

var paths = await parseChromeDefaultFileSystem("file:///home/user/.config/chromium/Default/File\ System/021/t/Paths/000003.log"); console.log(paths); ```

What I am trying to do now is get the parent directory of the discrete files from 000003.log. So I need to get those @ symbols followed by the directory or subdirectory name, or parse the CHILD_OF and so forth parts of the string.

How would you go about extracting the parent directories and prepending that to the file names so we can know which flat files in 00 correspond to which directories and subdirectories in the 000003.log file?

Solution:

``` async function parseChromeDefaultFileSystem(path) { try { const set = new Set([ 32, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 95, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, ]); const request = await fetch(path); const text = (await request.text()).replace(/./g, (s) => set.has(s.codePointAt()) ? s : ""); const files = [ ...new Set( text.match( /00000\d+[A-Za-z-.0-9\s]+.crswap/g, ), ), ].map((s) => { const dir = [...new Set(text.slice(0, text.indexOf(s)).match(/(?<=[@\s]|CHILD_OF:0:)([\w-])+(?=Ux)/g).map((d) => d.split(/\d+|D140/) ))].flat().pop(); const [key] = s.match(/00000[\d\s]+|.crswap/g); return ({ [key]: s.replace(/00000[\d\s]+|.crswap/g, ""), dir }) }); return { name: files[0].dir, files } } catch (e) { console.error(e); } }

let paths = await parseChromeDefaultFileSystem("file:///home/user/.config/chromium/Default/File\ System/021/t/Paths/000003.log");

console.log(JSON.stringify(paths,null,2));

{ "name": "persistent-serviceworker", "files": [ { "00000001": "README.md", "dir": "persistent-serviceworker" }, { "00000003": "background.js", "dir": "chromium_extension_web_accessible_resources_iframe_message_event" }, { "00000005": "index.html", "dir": "chromium_extension_web_accessible_resources_iframe_message_event" }, { "00000007": "index.js", "dir": "chromium_extension_web_accessible_resources_iframe_message_event" }, { "00000009": "manifest.json", "dir": "chromium_extension_web_accessible_resources_iframe_message_event" }, { "00000011": "index.html", "dir": "docs" }, { "00000013": "script.js", "dir": "docs" }, { "00000015": "sw.js", "dir": "docs" }, { "00000017": "index.html", "dir": "docs" }, { "00000019": "script.js", "dir": "docs" }, { "00000021": "sw.js", "dir": "docs" }, { "00000023": "index.html", "dir": "message-event" }, { "00000025": "script.js", "dir": "message-event" }, { "00000027": "sw.js", "dir": "message-event" }, { "00000029": "index.html", "dir": "readablestream-fetch-respondwith" }, { "00000031": "script.js", "dir": "readablestream-fetch-respondwith" }, { "00000033": "sw.js", "dir": "readablestream-fetch-respondwith" } ] } ```

Wes Bos's Javascript course

Hey everyone, I came across Wes Bos's Beginner Javascript course, just wanted to ask if anyone in this community has taken it! I kind of liked the promo video he has on the course page..

How is the phase determined when filling a path with an image pattern?

I'm writing a JS program (a game called Paul's Weird Adventure) where I need to copy the part of a canvas within a certain shape. I'm doing it using a path. I found the functions for that, but I couldn't find how to specify where a point of that image is

The context is a CanvasRenderingContext2D. The code currently is:

screenSettings.ctx.fillStyle = createPattern(this.getRenderer(screenSettings, orn, doMarkEdit).getRendered());
const hr = pwaPartialFillHelper(screenSettings, orn);
const ts = screenSettings.tileSize;
const xc = xr * ts;
const yc = yr * ts;
const xd = xc + ts;
const yd = yc + ts;
const xl = xd / l;
const xr = xd / r;
const ll = yd * l;
const rr = yd * r;
const lc = yc * l;
const rc = yc * r;
screenSettings.ctx.beginPath();
hr.point(lc, yc);
if (ll < xd)
  hr.point(ll, yd);
else
  hr.point(xd, xl);
if (ll < xd && rr > xd)
  hr.point(xd, yd);
if (rr > xd)
  hr.point(xd, xr);
else
  hr.point(rr, xd);
screenSettings.hr.point(rc, yc);
ctx.fill(); // TODO: phase?

where

class pwaPartialFillHelper {
  constructor(screenSettings) {
    this.cx = screenSettings.ctx;
    this.ox = screenSettings.x;
    this.oy = screenSettings.y;
    this.xs = orn.fx ? -1 : 1;
    this.ys = orn.fy ? -1 : 1;
  }
  pointInner(x, y) {
    this.cx.moveTo(
      Math.floor(x * this.xs),
      Math.floor(y * this.ys)
    );
  }
  point(x, y) {
    if (this.orn.fo)
      this.pointInner(y, x);
    else
      this.pointInner(x, y);
  }
}
2
0
21h
About type information in Node.js

console.log(function log(){}); // [Function: log]

In Node.js, if I try to print a function, output is

[Function: log]

Why do they have this convention should not specifying variable name and then its type be more logical?

[log: Function]

And why do they have the expression surrounded with square brackets? It looks like an array.

Randomly select a pre-determined string?

I'm very new to this, and I'm trying to figure out how I would go about creating a program that randomly picks from a set of pre-determined words or phrases and display it in the console using console.log. Can y'all help me out with this? I'd really appreciate it :)

by S4PG
3
3
1d
Functions logic

Is there any resources that would help me understand the logic behind functions on how it works.would prefer a visualization of how it works.

Deobfuscate code

Any ideas that can point me in a direction to de-obfuscate this code? https://pastebin.ai/g8fy6wvkot

baby graphic designer trying to use tweakpane

I just saw this post on insta and it made me really want to learn how to make stuff like this. In the comments the guy says they used Tweakpane
https://www.instagram.com/p/C40HzGztw6x/?img_index=1

can anybody help me in how i can make something like this? im very new to this and im having a really tough time understanding what i need to do

1
1
1d
I’m so confused with this api

I’m coming back to an old project I was working on and am not fully sure where these lines of code came from, because I can’t find any official documentation on the DDG search api, as well as how it formats its returned data. I was hoping someone has some idea of how it might be returning results, here’s the code snippet :

// Step 2: Search each suggestion using DuckDuckGo. const searchPromises = suggestions.map(suggestion => { const encodedSuggestion = encodeURIComponent(suggestion); return fetch(https://api.duckduckgo.com/?q=${encodedSuggestion}&format=json&kl=us-en); });

What to do to get good speeds going through huge Datafiles

I've made a web application which is for Trading and also Back testing for my trading strategies which I have made in JavaScript. My code is in no way optimal and I have to go through it all. Therefore I want to know what I should avoid doing in my code and what to do. And also adding a code snippet wouldn't be a lot of help since I named a few things in a different language and going over it all is a bit to time consuming

First some Information on what my JS code does:
I collect trading data myself using the Binance Api and python to create huge Files with millions of lines of data. This data is then proceed and split for my Web workers that do my Calculation. each worker then cuts down the data.
Since the data that I got from the Api endpoint is in the wrong format to be used for certain Chart libraries or rather for my timeframe of 1 Minute I first have to change the code.
This is currently done by each worker which I do need to change so that another worker file does the conversion one time or that I create a new file with the right data. But that's something I can take care of.

I tested the code with a dataset of 500k lines which is then split and send to the worker around half of that depending on the data is cut down and afterwards is the calculation. This takes around 3 to 5 secs
After some testing I got on average 17s with 10 workers I could increase the worker to 20 but since it was only a test and not the whole data which is around 15 times larger it would still take a long time.
I read something about using a GPU to do the accelerate calculations and would like to hear your though on it?
I have a good PC with the 14th gen i5 and 4070ti which are quite powerful, so when it takes 17s, it's showing me in my opinion that my code is lacking.

Also I plan on making it go through it hundreds of thousands of times using different parameters which I can adjust to get a better strategies. Doing that manual is going to be a pain, therefore I plan to be automatic, but even if It's done effectively it would take a long time.
I do on planning on cutting arrays down to only the bits that are needed meaning the last 100 or 50 elements which are used for the calculation. But it would only save a bit, some arrays just cant be changed because they are needed to display graphs.

My code mostly consist of Functions, If statements, arrays and Loops I don't have a single async function since the only part to implement it would be to change the data but if it takes 5sec or 10sec doesn't really matter since I will only need to calculate it ones.

My Question in short form:

Therefore I would like to hear what should be avoiding coding in JS and what I should do that helps performance when using huge data.
Also is it worth to use my GPU /GPU.js to accelerate the calculation?

I have a bit that I can show but my code basically consist of this format and if question arise I am going to try to answer them as good as possible:

    //Update the data for the SMA series
    if (closeValuesArray.length >= changer) {
        // CALCULATION ON EVERY CLOSE //
            if (closeValuesArray.length >= changer && !cal_on_every_tick) {
            lastChangerValues = closeValuesArray.slice(-changer);
            sumClose = lastChangerValues.reduce((a, b) => +a + +b);
            SMA = sumClose / changer;
            colorSMA = (CloseValue >= SMA) ? '#0000FF' : '#FFA500';
            if (ChunkProcessing === true) { // === true not needed but it's there for clarity
                const SmaSeries = createSmaSeries(LastCandlestick, SMA, colorSMA);
                SmaSeriesArray.push(SmaSeries);
            };
        };
Aiven/MySQL Handshake Timeout
import express from 'express';
import ViteExpress from 'vite-express';
import mysql from 'mysql';
import fs from 'fs';
import { config as config } from 'dotenv';
config();

const app = express();
const pool = mysql.createPool({
  connectionLimit: 10,
  connectTimeout: 60 * 60 * 1000,
  host: process.env.DB_HOST,
  database: process.env.DB_NAME,
  user: process.env.DB_USER,
  port: process.env.DB_PORT,
  password: process.env.DB_PASS,
  ssl: {
    rejectUnauthorized: true,
    ca: process.env.DB_CA,
  },
});


app.get('/posts', (_, res) => {

  pool.query(
    'SELECT * FROM `Images` LIMIT 50;',
    function (error, results, fields) {
      if (error) {
        console.log(`Error:${error}`);
        res.end();
        return;
      }
      if (results == null) {
        console.log('no results');
        res.send([]);
        return;
      }
      let data = [];
      for (let i of results) {
        data.push({
          url: i.ImageUrl,
          name: i.ImageName,
        });
      }
      res.send(data);
    }
  );
});

ViteExpress.listen(app, 3000, () => console.log('Server is listening...'));

It keeps saying Error: Handshake inactivity timeout

I believe this is due to incorrect credentials

im using aiven and mysql. Can anyone experienced with Mysql AIVEN tell me what possible issues I am making with my credentials/sql config?

Thank you in advance

1
0
1d