- Nov 2020
-
github.com github.com
-
For now, using spread attributes allows you to control which attributes appear on an element. <div {...foo}> where foo is an object of attribute keys and values will add/remove attributes according to which are present and non-null.
-
- Oct 2020
-
stackoverflow.com stackoverflow.com
-
for (var member in myObject) delete myObject[member]; ...would seem to be pretty effective in cleaning the object in one line of code
But checking
hasOwnProperty
is probably better/safer idea:for (var prop in obj) { if (obj.hasOwnProperty(prop)) { delete obj[prop]; } }
-
-
www.basefactor.com www.basefactor.com
-
Ubiquity: you can also run your validation on the server side (e.g. nodejs)
-
-
github.com github.com
Tags
Annotators
URL
-
-
github.com github.com
-
Another example:
const expensiveOperation = async (value) => { // return Promise.resolve(value) // console.log('value:', value) await sleep(1000) console.log('expensiveOperation: value:', value, 'finished') return value } var expensiveOperationDebounce = debounce(expensiveOperation, 100); // for (let num of [1, 2]) { // expensiveOperationDebounce(num).then(value => { // console.log(value) // }) // } (async () => { await sleep(0 ); console.log(await expensiveOperationDebounce(1)) })(); (async () => { await sleep(200 ); console.log(await expensiveOperationDebounce(2)) })(); (async () => { await sleep(1300); console.log(await expensiveOperationDebounce(3)) })(); // setTimeout(async () => { // console.log(await expensiveOperationDebounce(3)) // }, 1300)
Outputs: 1, 2, 3
Why, if I change it to:
(async () => { await sleep(0 ); console.log(await expensiveOperationDebounce(1)) })(); (async () => { await sleep(200 ); console.log(await expensiveOperationDebounce(2)) })(); (async () => { await sleep(1100); console.log(await expensiveOperationDebounce(3)) })();
Does it only output 2, 3?
-
-
www.npmjs.com www.npmjs.com
-
most popular one by downloads
-
-
www.npmjs.com www.npmjs.comdebounce1
Tags
Annotators
URL
-
-
codesandbox.io codesandbox.io
-
-
humanwhocodes.com humanwhocodes.com
-
JavaScript is, of course, a dynamic language that allows you to add and remove objects and their members at any point in time. For many, this is precisely why they enjoy the language: there are very few constraints imposed by the language.
-
-
masteringjs.io masteringjs.io
Tags
Annotators
URL
-
-
masteringjs.io masteringjs.io
-
You can set options.params to a POJO as shown above, or to an instance of the JavaScript's built-in URLSearchParams class. const params = new URLSearchParams([['answer', 42]]); const res = await axios.get('https://httpbin.org/get', { params });
-
-
github.com github.com
-
-
In contrast, an object's actual prototype (obtained with Object.getPrototypeOf) is the real and only definition of an object's nature -- even in the possible case that its prototype has been changed after creation (either though the spec compliant Object.setPrototypeOf or by changing the commonly implemented __proto__ property).
-
-
masteringjs.io masteringjs.io
-
-
Checking if an object is a POJO can be somewhat tricky and depends on whether you consider objects created using Object.create(null) to be POJOs. The safest way is using the Object.getPrototypeOf() function and comparing the object's prototype.
-
-
-
mixing the turing complete of javascript with the markup of HTML eliminates the readability of JSX so that it is actually harder to parse than a solution like hyperscript
-
If the react cargo cult didn't have the JSX cowpath paved for them and acclimated to describing their app interface with vanilla javascript, they'd cargo cult around that. It's really about the path of least resistance and familiarity.
-
hyperscript is much simpler to refactor and DRY up your code than with JSX, because, being vanilla javascript, its easier to work with variable assignment, loops and conditionals.
-
Don't think so; template strings solve the problem JSX tries to tackle without forking the language.
Tags
- familiar syntax
- paving cow paths
- javascript: tagged template literals
- hybrid/mixture
- comparison with:
- react-hyperscript
- doing something without knowing why/how it works
- controversial
- making it easy for later refactoring
- hypothetical/alternate history
- reuse existing language constructs
- it's just plain JavaScript
- Turing complete
- forking
- JSX
- hyperscript
- JavaScript
- template language vs. reusing existing language constructs
- it's just _
- familiarity
- cargo cult
- javascript
- missing out on the benefits of something
- bad combination/mixture/hybrid/frankenstein
- UI library
- UI library: syntax
- template language: bad: by not reusing existing language constructs; forced to reinvent equivalents which are inferior and unfamiliar
- good point
- path of least resistance
- due to historical reasons
Annotators
URL
-
-
www.npmjs.com www.npmjs.comhyperx2
-
This module is similar to JSX, but provided as a standards-compliant ES6 tagged template string function.
-
tagged template string virtual dom builder
-
-
github.com github.com
-
render(html`<${Button} on:click=${() => (clicked += 1)}>Click Me!<//>`)
Compared to https://github.com/kenoxa/svelte-jsx#api, this alows on:click instead of on_click.
So maybe this syntax allows for fewer workarounds overall?
-
-
-
github.com github.com
-
svelte-htm - Hyperscript Tagged Markup for svelte; a jsx-like syntax using Tagged Templates
-
-
github.com github.com
-
My proposal is that we solve this by treating a static key prop as different from one provided through spread. I think that as a second step we might want to even give separate syntax such as:
-
-
-
by using tagged templates we can inline function calls
(below)
-
-
github.com github.com
-
Use a node-style require() to organize your browser code and load modules installed by npm.
-
-
github.com github.com
-
browserify is a tool for compiling node-flavored commonjs modules for the browser.
-
-
2ality.com 2ality.com
-
trusktr herman willems • 2 years ago Haha. Maybe React should focus on a template-string syntax and follow standards (and provide options for pre-compiling in Webpack, etc).
-
To suggest template literals cover the level of abstraction that JSX has to offer is just dumb. They're great and all, but c'mon now...
-
-
facebook.github.io facebook.github.io
-
However, this would lead to further divergence. Tooling that is built around the assumptions imposed by template literals wouldn't work. It would undermine the meaning of template literals. It would be necessary to define how JSX behaves within the rest of the ECMAScript grammar within the template literal anyway.
-
Template literals work well for long embedded DSLs. Unfortunately the syntax noise is substantial when you exit in and out of embedded arbitrary ECMAScript expressions with identifiers in scope.
-
ECMAScript 6th Edition (ECMA-262) introduces template literals which are intended to be used for embedding DSL in ECMAScript.
-
Why not Template Literals?
Tags
- javascript: tagged template literals
- divergence
- verbose/noisy
- benefiting from shared tooling that can be reused
- assumptions
- syntax noise
- developer's intention
- controversial
- substantial
- non-standard
- JSX
- why not?
- DSL
- good question
- ECMAScript standard
- design goals
- exceptions to the rule
- embedding
- good point
- intended use/purpose
- leverage the fact that tooling already exists
- undermine
Annotators
URL
-
-
gist.github.com gist.github.com
-
This is valid javascript! Or harmony or es6 or whatever, but importantly, it's not happening outside the js environment. This also allows us to use our standard tooling: the traceur compiler knows how to turn jsx`<div>Hello</div>`; into the equivalent browser compatible es3, and hence we can use anything the traceur compile accepts!
-
-
-
Think of JavaScript. In the browser you don't have direct access to the file system. In Node.js you have. Same programming language. Different APIs.
-
-
-
IMO svelte does have a responsibility to teach/demo the basics of "functional javascript" probably as a docs/tutorial/demos chapter on "the power of javascript expressions"
-
-
reactjs.org reactjs.org
-
Hooks embrace JavaScript closures and avoid introducing React-specific APIs where JavaScript already provides a solution.
-
-
github.com github.com
-
Solid supports templating in 3 forms JSX, Tagged Template Literals, and Solid's HyperScript variant.
-
JSX is an XML-like syntax extension to EcmaScript (https://facebook.github.io/jsx/).
-
-
en.wikipedia.org en.wikipedia.org
-
use universal loading to render identical HTML on both the server and client.
-
-
dmitripavlutin.com dmitripavlutin.com
Tags
Annotators
URL
-
-
stackoverflow.com stackoverflow.com
-
Node.js code must be run by the node process, not the browser (the code must run in the server).
-
-
-
use Xstate which offers a finite state machine that adheres to the SCXML specification and provides a lot of extra goodness, including visualization tools, test helpers and much more
-
-
stackoverflow.com stackoverflow.com
-
the function you pass to the find method is called a predicate. The predicate here defines a boolean outcome based on conditions defined in the function itself, so that the find method can determine which value to find.
-
-
github.com github.com
-
perhaps, imo this would make more sense. but it would slow down Parcel significantly as packages who don't have a browserslist or something similar will all get compiled (and most packages actually do target commonjs, which makes this prob not such a good idea). Which unfortunately is way too many packages. It would be great if tools like babel actually enforced a similar pattern to Parcel and use browserlist file or package.json instead of allowing defining target env in babel. Or at least not encourage it.
-
- Sep 2020
-
github.com github.com
-
I forgot to mention in the original issue way back that I have a lot of data. Like 1 to 3 MB that is being passed around via export let foo.
-
-
sapper.svelte.dev sapper.svelte.dev
-
But we face our own hostile environment: underpowered devices, poor network connections, and the complexity inherent in front-end engineering.
-
-
stackoverflow.com stackoverflow.com
-
Your problem is that you were returning the rejected loginDaoCall, not the promise where the error was already handled. loginApi.login(user, password) did indeed return a rejected promise, and even while that was handled in another branch, the promise returned by the further .then() does also get rejected and was not handled.
-
// LoginApi.js return loginDao.login(username, password).then(function (res) { store.dispatch(loginSuccess()); log.log("[loginApi.login] END"); return true; }, function (err) { store.dispatch(loginFail()); errorUtils.dispatchErrorWithTimeout(errorLogin); log.log(err); return false; }); // never supposed to reject
-
-
javascript.info javascript.info
-
The "invisible try..catch" around the executor automatically catches the error and turns it into rejected promise.
-
-
stackoverflow.com stackoverflow.com
-
This treatment of thenables allows promise implementations to interoperate, as long as they expose a Promises/A+-compliant then method. It also allows Promises/A+ implementations to “assimilate” nonconformant implementations with reasonable then methods.
-
the promise specification explicitly does not make a distinction
-
-
final-form.org final-form.org
-
I love how they have this example with plain JS to show how slim and simple it can be even when not using react and react-final-form. It demystifies things so you can see how it works and how it would be if not using React (which in turn helps you appreciate what react/react-final-form do for you).
-
-
rollupjs.org rollupjs.orgRollup2
-
If you need to call the function repeatedly, this is much, much faster than using eval.
-
Some modules, like events or util, are built in to Node.js. If you want to include those (for example, so that your bundle runs in the browser), you may need to include rollup-plugin-node-polyfills.
-
-
discuss.rubyonrails.org discuss.rubyonrails.org
-
Getting the JS infrastructure upgraded can take hours of Googling.
-
-
medium.com medium.com
-
Modules using code that doesn’t exist in browsers such as process.env.NODE_ENV and forcing you to convert or polyfill it.
-
-
engineering.mixmax.com engineering.mixmax.com
-
If you've followed React's guide, you've installed react from npm. You can teach Rollup how to find this package within your project's node_modules directory using the rollup-plugin-node-resolve plugin. Since React exports a CommonJS module, you'll also need to convert that into an ES6 module using the rollup-plugin-commonjs plugin.
-
-
github.com github.com
-
This isn't really a bug, because if you have an async function that returns a function, it doesn't really return a function - it returns a promise. I don't remember whether the Svelte internals currently check for the onMount callback's return being a function or whether they check for it being truthy. Maybe there's some adjustment to be made there.
-
-
github.com github.com
-
The lack of spread continues to be a big pain for me, adding lots of difficult-to-maintain cruft in my components. Having to maintain a list of all possible attributes that I might ever need to pass through a component is causing me a lot of friction in my most composable components.
-
-
final-form.org final-form.org
-
By default, in order to allow inline fat-arrow validation functions, the field will not rerender if you change your validation function to an alternate function that has a different behavior. If you need your field to rerender with a new validation function, you will need to update another prop on the Field, such as key
-
-
stackoverflow.com stackoverflow.com
-
function* enumerate(iterable) { let i = 0; for (const x of iterable) { yield [i, x]; i++; } } for (const [i, obj] of enumerate(myArray)) { console.log(i, obj); }
-
for (let [index, val] of array.entries())
-
Note that Array.entries() returns an iterator, which is what allows it to work in the for-of loop; don't confuse this with Object.entries(), which returns an array of key-value pairs.
-
Object.keys(obj).forEach could work, but it only includes own properties; for…in includes enumerable properties anywhere on the prototype chain.
-
-
developer.mozilla.org developer.mozilla.org
-
react-spectrum.adobe.com react-spectrum.adobe.com
-
www.coreycleary.me www.coreycleary.me
-
-
The error callback becomes a reject, while the "happy path" callback becomes a resolve.
-
-
developer.mozilla.org developer.mozilla.org
-
Here we store the three Promise objects in variables, which has the effect of setting off their associated processes all running simultaneously. Next, we await their results — because the promises all started processing at essentially the same time, the promises will all fulfill at the same time
-
-
adamloving.com adamloving.com
-
The “shared” schema is effectively the API schema. These are the fields exchanged in the API, common to client and server.
-
-
-
.catch(error => download_count = error) // check for error in template
-
Making the value change to a Promise for the duration would be more fitting for many uses.
-
-
developer.mozilla.org developer.mozilla.org
-
Migrating the stores to TypeScript
-
-
svelte.dev svelte.dev
-
The value attribute of an input element or its children option elements must not be set with spread attributes when using bind:group or bind:checked. Svelte needs to be able to see the element's value directly in the markup in these cases so that it can link it to the bound variable.
Tags
Annotators
URL
-
-
developer.mozilla.org developer.mozilla.org
-
Rest syntax looks exactly like spread syntax. In a way, rest syntax is the opposite of spread syntax. Spread syntax "expands" an array into its elements, while rest syntax collects multiple elements and "condenses" them into a single element.
-
-
github.com github.com
-
One of the arguments that's frequently deployed in favour of JSX-based frameworks over template-based ones is that JSX allows you to use existing language constructs:
-
-
github.com github.com
-
But what all frameworks have in common is to write JS and this could convince users of React but also newcomers that know JS.
-
-
reactjs.org reactjs.org
-
functions present a problem again because there is no reliable way to compare two functions to see if they are semantically equivalent.
-
-
stackoverflow.com stackoverflow.com
-
React is an isomorphic/universal framework. That means that there is a virtual representation of the UI component tree, and that is separate from the actual rendering that it outputs in the browser.
-
-
github.com github.com
-
Note that to use the this context the test function must be a function expression (function test(value) {}), not an arrow function, since arrow functions have lexical context.
Tags
Annotators
URL
-
-
-
Now only the defined subpath in "exports" can be imported by a consumer:
Tags
Annotators
URL
-
-
exploringjs.com exploringjs.com
-
Even though it works much like a function, import() is an operator
-
The module specifier is always fixed. That is, you can’t change what you import depending on a condition. And you can’t assemble a specifier dynamically.
-
Ways of delivering JavaScript source code
-
-
github.com github.com
-
-
many organizations have been burned by the high churn in JavaScript tooling, which sadly moves projects backwards as a part of moving the web forward
-
-
daveceddia.com daveceddia.com
-
This is what I love about React, it's JavaScript basically, not a DSL
-
- Aug 2020
-
www.alec.fyi www.alec.fyi
-
find every email on a web page that you're on. The big kahuna - this works for every website. Inject it into a site with Chrome DevTools (more here)
Use this code below to find every e-mail on a webpage:
var elems = document.body.getElementsByTagName("*"); var re = new RegExp("(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"); for (var i = 0; i < elems.length; i++) { if (re.test(elems[i].innerHTML)) { console.log(elems[i].innerHTML); } }
-
-
svelte.dev svelte.dev
-
count_value
going against the grain? or ?
-
- Jul 2020
-
github.com github.com
-
But I'll definitely take underscore mixins over extending String.prototype or other clunky implementations any day.
-
-
amp.dev amp.dev
-
If you can, use AMP like any other JavaScript library to build your site and forget about the canonical linking. Using AMP to build a whole website dramatically reduces your maintenance burden.
-
-
github.com github.com
-
developer.mozilla.org developer.mozilla.org
-
the umbrella term "JavaScript" as understood in a web browser context contains several very different elements. One of them is the core language (ECMAScript), another is the collection of the Web APIs, including the DOM (Document Object Model)
-
-
legacy.reactjs.org legacy.reactjs.org
-
a syntax extension to JavaScript
Tags
Annotators
URL
-
-
developer.mozilla.org developer.mozilla.org
-
name provided to a function expression as above is only available to the function's own scope
-
supports functional programming — because they are objects, functions may be stored in variables and passed around like any other object
-
most common host environment is the browser, but JavaScript interpreters can also be found in a huge list of other places
-
-
docdrop.org docdrop.org
-
Made analogy with internal combustion engine, which has 1000s of parts, with the "radical simplicity" approach taken by Tesla: they use an electric motor, which only has 2 components!
comparison: Sapper vs. Gatsby
-
- Jun 2020
-
stackoverflow.com stackoverflow.com
-
What would be nice is if JavaScript had a built-in way to do what I can do in Ruby with:
> I18n.interpolate('Hi, %{name}', name: 'Fred') => "Hi, Fred"
But to be fair, I18n comes from i18n library, so JS could just as easily (and I'm sure does) have a library that does the same thing.
Update: Actually, you can do this in plain Ruby (so why do we even need
I18n.interpolate
?):main > "Hi, %{name}" % {name: 'Fred'} => "Hi, Fred"
main > ? String#% From: string.c (C Method): Owner: String Visibility: public Signature: %(arg1) Number of lines: 9 Format---Uses str as a format specification, and returns the result of applying it to arg. If the format specification contains more than one substitution, then arg must be an Array or Hash containing the values to be substituted. See Kernel::sprintf for details of the format string. "%05d" % 123 #=> "00123" "%-5s: %016x" % [ "ID", self.object_id ] #=> "ID : 00002b054ec93168" "foo = %{foo}" % { :foo => 'bar' } #=> "foo = bar"
I guess that built-in version is fine for simple cases. You only need to use
I18n.translate
if you need its more advanced features likeI18n.config.missing_interpolation_argument_handler
. -
When you hear there's something called "template strings" coming to JavaScript, it's natural to assume it's a built-in template library, like Mustache. It isn't. It's mainly just string interpolation and multiline strings for JS. I think this is going to be a common misconception for a while, though.
-
-
-
HTML templates
-
No built-in syntax for looping
-
Multi-lines strings and indented strings
-
- May 2020
-
localforage.github.io localforage.github.io
-
localForage is a JavaScript library that improves the offline experience of your web app by using an asynchronous data store with a simple, localStorage-like API. It allows developers to store many types of data instead of just strings.
-
-
github.com github.com
-
This starter takes advantage of Typescript and Emotion. This is a personal choice, and I'd encourage you to give it a shot. If you're interested in using plain ES6 and regular scss styling, see release v1 of this library.
-
-
nitayneeman.com nitayneeman.com
-
developer.mozilla.org developer.mozilla.org
-
www.sitepoint.com www.sitepoint.com
-
There’s no need for nasty repetition in ES6!… // ES6 code const a = 1, b = 2, c = 3; obj = { a b c }; // obj.a = 1, obj.b = 2, obj.c = 3
ES6 way of creating an object from variables .
-
// ES5-compatible code var myObject = { prop1: 'hello', prop2: 'world', output: function() { console.log(this.prop1 + ' ' + this.prop2); } }; myObject.output(); // hello world
Creating an object.
-
-
developer.mozilla.org developer.mozilla.orgPromise4
-
The promises of a chain are nested like Russian dolls, but get popped like the top of a stack.
-
Similarly, .catch() is really just a .then() without a slot for handleFulfilled.
-
in the absence of an immediate need, it is simpler to leave out error handling until a final .catch() statement.
-
Handling a rejected promise too early has consequences further down the promise chain. Sometimes there is no choice, because an error must be handled immediately.
-
-
github.com github.com
-
Mozilla does not permit extensions distributed through https://addons.mozilla.org/ to load external scripts. Mozilla does allow extensions to be externally distributed, but https://addons.mozilla.org/ is how most people discover extensions. The are still concerns: Google and Microsoft do not grant permission for others to distribute their "widget" scripts. Google's and Microsoft's "widget" scripts are minified. This prevents Mozilla's reviewers from being able to easily evaluate the code that is being distributed. Mozilla can reject an extension for this. Even if an extension author self-distributes, Mozilla can request the source code for the extension and halt its distribution for the same reason.
Maybe not technically a catch-22/chicken-and-egg problem, but what is a better name for this logical/dependency problem?
-
-
muldoon.cloud muldoon.cloud
-
Now, a couple of years later, my guidelines for JS are:
Advices on using JavaScript from a long time programmer:
- Use TypeScript instead.
- Push as much logic to the server as possible
- Use a framework like Vue or React if you need front interactivity
- Don't skip unit tests
-
- Apr 2020
-
-
In Python, when trying to do a dubious operation, you get an error pretty soon. In JavaScript… an undefined can fly through a few layers of abstraction, causing an error in a seemingly unrelated piece of code.
Undefined nature of JavaScript can hide an error for a long time. For example,
function add(a,b) { return + (a + b) } add(2,2) add('2', 2)
will result in a number, but is it the same one?
-
I found that the overhead to use types in TypeScript is minimal (if any).
In TypeScript, unlike in JS we need to specify the types:
-
ESLint does automatic code linting
ESLint <--- pluggable JS linter:
- mark things that are incorrect,
- mark things that are unnecessary or risky (e.g.
if (x = 5) { ... })
- set a standard way of writing code
-
Write a new test and the result. If you want to make it REPL-like, instead of writing console.log(x.toString()) use expect(x.toString()).toBe('') and you will directly get the result.
jest <--- interactive JavaScript (TypeScript and others too) testing framework. You can use it as a VS Code extension.
Basically, instead of
console.log(x.toString())
, you can useexcept(x.toString()).toBe('')
. Check this gif to understand it further -
I recommend Airbnb style JavaScript style guide and Airbnb TypeScript)
Recommended style guides from Airbnb for:
-
-
github.com github.com
-
-
zxcvbn works identically on the server
-
-
medium.com medium.com
-
The “universal” label that has been slapped on to it is superfluous, but it does have its merits. Now that we have a commonly known term to refer to environment agnostic JavaScript code, it allows library authors to list it as a feature and be fashionable doing it. I’m happy with the term “universal” being fashionable because it makes developers think about their dependencies on the runtime environment. In the end this will help the JavaScript ecosystem mature and allow libraries to be used everywhere.
-
The “universal” label that has been slapped on to it is superfluous
-
Running the same code in the browser and on the server in order to avoid code duplication is a very different problem. It is simply a matter of good development practices to avoid code duplication. This however is not limited to isomorphic applications. A utility library such as Lodash is “universal”, but has nothing to do with isomorphism. Sharing code between environments does not give you an isomorphic application. What we’re referring to with Universal JavaScript is simply the fact that it is JavaScript code which is environment agnostic. It can run anywhere. In fact most JavaScript code will run fine on any JavaScript platform.
-
Isomorphism itself is not purely a JavaScript thing. You can also build an isomorphic application in Dart or even use two different languages/stacks to render the same result. In fact there are many “isomorphic” applications which render a full HTML document on the server using PHP, Java or Ruby and use JavaScript and AJAX to create a rich user experience in the browser. This was the way things were done before the rise of Single Page Applications. The only real reason isomorphism is tied to JavaScript is because it’s the only language widely supported in the browser, and so at least part of the whole thing will use JavaScript. There’s no such thing as Isomorphic JavaScript, only isomorphic applications.
-
-
-
cdb.reacttraining.com cdb.reacttraining.com
-
en.wikipedia.org en.wikipedia.org
-
2ality.com 2ality.com
-
Maybe we should distinguish between: The technique of asssembling pages on either client or server. Here, “isomorphic” and “full stack” (as proposed by Rodrigo Medeiros) seem good choices. JavaScript that runs in all (or most) JavaScript environments, especially browsers and Node.js. Here, “universal” seems a good choice.
-
-
-
-
Let's reason through our memoizer before we write any code.
Operations performed by a memoizer:
- Takes a reference to a function as an input
- Returns a function (so it can be used as it normally would be)
- Creates a cache of some sort to hold the results of previous function calls
- Any future time calling the function, returns a cached result if it exists
- If the cached value doesn't exist, calls the function and store that result in the cache
Which is written as:
// Takes a reference to a function const memoize = func => { // Creates a cache of results const results = {}; // Returns a function return (...args) => { // Create a key for results cache const argsKey = JSON.stringify(args); // Only execute func if no cached value if (!results[argsKey]) { // Store function call result in cache results[argsKey] = func(...args); } // Return cached value return results[argsKey]; }; };
-
Let's replicate our inefficientSquare example, but this time we'll use our memoizer to cache results.
Replication of a function with the use of memoizer (check the code below this annotation)
-
The biggest problem with JSON.stringify is that it doesn't serialize certain inputs, like functions and Symbols (and anything you wouldn't find in JSON).
Problem with
JSON.stringify
.This is why the previous code shouldn't be used in production
Tags
Annotators
URL
-
-
-
Frontend Devs: What should I learn after JavaScript? Explore these frameworks and libraries
Most paid JS frameworks and libraries:
-
-
-
Use camelCase when naming objects, functions, and instances.
camelCase for objects, functions and instances
const thisIsMyFuction() {}
-
Use PascalCase only when naming constructors or classes.
PascalCase for constructors and classes
// good class User { constructor(options) { this.name = options.name; } } const good = new User({ name: 'yup', });
-
Use uppercase only in constants.
Uppercase for constants
export const API_KEY = 'SOMEKEY';
-
-
medium.com medium.com
-
What is a Function Expression?A JavaScript function can also be defined using an expression.A function expression can be stored in a variable:var x = function (a, b) {return a * b};After a function expression has been stored in a variable, the variable can be used as a function. Functions stored in variables do not need function names. They are always invoked (called) using the variable name.
Test question: What is function expression?
-
-
codeburst.io codeburst.io
-
Writing an async function is quite simple. You just need to add the async keyword prior to function:
Test question: What is the syntax of async function?
-
-
codeburst.io codeburst.io
-
Our Promise can have one of three states:
Testing question: what are the states of a promise?
-
-
javascript.info javascript.info
-
Using objects as keys is one of most notable and important Map features.
Test question: What is one of the most notable and important Map features?
-
Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.
Test question: What is the difference between Map and Object in JavaScript?
Tags
Annotators
URL
-
-
javascript.info javascript.infoFetch1
-
he basic syntax is: let promise = fetch(url, [options])
Test question: What s the basic syntax of fetch(); ?
Tags
Annotators
URL
-
-
www.taniarascia.com www.taniarascia.com
-
Metadata::
- Author:: Tania Rascia
- Article:: How to Use the JavaScript Fetch API to Get JSON Data
- URL:: How to Use the JavaScript Fetch API to Get JSON Data – Tania Rascia
-
-
levelup.gitconnected.com levelup.gitconnected.com
-
Here are the possible ways to make an API call:XMLHttpRequestfetchAxiosjQuery
Test question: What are 4 ways to make an api call?
-
-
blog.appsignal.com blog.appsignal.com
-
200 megabytes is not that bad. I’ve seen it rise above 700 MB easily.
200M已经不算算,升到700M都很容易。
-
-
developer.mozilla.org developer.mozilla.org
-
click
In javascript used instead of onclick in html.
-
-
www.w3schools.com www.w3schools.com
-
document.addEventListener("click", myFunction);function myFunction() { document.getElementById("demo").innerHTML = "Hello World"; }
document.addEventListener() - Reference to the external function.
-
document.addEventListener(event, function, useCapture)
Test question: What is the syntax of element.addEventListener() ?
-
-
www.tutorialspoint.com www.tutorialspoint.com
-
JSON syntax is basically considered as a subset of JavaScript syntax;
Test question: What is JSON syntax part of?
-
-
developer.mozilla.org developer.mozilla.orgeval()1
-
Never use eval()! eval() is a dangerous function, which executes the code it's passed with the privileges of the caller.
Testing question: Should you ever use eval()?
-
-
github.com github.com
-
github.com github.com
-
find src -name '*.js' -print | xargs jscodeshift -t node_modules/@material-ui/codemod/lib/v4.0.0/top-level-imports.js
-
-
github.com github.com
-
www.cnblogs.com www.cnblogs.com
-
对象属性的命名规则 通过[]操作符为对象添加属性时,属性名称可以是任何字符串(包括只包含空格的字符串和空字符串); 通过.操作符为对象添加属性时,属性名称必须是合法的标识符名称; 如果属性名包含非法的标识符字符,则只能采用obj[“propertyName”]的形式; 如果属性名是合法的标识符,读取时即可以采用obj.propertyName,也可以采用obj[“propertyName”]的形式;
除此之外,根据下面的介绍,也可以用数字和布尔值作为属性名,但会自动转换为字符串。
Tags
Annotators
URL
-
-
medium.com medium.com
-
We really only need to test that the button gets rendered at all (we don’t care about what the label says — it may say different things in different languages, depending on user locale settings). We do want to make sure that the correct number of clicks gets displayed
An example of how to think about tests. Also asserting against text that's variable isn't very useful.
-
It’s still a good idea to keep your code in three different buckets, and keep these buckets isolated from each other:Display/UI ComponentsProgram logic/business rules — the stuff that deals with the problem you’re solving for the user.Side effects (I/O, network, disk, etc.)
How do I organize my code like this? What's the directory structure look like.
-
-
medium.com medium.com
-
I love that type annotations can be optional
How is TypeScript optional
-
-
stackoverflow.com stackoverflow.com
-
Any JavaScript style guide that is up-to-date for ES6 is going to cover nearly all TypeScript constructs except for type annotations, so I would start with your favorite JS style and decide on what you want the rules for type annotations to be
可惜这个问题被关了。因此显得有点老。不过他的建议也不错。使用用JS的风格。
-
-
microbit.org microbit.org
-
You can also switch to JavaScript to see the text-based code behind the blocks.
-
- Mar 2020
-
www.runoob.com www.runoob.com
-
Online javascript editor
-
-
-
How do you leverage browser cache when Google’s very own Analytics.js has it’s expiry time set to 2 hours? How do you minimize DNS requests when Google advices you to copy their tracking code, linking to an externally hosted Javascript file?If that isn’t bad enough already, Google’s advice is to avoid hosting the JavaScript file locally. And why? To ensure you get access to new features and product updates.
-
Why should I host analytics.js locally?The Complete Analytics Optimization Suite for WordPress gives you the best of both worlds. After activation it automagically downloads the latest version of analytics.js from Google’s servers, places the necessary tracking code in your WordPress theme’s header and keeps the local Javascript file up-to-date using an adjusted version of Matthew Horne’s update analytics script and wp_cron(). This way you can minimize DNS requests, leverage browser cache, track your visitors and still follow Google’s recommendation to use the latest features and product updates.
-
-
paramaggarwal.substack.com paramaggarwal.substack.com
-
Javascript, APIs and Markup — this stack is all about finding middleground from the chaos of SSR+SPA. It is about stepping back and asking yourself, what parts of my page change and what parts don’t change?
JavaScript, APIs and Markup (JAM Stack) - middleground between SSR + SPA.
Advantages:
- The parts that don’t change often are pre-rendered on the server and saved to static HTML files. Anything else is implemented in JS and run on the client using API calls.
- Avoids too much data transfer (like the hydration data for SSR), therefore finds a good tradeoff to ship web content
- Allows to leverage the power and cost of Content delivery networks (CDNs) to effectively serve your content
- With serverless apps your APIs will never need a server to SSH into and manage
-
-
-
TL;DR;
Don't use:
- No global vars.
- Declare variables using "var".
- Declare functions using "function" keyword.
- Avoid use "for" in loops.
- Array push, inmutability.
- Class.
- Use delete to remove a object atribute.
- Avoid nested if.
- else if.
- Heavy nesting.
- Avoid to add prototype to functions that could be used in a module.
Use:
- Common code in functions, follow D.R.Y principle.
- Shorcut notation.
- Spread operator over Object.assign (airbnb 3.8).
- Pascal case naming.
- Modularize your code in modules.
- const and let!.
- Literal syntax for object creation (airbnb 3.1).
- Computed property names when creating objects (airbnb 3.2).
- Property value shorthand (airbnb 3.4).
- Group your shorthand properties at the beginning of your objec (airbnb 3.5).
- use the literal syntax for array creation (airnbnb 4.1).
- Use array spreads ... to copy arrays. (airbnb 4.3).
- use spreads ... instead of, Array.from. (airbnb 4.4).
- Use return statements in array method callbacks (airbnb 4.7).
-
Don’t use iterators, prefer js higher-order functions instead of for / for..in
// bad const increasedByOne = []; for (let i = 0; i < numbers.length; i++) { increasedByOne.push(numbers[i] + 1); } // good const increasedByOne = []; numbers.forEach((num) => { increasedByOne.push(num + 1); });
-
Ternaries should not be nested and generally be single line expressions.
e.g.
const foo = maybe1 > maybe2 ? 'bar' : maybeNull;
Also:
// bad const foo = a ? a : b; const bar = c ? true : false; const baz = c ? false : true; // good const foo = a || b; const bar = !!c; const baz = !c;
-
Use === and !== over == and !=.
Bases on the Airbnb guide
-
Use JSDOC https://jsdoc.app/about-getting-started.html format.
Standardise your JavaScript comments:
- Use block comment
/** This is a description of the foo function. */ function foo() { }
- Use JSDOC tag to describe a function: ```javascript /**
- Represents a book.
- @constructor
- @param {string} title - The title of the book.
- @param {string} author - The author of the book. */ function Book(title, author) { } ```
- Use block comment
-
When JavaScript encounters a line break without a semicolon, it uses a set of rules called Automatic Semicolon Insertion to determine whether or not it should regard that line break as the end of a statement, and (as the name implies) place a semicolon into your code before the line break if it thinks so. ASI contains a few eccentric behaviors, though, and your code will break if JavaScript misinterprets your line break.
Better place a semicolon (;) in the right place and do not rely on the Automatic Semicolon Insertion
e.g.
const luke = {}; const leia = {}; [luke, leia].forEach((jedi) => { jedi.father = 'vader'; });
```
-
-
developer.wordpress.org developer.wordpress.org
-
WordPress 5.0 introduced the wp-i18n JavaScript package that provides the functions needed to add translatable strings as you would in PHP.
-
-
-
The combination of WordPress, React, Gatsby and GraphQL is just that - fun
Intriguing combination of technologies.
Keep an eye on the post author, who is going to discuss the technologies in the next writings
-
-
www.danielworsnup.com www.danielworsnup.com
-
map, filter and reduce can all operate independently, or be chained together
-
During each loop of reduce, you can get result of the last loop, and the next element in the array Change the result, then return it for the next loop iteration When you're done, you have the completed collection
reduce
-
This lets you transform each element into something new (or keep it the same) Types don't have to be the same: can return objects, string, numbers - anything!
map
-
It loops over the elements, passing each one to a callback function You can return true to include that element in the new array, or false to exclude it
filter
-
So why are map, filter and reduce useful?
Advantages of
map
,filter
,reduce
:- don't have to manually loop over array
- chain together for short, straightforward array transformations
- can reuse callback functions and compose them together
-
- Feb 2020
-
github.com github.com
-
-
docs.k6.io docs.k6.iok6/http1
-
k6 does not run in Node.js because it would perform poorly while running larger tests.Javascript is not generally well suited for high performance. It's a Go program - to achieve maximum performance - embedding a JavaScript runtime for running tests written in JavaScript.
Tags
Annotators
URL
-
- Jan 2020
-
inlehmansterms.net inlehmansterms.net
-
stackoverflow.com stackoverflow.com
-
[...nodelist] will make an array of out of an object if the object is iterable. Array.from(nodelist) will make an array out of an object if the object is iterable or if the object is array-like (has .length and numeric props)
-
- Dec 2019
-
www.freecodecamp.org www.freecodecamp.org
-
scripts are plenty powerful and often easier to live with.
-
-
github.com github.com
-
Neutrino only babel-compiles first party source (the JSX -> JS transformation is handled by a babel plugin). It does this because even when using the module entry in package.json, it's expected that the provided file (and it's imports) still be JS and not in some other format - ie: the only difference from the content in main should be that it can use modules syntax (that is import and export rather than require etc).
module
version compared tomain
version:only difference from the content in main should be that it can use modules syntax (that is import and export rather than require etc).
You can see the difference in this example: https://unpkg.com/browse/reactstrap@8.0.1/es/Alert.js ("module": "es/index.js": import) vs. https://unpkg.com/browse/reactstrap@8.0.1/lib/Alert.js ("main": "lib/index.js": require)
-
-
github.com github.com
-
One thing that matters is if code uses browser-specific (example: Dom) or server-specific (example: filesystem) features.
-
-
2ality.com 2ality.com
-
esnext: source code using stage 4 features (or older), not transpiled, in ES modules. main continues to be used the same way. Its code can be generated from the untranspiled code. Most module use cases should be handleable via esnext. browser can be handled via an extended version of esnext (see next section).
-