1565076222
Most production applications have at least a few "business rules" (and often times, very many). Enforcing these rules in a client-side application can be challenging and somewhat tedious. I'd like to present one way to enforce such rules using JS getters and setters.
To demonstrate this idea, I created a very simple application that revolves around "special rectangles" (I just made this phrase up). In this case, a "special rectangle" is a rectangle that always has the same perimeter (or, distance around the outside of it). So if the width of the rectangle increases, the height has to shrink accordingly. Check out the embed above to get a feel for how the rectangle will behave.
Getters and Setters (a.k.a. "Accessors") allow us to define custom object property behaviors.
MDN defines a "getter" in the following way:
The get
syntax binds an object property to a function that will be called when that property is looked up.
Basically, this allows you to make a "custom" readable property on an object. Here's a really simple example:
const obj = { x: 7, // Double the value of x get doubleX() { return 2*this.x; } };console.log(obj.doubleX); // -> 14
obj.x = 12.3;
console.log(obj.doubleX); // -> 23.6
Getters allow us to create “computed” properties with ease. This is wonderful - anytime you update obj.x
in the example above, obj.doubleX
will be “updated” accordingly - and you never have to do the manual updating.
NOTE: getters only affect accessing a property. That is, we can read obj.doubleX
, but at the moment, trying to set this property’s value will not work as you might expect.
MDN defines a setter in the following way:
The set syntax binds an object property to a function to be called when there is an attempt to set that property.
Now, instead of providing behavior for when a property is being read, we provide behavior for when a property is being set. Let’s adjust our previous example:
const obj = {
x: 7,// Double the value of x
get doubleX() {
return 2*this.x;
},// Setting doubleX: x will be half of the value
set doubleX(val) {
this.x = val/2;
}
};console.log(obj.doubleX); // -> 14
obj.doubleX = 70;
console.log(obj.x); // -> 35
This is really cool stuff! We can create custom properties without having to keep track of excessive amounts of values. This is great for adding custom/computed properties, but it’s also great for enforcing business rules!
I like to enforce business rules within setters. That way you can write your rules once, and then just set properties like you normally would. Let’s check out an example.
Before we start writing code, let’s make sure we understand our problem space. We want to make a rectangle that has a fixed perimeter, and as the width or height of the rectangle changes - the other dimension will change accordingly. Keep in mind that for any rectangle,
(2 * width) + (2 * height) = perimeter
For reference, here’s a diagram representing how the width, height, and perimeter of a rectangle are related.
If we take away the two “width” sides of the rectangle, it leaves us with the two “height” sides. So one “height” side is the perimeter minus two “widths”:
height = (perimeter - (2 * width)) / 2
The same goes for the width:
width = (perimeter - (2 * height)) / 2
If we change the width of the rectangle, we need to adjust the height using the first rule above. If we change the height, we set the width using the second rule.
We’re going to create an ES6 class to apply our new tools and enforce our rules. If you’re not familiar with classes in ES6, check out MDN’s guide on them. We’ll start a file named SpecialRectangle.class.js
to hold this Special Rectangle class.
// Create class
export default class SpecialRectangle {}
For this example, we’ll instantiate a SpecialRectangle instance with a perimeter that we want to use as the fixed perimeter of the rectangle, and an initial width. If we know the width, we can determine the corresponding height. Let’s do that now.
// Create class
export default class SpecialRectangle {
// Constructor
constructor(perimeter, width) {
// Set the perimeter and width
this.perimeter = perimeter;
this.width = width;
// Set the height using the perimeter and width
this.height = (this.perimeter - 2*this.width)/2;
}
}
Whenever we set the width of the rectangle, we’ll update the height accordingly, so let’s abstract this out to a method and use it in our constructor.
// Create class
export default class SpecialRectangle {
// Constructor
constructor(perimeter, width) {
// Set the perimeter and width
this.perimeter = perimeter;
// Set the width (which will update the height)
this.setWidth(width);
}// Set width
setWidth(val) {
this.width = width;
// Set the height using the perimeter and width
this.height = (this.perimeter - 2this.width)/2;
}
}
Now, let’s use getters and setters within our class definition so that we can get/set our width and automatically have these rules enforced. Since we already have a width
property, we’ll create a new property named _width
that will “wrap” around the actual width
property. There’s nothing special about the name _width
, call it whatever you’d like.
// Create class
export default class SpecialRectangle {
// Constructor
constructor(perimeter, width) {/ … */}// Set width
setWidth(val) {/* … */}// Get/set the width. Use the helper method we already defined.
get _width() {
return this.width;
}
set _width(val) {
this.setWidth(val);
}
}
Now we can access and “bind to” the _width
property of any SpecialRectangle
instances and automatically have our rules enforced! We can extend this to the height property as well - the logic is just about the same:
// Create class
export default class SpecialRectangle {
// Constructor
constructor(perimeter, width) {/* … */}// Set width
setWidth(val) {/* … */}// Set the height
setHeight(val) {
this.height = val;
this.width = (this.perimeter - 2*this.height)/2;
}// Get/set the width. Use the helper method we already defined.
get _width() {/* … /}
set _width(val) {/ … */}// Get/set the width. Use the helper method we already defined.
get _height() {
return this.height;
}
set _height(val) {
this.setHeight(val);
}
}
Alright, this handles the base logic for this class! Now we can use it to create “special rectangles”. Here’s a simple example:
// Import SpecialRectangle class// Create rectangle with 600 unit perimeter, initial width of 75 units.
const rect = new SpecialRectangle(600, 75);// Let’s set the width
rect._width = 200;
console.log(rect._height); // -> 100
The width and height of our rectangle should never be less than 0, and either dimension can be at most half of the total perimeter. Rules like this are very common when doing computations, and therefor I almost always create a utility function that will add “bumpers” to a number - so we never go below a minimum, or above a maximum.
Here’s an example of such a function:
// Utility function
const keepBetween = (x, min, max) => {
if (min !== null && x < min) return min;
if (max !== null && x > max) return max;
return x;
};
The logic here is pretty simple: just don’t allow x
to be less than min
or more than max
. If x
is between min
and max
, we use the value of x
.
We can use this function when setting values (or even accessing values!) to make sure we don’t do mathematically naughty things (like set the width of a rectangle to a negative number). If we factor this into our SpecialRectangle
class, it might look like the following:
/**
/**
“SpecialRectangle” class
// Set the width
this.setWidth(width);
}
/**
// Width is half of what we have left after removing two "lengths" from the perimeter
this.height = keepBetween(
(this.perimeter - 2 * this.width) / 2,
0,
this.perimeter / 2
);
}
/**
// Length is half of what we have left after removing two "lengths" from the perimeter
this.width = keepBetween(
(this.perimeter - 2 * this.height) / 2,
0,
this.perimeter / 2
);
}
/**
/**
Let’s create a really simple user interface using Vue.JS to showcase our new class. We’ll create a single component with the following JS:
import SpecialRectangle from “@/assets/SpecialRectangle.class”;export default {
name: “App”,data: () => ({
rect: new SpecialRectangle(100, 10)
})
};
All we’re doing is creating an instance of our SpecialRectangle
class that we’ll use in our template/markup. Since we have getters and setters for the _width
and _height
properties of our SpecialRectangle
instance, we can use Vue’s v-model
directive to bind right to these properties. For example, we can create a slider to control the width of our rectangle:
<input
name=“length”
type=“range”
:min=“0”
:max=“rect.perimeter/2”
step=“0.1”
v-model=“rect._width”
>
The full code is shown in the embed below. Try using the sliders in the result to see it in action!
With this method, we can push our business rules into class definitions. This keeps our Vue logic clean, and allows us to re-use these rules over and over again!
If you’ve got a big application with a lot of business/data rules, moving your logic out of your UI components and into class definitions (using getters and setters) can keep your codebase cleaner, and make these rules re-usable.
#javascript #vue-js #web-development
1632537859
Not babashka. Node.js babashka!?
Ad-hoc CLJS scripting on Node.js.
Experimental. Please report issues here.
Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.
Additional goals and features are:
Nbb requires Node.js v12 or newer.
CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).
Install nbb
from NPM:
$ npm install nbb -g
Omit -g
for a local install.
Try out an expression:
$ nbb -e '(+ 1 2 3)'
6
And then install some other NPM libraries to use in the script. E.g.:
$ npm install csv-parse shelljs zx
Create a script which uses the NPM libraries:
(ns script
(:require ["csv-parse/lib/sync$default" :as csv-parse]
["fs" :as fs]
["path" :as path]
["shelljs$default" :as sh]
["term-size$default" :as term-size]
["zx$default" :as zx]
["zx$fs" :as zxfs]
[nbb.core :refer [*file*]]))
(prn (path/resolve "."))
(prn (term-size))
(println (count (str (fs/readFileSync *file*))))
(prn (sh/ls "."))
(prn (csv-parse "foo,bar"))
(prn (zxfs/existsSync *file*))
(zx/$ #js ["ls"])
Call the script:
$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs
Nbb has first class support for macros: you can define them right inside your .cljs
file, like you are used to from JVM Clojure. Consider the plet
macro to make working with promises more palatable:
(defmacro plet
[bindings & body]
(let [binding-pairs (reverse (partition 2 bindings))
body (cons 'do body)]
(reduce (fn [body [sym expr]]
(let [expr (list '.resolve 'js/Promise expr)]
(list '.then expr (list 'clojure.core/fn (vector sym)
body))))
body
binding-pairs)))
Using this macro we can look async code more like sync code. Consider this puppeteer example:
(-> (.launch puppeteer)
(.then (fn [browser]
(-> (.newPage browser)
(.then (fn [page]
(-> (.goto page "https://clojure.org")
(.then #(.screenshot page #js{:path "screenshot.png"}))
(.catch #(js/console.log %))
(.then #(.close browser)))))))))
Using plet
this becomes:
(plet [browser (.launch puppeteer)
page (.newPage browser)
_ (.goto page "https://clojure.org")
_ (-> (.screenshot page #js{:path "screenshot.png"})
(.catch #(js/console.log %)))]
(.close browser))
See the puppeteer example for the full code.
Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet
macro is similar to promesa.core/let
.
$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)' 0.17s user 0.02s system 109% cpu 0.168 total
The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx
this adds another 300ms or so, so for faster startup, either use a globally installed nbb
or use $(npm bin)/nbb script.cljs
to bypass npx
.
Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.
To load .cljs
files from local paths or dependencies, you can use the --classpath
argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs
relative to your current dir, then you can load it via (:require [foo.bar :as fb])
. Note that nbb
uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar
in the namespace name becomes foo_bar
in the directory name.
To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:
$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"
and then feed it to the --classpath
argument:
$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]
Currently nbb
only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar
files will be added later.
The name of the file that is currently being executed is available via nbb.core/*file*
or on the metadata of vars:
(ns foo
(:require [nbb.core :refer [*file*]]))
(prn *file*) ;; "/private/tmp/foo.cljs"
(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"
Nbb includes reagent.core
which will be lazily loaded when required. You can use this together with ink to create a TUI application:
$ npm install ink
ink-demo.cljs
:
(ns ink-demo
(:require ["ink" :refer [render Text]]
[reagent.core :as r]))
(defonce state (r/atom 0))
(doseq [n (range 1 11)]
(js/setTimeout #(swap! state inc) (* n 500)))
(defn hello []
[:> Text {:color "green"} "Hello, world! " @state])
(render (r/as-element [hello]))
Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core
namespace is included with the let
and do!
macros. An example:
(ns prom
(:require [promesa.core :as p]))
(defn sleep [ms]
(js/Promise.
(fn [resolve _]
(js/setTimeout resolve ms))))
(defn do-stuff
[]
(p/do!
(println "Doing stuff which takes a while")
(sleep 1000)
1))
(p/let [a (do-stuff)
b (inc a)
c (do-stuff)
d (+ b c)]
(prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3
Also see API docs.
Since nbb v0.0.75 applied-science/js-interop is available:
(ns example
(:require [applied-science.js-interop :as j]))
(def o (j/lit {:a 1 :b 2 :c {:d 1}}))
(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1
Most of this library is supported in nbb, except the following:
:syms
.-x
notation. In nbb, you must use keywords.See the example of what is currently supported.
See the examples directory for small examples.
Also check out these projects built with nbb:
See API documentation.
See this gist on how to convert an nbb script or project to shadow-cljs.
Prequisites:
To build:
bb release
Run bb tasks
for more project-related tasks.
Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb
License: EPL-1.0
#node #javascript
1624420620
JavaScript Getters and Setters
📺 The video in this post was made by Programming with Mosh
The origin of the article: https://www.youtube.com/watch?v=bl98dm7vJt0&list=PLTjRvDozrdlxEIuOBZkMAK5uiqp8rHUax&index=11
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!
#javascript #getters and setters. #getters #setters #javascript getters and setters
1616671994
If you look at the backend technology used by today’s most popular apps there is one thing you would find common among them and that is the use of NodeJS Framework. Yes, the NodeJS framework is that effective and successful.
If you wish to have a strong backend for efficient app performance then have NodeJS at the backend.
WebClues Infotech offers different levels of experienced and expert professionals for your app development needs. So hire a dedicated NodeJS developer from WebClues Infotech with your experience requirement and expertise.
So what are you waiting for? Get your app developed with strong performance parameters from WebClues Infotech
For inquiry click here: https://www.webcluesinfotech.com/hire-nodejs-developer/
Book Free Interview: https://bit.ly/3dDShFg
#hire dedicated node.js developers #hire node.js developers #hire top dedicated node.js developers #hire node.js developers in usa & india #hire node js development company #hire the best node.js developers & programmers
1628482694
Howdy, folks! The fact that you're here means you're looking for the new JavaScript features you can use in the close future. But by any chance, if you're not familiar with TC39, ECMA, or ECMAScript, check this article before reading this one, because you will need to know these to understand some of the following parts.
TC39 is an amazing and dedicated group of people who come from many different backgrounds and have one goal in common: they want to help to make the JavaScript language better. To do so, they have to keep many things in mind, and one rule they have is "don't break the web". Their approach to the language actually reminds me of the medical approach to the patients: "First, do no harm". Every step is carefully and meticulously calculated, so they don't break the existing parts.
Every feature that gets added to the spec has to go through the following 5 stages, just like drug trials. To proceed to the next stage, each has to achieve certain criteria. To be added to the ECMAScript spec, a feature has to be at least on stage 4.
JavaScript is an evolving language, and some features we use today were actually added pretty recently. After 2015, TC39 decided to make the changes annually, so each year they decide which new features are ready to be added. This is the list of the features that have been added to the spec after 2015:
Array.prototype.includes()
: Determines if a given element is included in the specified array. String.prototype.contains()
was also deprecated and String.prototype.includes()
was added to determine if a given string in included in another string.Exponentiation operator(** and **=)
: a**b
is shorthand notation for Math.pow(a,b)
, and a **= b
is shorthand for a = a**b
Object.values / Object.entries
: Retrieves an array of values / arrays of key-value pairs, respectively.Trailing commas in function parameter lists and calls
: Both (a) => {}
and (a,) => {}
are valid function definitions, and both foo(a)
and foo(a,)
are valid function calls.Async functions
: async/await was introduced to JavaScriptObject.getOwnPropertyDescriptors()
: Returns the property descriptors of all own properties of an object.String.prototype.padStart() / String.prototype.padEnd()
: Takes two arguments, first one being the repeat number, second one being the string that is going to be added and adds padding to the start or end of a given string.Promise.prototype.finally
: Finally was introduced to register a callback function that runs when a promise is settled (either fulfilled or rejected)Rest and spread operators(...)
: Rest operator collects values in an array. The spread operator spreads the values in an iterator.Asynchronous iteration
: for-await-of
was introduced. It is a variation of the for-of iteration statement and can be used in async iterable objects.Improvements on Regular Expressions
: RegExp Unicode Property Escapes, RegExp Lookbehind Assertions, s(dotAll) flag for regular expressions, RegExp named capture groupsArray.prototype.flat()
: Flattens nested arrays up to a provided depth. Default depth is 1.Array.prototype.flatMap()
: Flattens and maps a given array subsequently. Flattening depth is 1.Object.fromEntries()
: Builds an object from given key-value pairs.String.prototype.trimStart()
: Trims the start of a given string.String.prototype.trimEnd()
: Trims the end of a given string.Symbol.prototype.description
: Read-only and optional string description for the Symbol objects.Optional catch binding
: Allows the omission of the catch block.JSON.stringify()
, Function.prototype.toString()
and Array.sort()
String.prototype.matchAll()
: Returns all matches for a global regex.dynamic imports
: Before this, we could only use static imports, which only accepted strings for the module path. With dynamic imports, we got to conditionally import modules by using promises.BigInt
: A new primitive data type that represents numbers bigger than 2⁵³.Promise.allSettled()
: Returns when all given promises are settled (rejected or fulfilled, doesn't matter).globalThis
: Before this, the global object had different syntax in different JavaScript environments (in a web browser it can be either window
, self
, frames
, or this
, in web workers it is self
, in Node.js it is global
). globalThis provided a single syntax for the global object in all JavaScript environments.Optional Chaining Operator(?.)
: Legible property chains that don't throw an error if a requested reference is missing. If one of the chained properties is nullish (null or undefined), the whole expression returns undefined.Nullish coalescing operator(??)
: Binary operator. If the value of the left side expression is null or undefined, the right side of the operator is evaluated.String.prototype.replaceAll()
: Replaces all the occurrences of a given string with another.Promise.any()
: resolves if any of the given promises are resolved.Underscore as a numeric separator
: To increase legibility in bigger numbers, numeric separators can be replaced with underscores.Logical assignment operators(&&=, ||=, ??=)
All of them are binary operators, with the added functionality for assignment. For &&=, if the left side is truthy, the right-side expression is evaluated and assigned to the variable on the left side. For ||= if the left side is falsy, the right-side expression is evaluated and assigned to the left-side variable. With the ??=, if the left-side value is null or undefined, the right-side expression is evaluated and assigned to the variable on the left side.WeakRefs and Finalizers
: This is a class that helps you create weak references to objects, so they can be garbage collected. A FinalizationRegistry
object lets you register a callback that will allow you to invoke when the object is garbage collected.Alright! You can check the latest spec that was published from here.
Class Public Instance Fields & Private Instance Fields
:
Since ES2015, we could define fields by simply setting them up in our constructors. As a convention, fields that were not supposed to be accessed outside of the class methods were preceded by an underscore, but this did not stop any consumer of this class from accessing them anyway.
class ColorButton extends HTMLElement {
constructor() {
this.color = "red"
this._clicked = false
}
}
const button = new ColorButton()
// Public fields can be accessed and changed by anyone
button.color = "blue"
// Curse your sudden but inevitable betrayal
console.log(button._clicked) // Prints: false, can be accessed from the instance
button._clicked = true // Doesn't throw an error, can be read from the instance
The first part of this proposal offers a more clear way to define the fields in a class. Instead of defining them in our constructor, we can now define, and if we want to, initialize them on the top level of our classes.
class ColorButton extends HTMLElement {
color = "red"
_clicked = false
}
The second part offers a more secure way of hiding private fields from prying eyes. Instead of the conventional underscore, we can now use a preceding # in the field names to block anybody from accessing them outside of the class they're defined on.
class ColorButton extends HTMLElement {
// All fields are public by default
color = "red"
// Private fields start with a #, can only be changed from inside the class
#clicked = false
}
const button = new ColorButton()
// Public fields can be accessed and changed by anyone
button.color = "blue"
// SyntaxError here
console.log(button.#clicked) // Cannot be read from outside
button.#clicked = true // Cannot be assigned a value from outside
Private instance methods and accessors
:
Some methods and variables of a class are internally important for that class to behave like it's supposed to, but shouldn't be accidentally reached from outside. To protect these implementation details and keep them strictly internal, we can use private methods and accessors with the syntax of a preceding #.
class Banner extends HTMLElement {
// Private variable that cannot be reached directly from outside, but can be modified by the methods inside:
#slogan = "Hello there!"
#counter = 0
// private getters and setters (accessors):
get #slogan() {return #slogan.toUpperCase()}
set #slogan(text) {this.#slogan = text.trim()}
get #counter() {return #counter}
set #counter(value) {this.#counter = value}
constructor() {
super();
this.onmouseover = this.#mouseover.bind(this);
}
// private method:
#mouseover() {
this.#counter = this.#counter++;
this.#slogan = `Hello there! You've been here ${this.#counter} times.`
}
}
Static class fields and private static methods
:
Static class fields and methods are useful when you want certain fields and methods to only exist in the prototype, but not in every instance of the given class. On the other side, you might also want to allow some of these fields and methods to be only accessed from within the class.
Since ES2015, we can define static fields on a class by simply defining the field on the class itself.
class Circle {}
Circle.PI = 3.14
Going forward, we are now able to define these static fields inside the class definition using the static keyword.
class Circle {
static PI = 3.14
}
Just like we did with class fields and methods, we can use the # prefix to set any static method or field as private. This prevents access to these static fields and methods from the outside, meaning they can only be accessed from inside the class.
class Circle {
static #PI = 3.14
static #calculateArea(radius) {
return #PI * radius * radius
}
static calculateProperties(radius) {
return {
radius: radius,
area: #calculateArea(radius)
}
}
}
// Public static method, outputs {radius: 10, area: 314}
console.log(Circle.calculateProperties(10))
// SyntaxError - Private static field
console.log(Circle.PI)
// SyntaxError - Private static method
console.log(Circle.calculateArea(5))
In public fields, if you try to access a non-existent field on a class, you get undefined
as a result. However, private class fields throw an exception instead of returning undefined
when you try to access a non-existent field on an object. Then, one way to check if a private field exists in an object is to see if accessing that field inside the class throws an exception or not. However, this approach has a big shortcoming. The exception might simply be because of another reason, such as a faulty getter on an existing field.
That's why, in keyword was proposed to allow us to check if a given private property/method exists in a class instance:
class VeryPrivate {
constructor() {
super()
}
#variable
#method() {}
get #getter() {}
set #setter(text) {
this.#variable = text
}
static isPrivate(obj) {
return (
#variable in obj && #method in obj && #getter in obj && #setter in obj
)
}
}
Regular expressions allow us to search for patterns in strings. If you're not familiar with regular expressions, you might want to start by reading this article first.
Both Regexp.exec
and String.matchAll
gives us a list of matches as a result. Regexp.exec
gives these results one by one, so you need to call it multiple times to get all matches until it returns null. On the other hand String.matchAll
returns an iterator where you can iterate over all matches. These results include both the full string of characters and the parenthesized substrings being matched, the input string and the 0-based index of the match. Take a look at the following example:
const str = 'Ingredients: cocoa powder, cocoa butter, other stuff'
const regex = /(cocoa) ([a-z]+)/g
const matches = [...str.matchAll(regex)]
// 0: "cocoa powder", 1: "cocoa", 2: "powder"
// index: 13
// input: "Ingredients: cocoa powder, cocoa butter, other stuff"
console.log(matches[0])
// 0: "cocoa butter", 1: "cocoa", 2: "butter"
// index: 27
// input: "Ingredients: cocoa powder, cocoa butter, other stuff"
console.log(matches[1])
While these results are pretty informative about the location of the entire match in the original input, they lack information regarding the indices of the substring matches. By using the new /d
flag, we can ask for the start and end positions of each matched capture group.
const str = 'Ingredients: cocoa powder, cocoa butter, other stuff'
const regex = /(cocoa) ([a-z]+)/gd
const matches = [...str.matchAll(regex)]
// 0: "cocoa powder", 1: "cocoa", 2: "powder"
// index: 13
// input: "Ingredients: cocoa powder, cocoa butter, other stuff"
// indices: [[13,25],[13,18],[19,25]]
console.log(matches[0])
// 0: "cocoa butter", 1: "cocoa", 2: "butter"
// index: 27
// input: "Ingredients: cocoa powder, cocoa butter, other stuff"
// indices: [[27,39],[27,32],[33,39]]
console.log(matches[1])
Until this point, we could only use await in the scope of async functions. This was fine until it wasn't, like when we hit the top level of our module and could not use the await keyword. Now await
can be used at the top level of a module, and can be super handy when initializing imports and creating fallbacks.
Here's an example:
// Before the top-level await, JavaScript would have given you a SyntaxError with this line of code, but that is no more
await Promise.resolve(console.log("🎉"))
So until the awaited promise is resolved, the execution of the current module and the parent module that imports the current child module are deferred, but the sibling modules can be executed in the same order. Check this article out to see more examples.
#javascript #es2022
1625232484
For more than two decades, JavaScript has facilitated businesses to develop responsive web applications for their customers. Used both client and server-side, JavaScript enables you to bring dynamics to pages through expanded functionality and real-time modifications.
Did you know!
According to a web development survey 2020, JavaScript is the most used language for the 8th year, with 67.7% of people choosing it. With this came up several javascript frameworks for frontend, backend development, or even testing.
And one such framework is Vue.Js. It is used to build simple projects and can also be advanced to create sophisticated apps using state-of-the-art tools. Beyond that, some other solid reasons give Vuejs a thumbs up for responsive web application development.
Want to know them? Then follow this blog until the end. Through this article, I will describe all the reasons and benefits of Vue js development. So, stay tuned.
Released in the year 2014 for public use, Vue.Js is an open-source JavaScript framework used to create UIs and single-page applications. It has over 77.4 million likes on Github for creating intuitive web interfaces.
The recent version is Vue.js 2.6, and is the second most preferred framework according to Stack Overflow Developer Survey 2019.
Every Vue.js development company is widely using the framework across the world for responsive web application development. It is centered around the view layer, provides a lot of functionality for the view layer, and builds single-page web applications.
• Vue was ranked #2 in the Front End JavaScript Framework rankings in the State of JS 2019 survey by developers.
• Approximately 427k to 693k sites are built with Vue js, according to Wappalyzer and BuiltWith statistics of June 2020.
• According to the State of JS 2019 survey, 40.5% of JavaScript developers are currently using Vue, while 34.5% have shown keen interest in using it in the future.
• In Stack Overflow's Developer Survey 2020, Vue was ranked the 3rd most popular front-end JavaScript framework.
• High-speed run-time performance
• Vue.Js uses a virtual DOM.
• The main focus is on the core library, while the collaborating libraries handle other features such as global state management and routing.
• Vue.JS provides responsive visual components.
Vue js development has certain benefits, which will encourage you to use it in your projects. For example, Vue.js is similar to Angular and React in many aspects, and it continues to enjoy increasing popularity compared to other frameworks.
The framework is only 20 kilobytes in size, making it easy for you to download files instantly. Vue.js easily beats other frameworks when it comes to loading times and usage.
Take a look at the compelling advantages of using Vue.Js for web app development.
Vue.Js is popular because it allows you to integrate Vue.js into other frameworks such as React, enabling you to customize the project as per your needs and requirements.
It helps you build apps with Vue.js from scratch and introduce Vue.js elements into their existing apps. Due to its ease of integration, Vue.js is becoming a popular choice for web development as it can be used with various existing web applications.
You can feel free to include Vue.js CDN and start using it. Most third-party Vue components and libraries are additionally accessible and supported with the Vue.js CDN.
You don't need to set up node and npm to start using Vue.js. This implies that it helps develop new web applications, just like modifying previous applications.
The diversity of components allows you to create different types of web applications and replace existing frameworks. In addition, you can also choose to hire Vue js developers to use the technology to experiment with many other JavaScript applications.
One of the main reasons for the growing popularity of Vue.Js is that the framework is straightforward to understand for individuals. This means that you can easily add Vue.Js to your web projects.
Also, Vue.Js has a well-defined architecture for storing your data with life-cycle and custom methods. Vue.Js also provides additional features such as watchers, directives, and computed properties, making it extremely easy to build modern apps and web applications with ease.
Another significant advantage of using the Vue.Js framework is that it makes it easy to build small and large-scale web applications in the shortest amount of time.
The VueJS ecosystem is vibrant and well-defined, allowing Vue.Js development company to switch users to VueJS over other frameworks for web app development.
Without spending hours, you can easily find solutions to your problems. Furthermore, VueJs lets you choose only the building blocks you need.
Although the main focus of Vue is the view layer, with the help of Vue Router, Vue Test Utils, Vuex, and Vue CLI, you can find solutions and recommendations for frequently occurring problems.
The problems fall into these categories, and hence it becomes easy for programmers to get started with coding right away and not waste time figuring out how to use these tools.
The Vue ecosystem is easy to customize and scales between a library and a framework. Compared to other frameworks, its development speed is excellent, and it can also integrate different projects. This is the reason why most website development companies also prefer the Vue.Js ecosystem over others.
Another benefit of going with Vue.Js for web app development needs is flexibility. Vue.Js provides an excellent level of flexibility. And makes it easier for web app development companies to write their templates in HTML, JavaScript, or pure JavaScript using virtual nodes.
Another significant benefit of using Vue.Js is that it makes it easier for developers to work with tools like templating engines, CSS preprocessors, and type checking tools like TypeScript.
Vue.Js is an excellent option for you because it encourages two-way communication. This has become possible with the MVVM architecture to handle HTML blocks. In this way, Vue.Js is very similar to Angular.Js, making it easier to handle HTML blocks as well.
With Vue.Js, two-way data binding is straightforward. This means that any changes made by the developer to the UI are passed to the data, and the changes made to the data are reflected in the UI.
This is also one reason why Vue.Js is also known as reactive because it can react to changes made to the data. This sets it apart from other libraries such as React.Js, which are designed to support only one-way communication.
One essential thing is well-defined documentation that helps you understand the required mechanism and build your application with ease. It shows all the options offered by the framework and related best practice examples.
Vue has excellent docs, and its API references are one of the best in the industry. They are well written, clear, and accessible in dealing with everything you need to know to build a Vue application.
Besides, the documentation at Vue.js is constantly improved and updated. It also includes a simple introductory guide and an excellent overview of the API. Perhaps, this is one of the most detailed documentation available for this type of language.
Support for the platform is impressive. In 2018, support continued to impress as every question was answered diligently. Over 6,200 problems were solved with an average resolution time of just six hours.
To support the community, there are frequent release cycles of updated information. Furthermore, the community continues to grow and develop with backend support from developers.
VueJS is an incredible choice for responsive web app development. Since it is lightweight and user-friendly, it builds a fast and integrated web application. The capabilities and potential of VueJS for web app development are extensive.
While Vuejs is simple to get started with, using it to build scalable web apps requires professionalism. Hence, you can approach a top Vue js development company in India to develop high-performing web apps.
Equipped with all the above features, it doesn't matter whether you want to build a small concept app or a full-fledged web app; Vue.Js is the most performant you can rely on.
#vue js development company #vue js development company in india #vue js development company india #vue js development services #vue js development #vue js development companies