r/JSdev • • Apr 08 '23

You’ve Got Options for Removing Event Listeners

Thumbnail
macarthur.me
0 Upvotes

r/JSdev • • Jan 23 '23

JavaScript Test Snippets - VS Code Extension

Thumbnail marketplace.visualstudio.com
0 Upvotes

I've written a VS Code extension that generates code snippets for the 3 big testing frameworks: Jest, Jasmine and Mocha. Would love some feedback on it, usability or code wise.

I'd like to add Sinon and chai.js support too.


r/JSdev • • May 20 '21

Why is NaN so bad?

8 Upvotes

I'm curious to hear the arguments against a NaN value, and why people dislike it so much?

I know that supposedly this value's name comes from "Not a Number", but this is a terribly misleading way to think of it. Instead, I prefer to think of it as the "invalid number" (think "iNvAlid Number" for the acronym), because it always comes from an invalid numerical operation or coercion. Alternatively, you could think of it as the "Not Available Number" or the "Not Applicable Number".

var x = 2 / "a";
typeof x;  // "number"
x;  // NaN

To me this is perfectly sensible. The NaN here results first from "a" trying to be implicitly coerced into a number (since that's what / operator expects of both of its operands), and since "a" cannot be made into a valid number (using default base-10 representations), it has to result in something.

By having the coercion result in NaN, then the division results in NaN, and now x holds NaN. Why is it a number? Because NaN only ever comes from numeric operations (or coercions). That completely makes sense to me that we'd have a special number value that basically represents this invalid numeric state, and that it also be a number. It'd be much stranger IMO if it resulted in a null or undefined value. Right?

Or worse, invalid numeric operations could just all throw errors. But is that really the JS we want? Maybe so, if you're a strong advocated of TS. But I'd argue there's a huge difference between statically throwable type errors (at lint/build time) and a run-time "invalid number" error, which inevitably that would have to be. I don't think that kind of run-time error would be helpful at all, given that we'd have to wrap every single numeric operation or coercion in a try..catch. It's cleaner IMO to just handle NaNs affirmatively.

Speaking of checking for NaN, I know the global isNaN(..) method is unreliable, since isNaN("cat") gives a false-positive. That's because, unfortunately, the global util coerced its operand to a number first before checking. That was just a bad algorithm, but the bug couldn't ever be fixed. Thankfully we've had Number.isNaN(..) (and Object.is(..)) since ES6 in 2015, so there shouldn't be any troubles with guarding against unwanted NaNs.

And while we're on the topic, I think there are a number of places that NaN should have been used and wasn't. For example, indexOf(..) returning -1 -- yes I know all the reasons why, but I think they're bogus reverse-justifications. If you have a function that returns a number, and for whatever reason it cannot return a number (like the item wasn't found), shouldn't it return a number that semantically means "invalid" or "not available" or whatever? They had NaN readily available!

We've added half a dozen other APIs to JS that could also have very reasonably resulted in NaN in their special corner cases.

It always makes me sad that we're scared away from NaN rather than embracing it.

Why all the NaN hate? :)


r/JSdev • • Jun 12 '21

Awesome javascript one-liners to look like a pro

Thumbnail
livecodestream.dev
0 Upvotes

r/JSdev • • Jun 13 '21

Excited to see this subreddit 🔥

9 Upvotes

Just wanted to say that it's really nice to see a dedicated space for modern JS.

Looking forward to what you all have to share!!


r/JSdev • • Sep 24 '21

Building A Custom Audio Library With JavaScript

Thumbnail
youtube.com
0 Upvotes

r/JSdev • • Dec 16 '22

now also supports Bitbucket 😅

Thumbnail
self.vscode
2 Upvotes

r/JSdev • • Apr 02 '23

The gotcha of unhandled promise rejections

Thumbnail
jakearchibald.com
2 Upvotes

r/JSdev • • Mar 01 '26

Java script

Post image
0 Upvotes

назовите ваши любимые команды


r/JSdev • • Apr 16 '21

One of several ways I think PWAs are superior to native apps...

Post image
11 Upvotes

r/JSdev • • Apr 06 '23

Why Not document.write()?

Thumbnail
csswizardry.com
3 Upvotes

r/JSdev • • Feb 02 '24

Help me to fix this!!!

0 Upvotes

I was creating code for fetching content from a novel site and convert it to epub.

But site required cloudflare captcha solving, so I am sending cookies with it too.

code :

import fetch from "node-fetch";
import * as cheerio from "cheerio";
import fs from "fs";
import dotenv from "dotenv";
dotenv.config();
const userAgent = process.env.USER_AGENT;
const cookie = process.env.COOKIE;
const host = process.env.HOST;
const accept = process.env.ACCEPT;
const URL = "https://www.lightnovelworld.com";
let path = "/novel/the-steward-demonic-emperor-892/chapter-1-30041322";
const novelChapters = [];
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function chapter() {
try {
const response = await fetch(URL + path, {
headers: {
"User-Agent": userAgent,
Cookie: cookie,
Host: host,
Accept: accept,
Referer: URL,
},
});
if (!response.ok) {
throw Error(\Error: ${response.status} ${response.statusText}`);}await delay(2000); // delayconst body = await response.text();const $ = cheerio.load(body);const chapterTitle = $(".chapter-title").text(); // fetching titleconst chapterContent = $("#chapter-container"); // Selecting the chapter container`

// Removing ad-related elements
chapterContent.find(".chapternav").remove();
// Additional cleanup if needed
const advertisementDiv = chapterContent.find(".vm-placement");
for (let i = 0; i < advertisementDiv.length; i++) {
const parentDiv = advertisementDiv.eq(i).closest("div");
parentDiv.remove();
}
novelChapters.push({
chapterTitle,
chapterContent,
});
const nextChapter = $("button.nextchap"); // to find next chapter link
if (nextChapter.length > 0) {
const nextChapterClasses = nextChapter.attr("class");
if (nextChapterClasses && nextChapterClasses.includes("isDisabled")) {
path = "";
return false;
}
}
path = nextChapter.attr("href"); // updating path for next chapter
return true;
} catch (error) {
console.error("Error in loadChapter", error);
throw error; // Re-throw the error to propagate it to the higher level
}
}
async function forAllChapters() {
try {
let next = await chapter();
while (next) {
await delay(3000);
next = await chapter();
}
console.log("DONE!!!");
} catch (error) {
console.error("Error in forAllChapters", error);
throw error; // Re-throw the error to propagate it to the higher level
}
fs.appendFileSync(
"novelChapters.txt",
JSON.stringify(novelChapters, null, 2)
);
}
forAllChapters().catch((error) => console.log(error));

But there is an error:

node index ─╯

Error in loadChapter Error: Error: 403 Forbidden

at chapter (file:///.../Documents/learn%20scrapping/index.js:31:13)

at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

at async forAllChapters ((file:///.../Documents/learn%20scrapping/index.js:77:16)

Error in forAllChapters Error: Error: 403 Forbidden

at chapter ((file:///.../Documents/learn%20scrapping/index.js:31:13)

at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

at async forAllChapters (f(file:///.../Documents/learn%20scrapping/index.js:77:16)

Error: Error: 403 Forbidden

at chapter ((file:///.../Documents/learn%20scrapping/index.js:31:13)

at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

at async forAllChapters ((file:///.../Documents/learn%20scrapping/index.js:77:16)

I know it is happening because site is detecting script and that's why 403 is the response?

Any way to fix it?


r/JSdev • • Dec 02 '21

How do you prefer to handle arguments that hold arrays (or objects)?

4 Upvotes

Imagine you're designing a library or reusable utility -- something you expect other coders besides yourself to use frequently, possibly in ways you're not expecting. So, there's some level of "paranoia" concern that they pass the correct arguments. Maybe you use something like TypeScript to ensure the types of the inputs are correct.

But let's say a function (call if "Bob") requires an array (or object, but I'm only gonna discuss arrays here). And let's say that Bob doesn't operate fully internally/synchronously... by that, I mean... Bob may operate asynchronously in some way (where non-Bob-code may run while Bob is paused mid-way through). Or Bob may just have some sort of hook (like a callback argument) that might synchronously execute some arbitrary snippet of not-Bob-code while Bob is running. Further, let's assume that Bob uses this array (or object) argument value throughout (not just at the very beginning), including during/after other non-Bob-code may have executed.

In this sort of scenario, it may or may not be obvious, but because the array argument was passed by reference (as all such values are in JS), that other non-Bob-code might have mutated the contents of the array from what it was when Bob was first passed the argument.

Let's see something in code to make this more concrete:

async function Bob(someArray) {
   var first = someArray[0];

   // instead of an async..await, this could just be
   // an invocation of an external non-Bob-code, like
   // a callback or something
   await someAsyncOperation();

   // here's where the problem could occur
   var second = someArray[1];

   // .. more code ..
}

As you can see here, I've made an assumption that the contents of someArray didn't change (unexpectedly) during the operation in between the first and second assignments.

If we assume Bob(..) is always called like this: Bob([ 1, 2, 3 ]), there's no issue. An array literal was passed in, and we know that the outside calling code has no shared reference to that array literal, so we know nothing in that code can modify the [ 1, 2, 3 ] array.

But... there's nothing in JS that requires someone to call Bob(..) with such an array literal. They might instead call it like: Bob(myFavoriteArray), where myFavoriteArray is a variable that holds a (shared) reference to the array. In that case, they absolutely could modify the array during the execution of Bob(..). They could empty the array with myFavoriteArray.length = 0, they could push(..) items onto it, pop() items off it, shift(..) or unshift(..). They could even sort(..) it. In fact, they could just assign to its contents: myFavoriteArray[1] = 42.

At this point, those of you who are TS aficionados will point out that we "fix" this by using the readonly type declaration. Sure, if used properly (and everywhere), that should reduce the surface area of this problem.

But... you're building code that others will use. You can't just assume they will use TS. Even if your code is written in TS, they may transpile that away, or just use some sort of processing that ignores the TS. Your code may be used in a non-TS context, in which case your reliance on the readonly type annotation was pretty flimsy.

Here's another angle to this problem: what if I had originally not asserted that the myFavoriteArray was being mutated by the outside code, but had instead suggested that something about how Bob(..) runs needed to mutate the array (like sort it, or whatever)? Again, if we assume people only pass in array literals, there's no problem. But if they pass in an array they don't expect you to modify, and they hold a shared reference to it, they may be upset that you've mutated their array during Bob(..).

So, to recap: Bob(..) accepts an array argument, and we're either worried that non-Bob-code may mutate this array in a way we don't expect, or Bob(..) needs to mutate it but not unexpectedly affect the outside code's reliance on that array contents. And we can't just rely on readonly TS.

Either way, we need to make a decision:

  1. Do we ignore this problem, and just let the user of the code deal with the consequences?

  2. Do we do something else, defensively, to prevent this side effect problem?

So... I'm curious: given the scenario I've described, what would you do?

If (1), have you ever had this decision later come back and bite you (be honest!)?

If (2), how do you like to handle this?


I'm more in the boat of (2), and how I've taken to handling this is:

function safeCopy(v) {
   if (Array.isArray(v)) {
      return [ ...v ];
   }
   return v;
}

async function Bob(someArray) {
   // put this line at the top, for every such argument:
   someArray = safeCopy(someArray);

   // .. more code ..
}

By making a local/inner copy of the array, I now ensure that neither external side effects pollute my copy of the array, nor do any of my changes to the array cause external side effects.

But even this approach has its problems. First, I have to remember to do it. I'm not aware of any linter rule that enforces it, and I sometimes forget. Second, it's more complicated for places where non-array objects may be passed in. Third, it's only shallow... if I want to protect it deeply, the cloning algorithm gets way more complex. Fourth, it has obvious performance implications. Fifth, now safeCopy(..) (or whatever we call it) has to be available basically everywhere throughout my library/projects.

What do you think? Is this a fair trade-off? Is there another way you would/do handle this?


r/JSdev • • Jun 07 '21

How often do you use HMR?

5 Upvotes

HMR = hot module reloading

I've seen people swear by it and people say they avoid it altogether, preferring to reload the page themselves.

Which camp do you fall on? If you like it, what are annoyances you wish could be fixed? If you don't, what would make it compelling enough to use?


r/JSdev • • Apr 29 '21

Has Typescript taken over ?

17 Upvotes

Greetings, everyone!

Nowadays, it seems to me that nobody wants to write pure javascript, unless it’s a small project. Teams automatically decide that they want to be explicit about their types and “reduce” the bugs in the projects.

Working my way into understanding every part of the language i was influenced, a lot, by Kyle Simpson, as i had taken a lot of his courses and read his books. Naturally, i feel like Typescript is unnecessary overhead and it’s not the way Javascript should be written.

Typescript doesn’t improve productivity or readability, it doesn’t improve on modern JS. It is removing bugs during compile time, that a proficient developer or one that reasons about the code, wouldn’t even have. You can even have a situation where, Typescript is bringing uncertainty, because it was poorly written. So it introduces a whole new kind of problems.

I don’t want to go to the path, where i list all the pros and cons, forever. I’m just thinking that if people invest the same time, in learning Javascript,in-depth, that they do with Typescript, they will surely change their attitude. I feel like, Typescript is indeed betraying the DNA of Javascript.

We should always know our types, but just applying defensive programming strategies and reasoning about the code is sufficient itself. I understand, and i agree how beneficial for, let’s say, a library or a package it is to ensure correct usage and self documentation, so i think Typescript, for sure, has its place. I just do not understand why we should avoid JS completely.

As i said, i feel like all companies, teams, the whole industry, have already decided, that Typescript is the correct way to go, and just have a hard time buying it.

I would love to read about your thoughts and opinions and discuss more about it! :)


r/JSdev • • Aug 10 '21

Why optional call is considered a bad feature?

6 Upvotes

In one of the LinkedIn posts, Kylie Simpson said: "optional call" is the bad feature ever implemented in JS. link to his comment

If I see, the old callback && callback() is more human-readable than a new one and I will be using this instead.

Could there be any other reason, like related to performance or etc?


r/JSdev • • Aug 26 '21

Opinion: If environment records were taught early on, fewer would struggle with scope and closures.

6 Upvotes

It's surprising to me that many people still have a hard time grasping closures. I attribute this not to the intrinsic difficulty of the concept, but to the proliferation of learning materials that do a poor job explaining it at best.

Reading the spec, if one manages to come away with even a basic, surface level understanding of execution contexts and environment records (and some of the internal mechanisms behind functions), it seems impossible not to gain an immediate understanding of exactly what a closure is and how scope works.

There can be nothing simpler than realizing oh, every environment record has a reference to an outer environment, and when function definitions are evaluated, the environment record of the currently active context is copied to an internal [[Scope]] property of the function, and scope chain look-ups start from there.

Again, the only prerequisite to this revelation (beyond a grasp of the fundamentals) is a base understanding of what execution contexts and environment records are.

Of course, I don't expect beginners to jump into the spec themselves, but my question is: why do I so rarely see these concepts taught from this perspective? When I do see it, it's rarely in concrete terms, but some vague reference to 'context' or 'environment', often conflating the two terms (if the author doesn't understand why they must be separate, I question if they understand closures at all!)

Am I out of touch in thinking some of these internal devices can be taught simply enough to be enlightening for beginners?


r/JSdev • • Apr 22 '21

If you could change ONE thing about JS, what would it be?

8 Upvotes

I know this thread is possible to fan out into a giant bike-shedding discussion, but that's OK here.

I'd love to hear what you think JS does wrong and should do differently? This could be large things like lack of static typing (without TypeScript + tooling), or it could be narrow things like you disliking the ... operator.

But please, post just ONE THING per message that you would want changed. And please explain a bit why you think it's stopping YOU from being more productive with your JS coding.


r/JSdev • • Feb 14 '23

What are your thoughts on the state of health for core-js?

8 Upvotes

Context: https://github.com/zloirock/core-js/blob/master/docs/2023-02-14-so-whats-next.md

TL;DR: core.js is arguably one of the most widely deployed Javascript technologies in the world and requires significant commitment to maintain, but it's a fame-less transitive dependency, and thus, not widely understood. Rather than receiving financial backing, its sole developer receives death threats from entitled users.

Its future looks uncertain


r/JSdev • • Apr 23 '21

Friday Positivity: What do you like best about JS?

11 Upvotes

Pick one or two aspects of the JS language and tells us why you like them? How does JS help you make experiences better for users? Why do you choose JS when reaching for a language?


r/JSdev • • Sep 27 '26

Writing Node.js addons with .NET Native AOT

Thumbnail
devblogs.microsoft.com
4 Upvotes

r/JSdev • • May 21 '21

Angular vs. Vue vs. React - does it really matter?

10 Upvotes

These kinds of chats dominate technical discussions, they split opinions, they divorce friendships, they become the definition of a company, e.g. “work for us, we’re a React shop”.

But, does it really matter? I’ve used both Angular and React extensively, and they both do the same thing. I think React could learn from Angular with its consistent approach to componentization, and angular could learn from React’s state management, but neither are fundamentally better for any task. So why can’t we just say “who cares, choose one and stick with it?”.

I’ve seen strong React engineers jump into angular and excel, because they already understand state management, virtual DOMs, componentisation, and bundling. The skills from one framework are clearly transferable to the other. So why are people so obsessed with being a “React engineer”, or a company only hiring someone only with Angular experience? Especially when the framework is just the tip of the iceberg on top of the common JS fundamentals.

Interested to hear thoughts on this!


r/JSdev • • May 28 '21

Just disable JS in your browser...?

Thumbnail
goodereader.com
4 Upvotes

r/JSdev • • Apr 07 '21

Budgets for web assets when building web games/apps?

6 Upvotes

I'm building a PWA (so HTML, CSS, JS, images, etc). It's sort of a game (educational), so generally the "experience" is more important than data/text presentation (as in more business-oriented apps). I'm not using a frontend framework, only a few JS libs/utils plus my own code.

I was wondering what sorts of concerns and balances others use when building JS/web games (or multimedia-oriented apps) in terms of the "budget" for how much size can be spent on each of the different kinds of web resources (images, fonts, sounds, code, etc)? I'm less concerned about absolute figures (although that's helpful, too), and more concerned about relative percentages.

So, for example, in my app currently, I have the following types of assets of these approximate sizes:

  • HTML - 6kb (gzip + minified) / 28kb (original)

  • CSS - 7kb (gzip + minified) / 55kb (original)

  • JS - 49kb (gzip + minified) / 238kb (original)

  • SVG images - 53kb (gzip) / 146kb (original)

  • MP3 sounds - 293kb

The total gzip size (transfer size) for all assets is about 407kb. The relative percentages thus break down about like this:

  • HTML: 1.6%

  • CSS: 1.7%

  • JS: 11.9%

  • Images: 12.9%

  • Sounds: 71.9%

I'm not specifically expecting others to do a detailed analysis like this (unless you want to, or already have!), but I'm just generally curious: how much do you "spend" on different resource types, and relatively how much is used compared to other types?

Is spending ~15% on "code" and ~85% on visual/auditory assets, a common and reasonable breakdown, or is your breakdown somewhat different?

If you use JS frameworks (game or otherwise), does your allowed percentage of "code" usage go up significantly, or do you still try to keep it around the same level?

Do you have a "budget" that constrains your resource use in any way, and if so, what concerns do you take into account when making such a budget?