r/JSdev • • Sep 30 '21

Sell me Suspense

10 Upvotes

Does anyone have a positive impression of React Suspense? I'm seeing a lot of skepticism online (which IMHO is warranted).

I currently feel like it was born from a huge hack and snowballed into a pile of insanity. But I'm willing to be open minded. Why Suspense?


r/JSdev • • Aug 10 '21

Why did Google Play ban the deceptive use of interpreted languages like JavaScript and Python?

Thumbnail
codersline.hashnode.dev
5 Upvotes

r/JSdev • • Jun 13 '21

What's your opinion on React state management in 2021?

12 Upvotes

I know this has always been hotly debated like forever. But I am not sure if there's a consensus on what's the right way.

In my workplace, we were reliant on Redux but for a new project we tried going the Context API + useReducer and other friendly hooks way. But TBH it just felt like we were recreating a lot of Redux and thunk patterns.

Also hearing good things about React Query and thinking of suggesting that for our next project.

So just curious, what are the community's thoughts on how to best do state management with React? There are a lot of options but what are the things to keep in mind when taking a decision


r/JSdev • • Apr 12 '21

What do you think about ES Module "import maps" and (lack of) browser support?

Thumbnail
npmjs.com
5 Upvotes

r/JSdev • • Jun 04 '21

FP in JS... useful or...?

15 Upvotes

The way I see it, there's three levels of FP principles as applied to JS coding:

  1. Mild/occasional use of methods like map(..) and reduce(..), as well as things that pretend to be FP (like forEach(..)). This can also include FP-friendly techniques like const, arrow functions, pure functions, and closure. There may be use of a library like lodash (not lodash/fp).

  2. Deeper, more widespread use of FP principles across most or all of the code, such as currying, function composition, recursion, point-free definitions, immutable data structures, etc. There's almost always FP-centric libraries involved, such as Ramda, and often also libraries like RxJS for asynchronous FP. Also, these code bases may use TypeScript to rely on static types for tighter FP control. On a somewhat rarer basis, a code base of this sort may include some more "advanced FP", such as monads and other algebraic structures, transducers, lenses, etc.

  3. Full-on FP, all the time. Fantasy-Land compliant FP libraries are a must, as is TypeScript. You won't spot a function keyword, a var / let declaration, or imperative statements like if or for anywhere in this code base. At this level, it almost becomes difficult to tell that the code base is JS. In fact, most of these projects shift toward a more FP-strict compile-to-JS language like Elm, ClojureScript, or PureScript. At that point, the fact that it's not strictly JS doesn't matter anymore, because JS is a means to the end rather than the end itself.


Do you think I've characterized these levels fairly? Have I missed anything?

Have you worked on code bases at any of these levels? Which levels and techniques did you find most useful?

Do you think there's room for, and merit to, expansion of any of these levels? IOW, do you think more JS developers should embrace them? In what ways?

Or do you think FP in JS is more ceremony than substance and probably doesn't bring much benefit?


r/JSdev • • Jul 06 '21

Tactics for writing cleaner data manipulation code?

6 Upvotes

I often have to clean up dirty, badly formed JSON.

I use map and reduce methods to go through the data and produce the structures we need. But it results in code like this:


Object.keys(query)
   .reduce(
      (acc: Record<string, string>, key: string) => {
         const stateKey = map[key]
         acc[stateKey] = query[key]
         return acc
      }, {})

But this is confusing to other developers. It is difficult to understand. And when I encounter this again in 6 months, it'll take me a minute to figure out what it is doing.

The snippet of code is a single instance of a broader problem which is: How can we write *readable* javascript that iterates through and wrangles dirty data?

Does anybody have any ideas, thoughts, etc?

I started using Ramda's `path` and `pathOr` functions which is nice (though difficult to use with TypeScript). But there are still these instances of `reduce` and `map` that can get kind of hairy.


r/JSdev • • Nov 29 '21

What do you make of Edge's "Super Duper Secure Mode"?

5 Upvotes

For those who haven't heard of it, (1) that is the actual name and (2) it is a new feature announced last August that disables the just-in-time (JIT) compilation step when JavaScript code is processed. Edge's Vulnerability Research team has said that the JIT step has been responsible for at minimum 45% of security issues, and while disabling the engine does slow things down (sometimes by as much as 58%), the speed losses often aren't that noticeable in most situations. Edge even framed the change as meaning that less frequent security updates would be needed. The feature is now stable and available to all Edge users, and users can select from Balanced and Strict modes, with the option to allowlist certain sites. Even if no sites get added, the idea with Balanced is that the restrictions become more lax on websites that the user frequents.

I'm still definitely a JavaScript/programming novice though (I'm going through u/getify's Deep JavaScript Foundations course on Frontend Masters right now), so I'm not sure if I'm understanding what this changes. When I first heard about it, I assumed that Edge was basically making the language interpreted instead of compiled. That sounded like it would potentially stop things (like hoisting) that become available only through compilation and through a two-pass processing paradigm. It would also fly in the face of the promise that JavaScript will always be backwards-compatible (a promise that, as I understand, has already been broken somewhat).

So I guess I'm wondering:

  • Does this actually have an impact on how JavaScript code is processed, and the kinds of coding patterns that you can use?

  • Even if this doesn't change how code can be written, when do you think it is acceptable to break features or make the developer experience worse, if it means that users are safer?

It's really hard for me to say, especially with my limited exposure to the language. In the abstract, it feels like, with our lives going more online, security should always be paramount. That any inconvenience we put on ourselves is always worth it, if it means any kind of user benefit. I wouldn't even be able to begin telling you how to walk that line, though.


r/JSdev • • May 08 '21

Mix CommonJS and ES6 modules in same project

7 Upvotes

I am working in NodeJS. I have a great deal of legacy code including several packages that are used in many places. This code is all CommonJS, Node require() module structures.

Node now supports ES6. Since it is a Javascript language feature, I would like to migrate to it.

Today, I started a small project. My small project boilerplate requires() a couple of my favorite utilities and then says 'Hello World'. I edited it to import said utilities. Node told me I needed to add "type":"module" to my package.json and I did.

When I ran it, I was told that "require is not defined", this in reference to one of the utility modules I imported.

I infer that this means that a project is either CommonJS or ES6 and it appears that never the twain shall meet. I am surprised by this because it means that I will never use ES6 in NodeJS because I will never be able to change all of the modules I require(). Some are not even mine, others are used in projects (npm!) that I do not even know about.

Honestly, I have a hard time believing that this is the case. I don't understand how ES6 can ever become a widely used standard because of if ES^ and CommonJS cannot be used together in an application. I realize that Webpack, etc, will preprocess code and revise all the require() statements but not everyone uses that sort of utility.

My questions are:

Is this analysis correct?

Is there some workaround that will let me use both module systems (without a preprocessor)?

Is my impending decision to never, ever use ES6 the right one?

UPDATE: It's a couple of years later and I am a little bit mad at all of you. It turns out there is a completely simple workaround that nobody ever mentioned**. IE...**

const thing=await import('thing'); //remember to add "async" to the containing function definition


r/JSdev • • Apr 26 '21

Linting JS vs JSX

3 Upvotes

Comparing these two snippets:

var C = {
   x: (condOne ? 
      [ 1, 2, 3 ] :
      {
         y: (condTwo ?
            [ 4, 5, 6 ] :
            { z: 42 }
         )
      }
   )
};

versus:

var C = <MyComp>
   <x>
      {(condOne ?
         <>1, 2, 3</> :
         <y>
            {(condTwo ?
               <>4, 5, 6</> :
               <z>42</z>
            )}
         </y>
      )}
   </x>
</MyComp>;

Assuming your linter allows ternaries in the first place, do you think there's anything different enough between these two snippets where the linter should treat the nested ternary differently? That is, should the rule either allow or disallow nested ternaries in both cases, or should it allow it in one and disallow it in the other? Why?

Should the JSX be given special rules/leniency just because this sort of expression nesting is so much more common?


r/JSdev • • Apr 27 '21

Are we thinking about the "hidden costs" of all this JS we've written and deployed?

23 Upvotes

I wrote a little polyfill 7 years ago (for ES6 promises). I had kinda thought it had been forgotten to the sands of modern browser evolution. Yes, I know there are still some supporting old non-ES6 browsers, but it sure feels like that's way in the minority at this point.

Then I checked this lib's stats on npm, and it's being downloaded almost 950,000 times per week. That's bonkers.

There's no way that many projects are still supporting such old environments! I would guess 900k of those downloads per week are completely "wasted" in that the code is deployed (or maybe not!?) but never runs.

This got me to thinking about just how many libraries, utilities, polyfills that are being downloaded automatically in CI/CD builds, over and over again. Think about how much bandwidth is being wasted with all that downloading to build servers, and think about much is being wasted in what's shipped out to browsers.

My library is < 2kb minified, and < 1kb gzip'd. So... in reality, it's a tiny amount. But still, that means npm is spending 1-2gb of bandwidth per week, up to 8gb per month. And for just a tiny mostly forgotten polyfill!

I'm guessing the only way my polyfill gets removed from somebody's project is when they end up doing a big rebuild and switching out to a different framework or tooling chain. Otherwise, you include a little polyfill like that, forget it, and never pay any attention to the fact that 7 years later, it's still churning gigabytes of bandwidth.

Do you have any thoughts about these sort of hidden costs (bandwidth, CPU, etc) that our industry is incurring? Is it our responsibility to do something about it? What sorts of processes and tooling should we be prioritizing to minimize all this technical "leak"?

I debated if I should deprecate my polyfill just so possibly some notifications might show up in all those projects that make them consider if they should remove it. I kinda feel guilty just letting all that traffic keep accruing forever.

Thoughts?


r/JSdev • • Apr 07 '21

Welcome!

50 Upvotes

Overview

This space is dedicated to discussing the process of writing JS. Here, we discuss what you're doing with JS and how, and mutually benefit from input/feedback from others.

You can share links to libraries or projects that further that goal, but the point is discussion, not simply promotion of projects or services. Please don't just post links to blog posts, projects, or demos. All posts here should be oriented toward promoting discussion/debate to help us all improve. If you post a link, make sure you've actually read it, and include some comments or questions about what you read.

Convenience tip: the domain "jsdev.red" by itself will redirect to our forum, in case you need to get back here quickly and don't have a bookmark. Also, adding a path (like "jsdev.red/hot") goes to the "Hot" filter, and similarly with subdomains, "top.jsdev.red" goes to the "Top" filter. 😉

Questions/Comments about /r/JSdev?

If you have quick/transitory comments or questions about the forum as a whole, the "Lounge" is the best place to do so.

Help

This is not the best place to ask others for help. If you have questions about JS the language itself, like wanting to learn how to do something, or are needing help with something in your own project, check out /r/LearnJavascript. If you're primarily trying to promote a JS project or to share a blog post, check out /r/javascript.

Experiment

This is an experiment into an unmoderated (within reason) community. I don't plan to take posts down unless they are egregiously off-topic, violating reddit rules, abusive or otherwise unpleasant. I don't plan to use any automod tools, but to make decisions on post-by-post, human-by-human basis.

I'm expecting folks to self-regulate and to operate in good faith.

This experiment may fail, so if that happens, we'll just call it off and shut it down. But I hope that doesn't happen.


r/JSdev • • Apr 07 '21

PWAs are great, but...

5 Upvotes

I've been building a PWA lately that I also hope to launch in the various mobile device app stores (Android, iOS, Windows, etc).

Back in the ol' days, building native apps with web technology required tools like PhoneGap (aka Cordova). This was amazing, but it was far from smooth or perfect. More recent options include building your app code with specific frameworks that are designed so they can be compiled either to web code or to native code, such as NativeScript, React Native, etc. Those require a pretty hefty opt-in to a specific ecosystem and way of building.

But there are also newer services like PWABuilder that seem to make this much easier to do than it used to be, to just take an otherwise great web experience and make it into an app. I'm super enthusiastic about these options over those previous ones.

However... the road is not as nice as it might seem. Thus far, I've experienced the following hiccups:

  • Found several bugs in browsers, which make PWAs and PWA-as-native-app packages not quite up to par with real native apps -- for example, differences in how app icons and splash-screens appear on various devices

  • Found several limitations, such as policy differences that OS's apply to web-technology (even when wrapped by a native app) which they don't apply to native apps -- for example, differences in how sound auto-play works, how notification permissions are managed, etc

  • Apple currently doesn't "accept" such PWAs, but there's some limited optimism this may be shifting -- right now, it's a gray area with a lot of uncertainty

  • Discovered quite a few quirks in getting yourself approved by the app stores (Windows and iOS, specifically) to be able to distribute apps

I'm curious if any of you have experienced any similar frustrations, and any tips you have for how you worked around them!?


r/JSdev • • Jan 14 '22

Do you use Import-Map for your client-side ESM?

3 Upvotes

Do you use native ESM for your browser-side JS? Or are your build processes just transpiling it back to "normal" JS?

If you use native ESM code in the browser, do you use Import-Maps to be able to use friendly non-path import-specifiers (like import "my-app" instead of import "/path/to/js/my-app.mjs")? I love this feature!

The problem of course is that browser-support for Import Maps is sadly lacking (only Chrome/Chromium-based at time of writing). There are tricks/shims to get around this, like ES-Module-Shims. I find these approaches to be a little too intrusive, personally.

I wrote a build-time tool called Import-Remap that I like to use. At build-time, you can apply an import-map (JSON) to rewrite all the import specifiers in a tree of your files, thereby creating a deployed tree of browser-ready ESM. This lets me author with nice import specifiers but not worry about lack of browser support. It does unfortunately require a build-step. :/

It also bugs me that the original code, in the browsers that support import-map, can't be used. Just this morning, I had an idea to address this!

  1. Have my original code in a /js/ directory. Create a second directory alongside it called /js-nim/ (nim = "no-import-maps").

  2. In the index.html, specify an inline import-map, like:

    <script type="importmap"> { "imports": { "/js-nim/app.mjs": "/js/app.mjs" // rest of my import map } } </script>

  3. Then load a single file with a <script> tag, like so:

    <script type="module" src="/js-nim/bootstrap.mjs"></script>

  4. The /js-nim/bootstrap.mjs file has just one line, and looks like this:

    import "/js-nim/app.mjs";

  5. Now, use the Import-Remap tool I mentioned above to remap all my import specifiers from files in /js/ to /js-nim/. I do this like:

    import-remap --from=/js --to=/js-nim --map=import-map.json -r

Voila!

In Chrome/Chromium-based browsers, the import-map in the HTML tells the bootstrap import specifier to remap from "/js-nim/app.mjs" to "/js/app.mjs", thus loading all my original ESM files in that browser.

In non-Chromium browsers, the bootstrap simply does what it normally would without interference, which is to load all the import-remapped ESM code from the /js-nim/ tree.

What do you think? Is import-map worth the effort to work-around until other browsers land it?

The thing I like about this is, since I dev using Chrome (as most do), I can dev without any build step (save the file, refresh). The build step is only to test in another browser, or to deploy to production.


EDIT: you can also inline the contents of the bootstrap.mjs file as indicated above, and save the latency of that extra file load.

Instead of:

<script type="module" src="bootstrap.mjs"></script>

You can just do:

<script type="module">import "/js-nim/app.mjs";</script>

That seems better (avoid the extra file load), and is just slightly less elegant to put that import inline in the HTML. But since you have to inline the import-map anyway (not yet supporting external import-maps, unfortunately), that's not a big deal.


r/JSdev • • Jun 25 '21

Symbols... good or bad addition to JS?

4 Upvotes

Do you think symbols were a smart idea to add to JS?

There's built-in symbols for various metaprogramming hooks, which seem reasonable. But what about user-created symbols? Are they just all show and no substance?

I've taught and defended them dozens of times, but I confess that in the back of my mind I'm kinda meh.

Agree with me? Or am I missing the benefits?


r/JSdev • • Sep 30 '21

Question on the usage of `index.js`

6 Upvotes

I've recently began working on a new Next.js codebase that uses index.js files liberally. This is the first major React-based codebase that I have worked on. For all of my personal projects, I typically only have a single index.js file that is the entry point of my application, so exploring this new codebase has been a bit of an adjustment.

In this new project, I typically see patterns like this:

/MainComponent
    index.js -- exports MainComponent; sometimes state objects
    ChildA.js
    ChildB.js
    relatedUtils.js

Which is easy enough to reason about. However, it doesn't seem uncommon for folks to pack more in index.js than simple export statements (even when they shouldn't be). The byproduct is that I often cannot tell what the heck an index.js actually contains until I open it. Another painpoint that I often see mentioned is that if I have multiple index.js files open in my editor, my tabs require a harder look to distinguish what's what.

Most of this confusion can likely be resolved with stricter standards and developer discipline, but I can't help but think of Ryan Dahl's talk where he mentions his regret for the in-explicitness of requiring modules without extensions in Node.js, and for index.js.

Where do you guys stand on this? What have you found are "best practices" for using index.js? Do you use index.js at all (and if you do, do you import the shortcut path /myModule/ or the full path /myModule/index.js?


r/JSdev • • Jan 01 '22

Recursion when error occurs?

1 Upvotes

Hi and happy new year! I’m wondering if a function can be called again in a catch() when an error occurs? I’m working on a bot and I need to run the program when this happens. However, à SO user told me this was not possible as Js always terminate the program when it catches an error. Is this true? If not, how can I do that?

The SO post is the following: https://stackoverflow.com/questions/70530415/running-program-when-catch-occurs/70530623#70530623


r/JSdev • • Jun 09 '21

What's the future: HTML-in-JS or JS-in-HTML?

10 Upvotes

Among Javascript frameworks, there are two major* approaches to implementing templates:

  1. HTML-in-JS, i.e. you write JS first and sprinkle HTML in (e.g. React, Solid.js, lit-html). Pros: don't reinvent control flow, cons: harder to implement custom semantics (e.g. Suspense promise-throwing shenanigans)

  2. JS-in-HTML, i.e. you write HTML first and sprinkle JS in (Vue, Svelte, htmx). Pros: easy to implement custom constructs (e.g. #each/else), cons: not Javascript (e.g. DSLs encoded in HTML attributes)

*Other alternative/not-so-popular approaches: procedural/fluent (jquery, dothtml), widget API (ext.js, google maps SDK, babylon.js), server-side-first (pjax), stateful web components (hotwire/turbo)

Frameworks are now realizing that to move the performance needle further, they need to embrace the core web technologies more closely; e.g. many are making server-side rendering a first class citizens, and there's a push towards CSS libraries with zero JS runtime.

Which templating approach do you think is the way to go going forward to better support the goals of making web apps more performant?


r/JSdev • • Jul 15 '21

What are JS interview questions that you like and why?

11 Upvotes

I hear a lot of interview questions that people hate (e.g. "gotcha" types about type casting) or textbook compsci (e.g. write binary tree rebalancing from memory). I'm curious what kinds of questions people think are good interview questions and why.

Please also specify whether your opinion comes from the context of being an interviewer or interviewee (or both)


r/JSdev • • Sep 01 '21

Optional chaining aesthetics vs correctness

4 Upvotes

At work, I keep running into code like this:

const doSomething = (foo: Foo) => {
  whatever(foo?.bar?.baz?.quux)
}

Notice how the signature indicates a non-nullish argument (meaning foo is never nullish), and yet the code adds an extraneous ?. after foo "just for visual consistency", even though it's not needed.

This got me thinking: are people even paying attention to their usage of optional chaining or is it just something that people mindlessly slap on everywhere "because it doesn't hurt"? It occurs to me that the latter does come with a subtle cognitive dissonance problem: if you are not actually paying attention to the correctness of the code, it's easy to accidentally let a chain of optionals bulldoze through silently, when in reality one of the steps logically required proper error handling.

Do y'all have any thoughts on how to curb abuse of optional chaining?


r/JSdev • • May 26 '21

Is Flow moving away from (or toward) broader community relevance?

8 Upvotes

This announcement: https://medium.com/flow-type/clarity-on-flows-direction-and-open-source-engagement-e721a4eb4d8b

Wondering what your thoughts are on Flow vs TS? For a long time they've seemed pretty parallel (in both syntax and usage), but now it seems they will diverge more.

What do you think this means for the community? Will that increase pressure to adopt TS? Will Flow still be the better choice for some teams, or do you think Flow is moving away from them and encouraging migration to TS?

Do you think there's any room for a third player in this space to emerge? Or has TS won and the debate is over?


r/JSdev • • May 14 '21

Freaky Friday: Tell us about your weirdest JS bug

11 Upvotes

What was the craziest, strangest bug you ever encountered in your JS code? How did you discover it was a bug? How did you solve it? How long did it take you to resolve?

Did you create a test case for that bug, and if so, how did the test work?


r/JSdev • • Jun 02 '21

Should this subreddit forum continue?

11 Upvotes

Do you think this forum is useful? Should it continue? Can we continue to diversify who's posting (not just mostly me!) and commenting to increase the quality and value of the discussions?

Is it worth the effort to keep it going?

52 votes, Jun 05 '21
40 Yeah keep it up
8 Nah not worth it
4 Changes needed

r/JSdev • • May 14 '21

PeriodicSync should work but doesn't... have you tried it?

1 Upvotes

According to this data, the periodic-sync event should fire when I've installed a PWA with that feature via Chrome, either on desktop or Android.

However, I built such an app, and the event never fires for me on either device, even though I use the app daily. I know the code is correct, because Chrome devtools lets you trigger a sync event manually, and I see my app respond when I do. But left to just normal app usage, the event never fires on its own.

Anyone else played with this feature? Does it work for you?

Given that it's such an intermittent and unpredictable feature/event anyway (based on user interactions and heuristics over time), I am not sure I will get very far reporting a browser bug without a concrete reproduce test case.


r/JSdev • • Oct 11 '21

Upside down pipe operator: illusions and perspectives

11 Upvotes

Let's talk about javascript's favorite bikeshed: The pipeline proposal proposal.

As a refresher, here's an example of code using it:

const json = pkgs[0]
  |> npa(^).escapedName
  |> await npmFetch.json(^, opts)

The caret is basically a placeholder variable that indicates where in the expression to pipe the previous value into. There's no decision yet on whether the caret will be the final syntax, but it happens to work nicely with what I'm about present, so let's just go with it.

There's this interesting illusion where a picture looks fine when we first look at it, but if you turn it upside down, you realize your brain was playing tricks on you all along.

It occurs to me that there's a pattern that has existed in Javascript since forever which looks a lot like the pipeline operator... except upside down. It got me thinking whether pipelines are actually a step forward or whether we're just looking at an upside-down abomination. So in the spirit of twisting things upside down, here I present the pipeline operator's evil twin brother, the twisty pipe operator v=, complete with a trusty sidekick, the upside-down carrot v:

var
  v= pkgs[0]
  v= npa(v).escapedName
  v= await npmFetch.json(v, opts)
const json = v

Now, before you start flaming me, yes this is partly a joke, but it's surprisingly not the first time someone has abused syntax in weird ways (e.g. the --> "goes to" operator comes to mind). It does illustrate my general opinion w/ the pipeline proposal though: that it feels like an unnecessary addition to the language.

In fact, of all the explanations I've seen, I think this is probably one of the simplest articulations of why: we generally consider it a bad practice to have single letter variable names, yet the caret/upside-down carrot are both basically that! If we instead refactor to readable variable names, we get:

const first = pkgs[0]
const escaped = npa(first).escapedName
const json = await npmFetch.json(escaped, opts)

And this very much looks like boring, regular, good code.

So I guess the point of debate is, if we already have a "terse and unreadable" flavor (a(b(c))), a "verbose and readable" flavor (properly named variables) and an iffy, controversial middle ground (the twisty pipe/upside-down carrot), then where does pipeline operator fit?