Search results

Generator functions.To create a generator, we need a special syntax construct: function*, so-called “… For instance, an unending sequence of pseudo-random numbers.… For instance, we have a function that generates a sequence of numbers:… generator composition is a natural way to insert a flow of one generator into another.… That’s not a problem: the generator will wait.
JavaScript is a very function-oriented language. It gives us a lot of freedom.… Below, makeCounter creates the “counter” function that returns the next number on each invocation:… random number generator to generate random values for automated tests.… Closure There is a general programming term “closure”, that developers generally should know… When on an interview, a frontend developer gets a question about “what’s a closure?”
In other words, a negative number after "e" means a division by 1 with the given number of… number using the unary plus or a Number() call, e.g. write +num.toFixed(5).… They “read” a number from a string until they can’t.… A few examples: Math.random() Returns a random number from 0 to 1 (not including 1).… A negative number after "e" causes the number to be divided by 1 with given zeroes.
Generators are labelled with function* (note the star) and use yield to generate a value, then we can… This example generates a sequence of values from start to end:… A common practice for Symbol.iterator is to return a generator, it makes the code shorter, as you can… generates a sequence of values, we can use an asynchronous generator.… In a regular generator we’d use result = generator.next() to get values.
Sec-WebSocket-Key – a random browser-generated key, used to ensure that the server supports WebSocket… , so that’s a sane default.… a lot of data to send.… But the user has a slow network connection, maybe on a mobile internet, outside of a city.… rights), they send a “connection close frame” with a numeric code and a textual reason.
The built-in eval function allows to execute a string of code.… But that time passed a decade ago. Right now, there’s almost no reason to use eval.… If someone is using it, there’s a good chance they can replace it with a modern language construct or… a JavaScript Module.… It creates a function from a string, also in the global scope. So it can’t see local variables.
a full browser restart (for localStorage).… given position. length – the number of stored items.… If they were any other type, like a number, or an object, they would get converted to a string automatically… removeItem(key) – remove the key with its value. clear() – delete everything. key(index) – get the key number… index. length – the number of stored items.
That may be even a primitive, like a number or a string, but it’s better to use objects, preferably with… a SyntaxError with the given message, the same way as JavaScript would generate it itself.… For instance, we want to measure the time that a Fibonacci numbers function fib(n) takes.… particular, the implementation of fib(n) in the code below returns an error for negative or non-integer numbers… message Error message. url URL of the script where error happened. line, col Line and column numbers
Primitives.The most intricate thing happens with strings, numbers and booleans.… access their properties, temporary wrapper objects are created using built-in constructors String, Number… But that is generally a bad idea.… So, generally, modifying a native prototype is considered a bad idea.… Polyfilling is a term for making a substitute for a method that exists in the JavaScript specification
That is: a number, followed by € sign. Lookahead.The syntax is: X(?… For an integer number followed by €, the regexp will be \d+(?… That’s a number \d+, NOT followed by €. For that, a negative lookahead can be applied.… number, not preceded by $, then we can use a negative lookbehind (?… That’s natural: we look for a number \d+, while (?
That’s fine for simple scripts, inlined into HTML, but generally isn’t a good thing.… The "s" letter is absent in getElementById, because it returns a single element.… It returns a collection, not an element!… In contrast, querySelectorAll returns a static collection. It’s like a fixed array of elements.… The static collection did not increase after the appearance of a new div in the document.
Iterable objects are a generalization of arrays.… That’s a concept that allows us to make any object useable in a for..of loop.… Like a range object that represents an interval of numbers:… Or we can make an iterable object that generates an infinite sequence of pseudorandom numbers.… a “real” Array from it.
for both floating-point and integer numbers, bigint for integer numbers of arbitrary length, string… number.… Comparisons Equality check == for values of different types converts them to a number (except null and… number as well.… Greater/less comparisons compare strings character-by-character, other types are converted to a number
HttpError objects may have a statusCode property with a value like 404 or 403 or 500.… The property may be absent or it may be in a wrong format (like a string value for age instead of a number… We’ll make a new class ReadError to represent a generic “data reading” error.… a ReadError instead.… Wrapping exceptions is a widespread technique: a function handles low-level exceptions and creates higher-level
A value in JavaScript is always of a certain type. For example, a string or a number.… For example, a variable can at one moment be a string and then store a number:… The number type represents both integer and floating point numbers.… It is a special value that’s greater than any number.… string or a number or whatever).
Recently, globalThis was added to the language, as a standardized name for a global object, that should… We’ll use window here, assuming that our environment is a browser.… Modern scripts use JavaScript modules where such a thing doesn’t happen.… The global object has a universal name globalThis.… And keep their number at minimum.
If we want a number, we can use \d+.… The first number \d+ has 7 digits, and then a number of 2 digits:… The first number has 6 digits, and then a number… There are many ways to split a sequence of digits 123456789 into numbers.… To avoid messing up with the numbers, we can give the parentheses a name, e.g. (?
JavaScript-initiated focus loss A focus loss can occur for many reasons.… for elements that a visitor can interact with: <button>, <input>, <select>, <a&… The value of the attribute is the order number of the element when Tab (or something like that) is used… To make an element a part of the form on par with <input>.… For instance, here’s a list.
the brackets: Array elements are numbered… We can get an element by its number in square brackets:… That’s essentially the same as obj[key], where arr is the object, while numbers are used as keys.… If new Array is called with a single argument which is a number, then it creates an array without items… declaration: The call to new Array(number
Now it works with any number… of arguments (though the hash function would also need to be adjusted to allow any number of arguments… It would be better if it could glue any number of args.… Decorators and function properties.It is generally safe to replace a function or a method with a decorated… a special Proxy object to wrap a function.
JSON.stringify.The JSON (JavaScript Object Notation) is a general format to represent values and objects… JSON supports following data types: Objects { ... } Arrays [ ... ] Primitives: strings, numbers, boolean… Formatting: space.The third argument of JSON.stringify(value, replacer, space) is the number of spaces… In this case, the string is used for indentation instead of a number of spaces.… JSON supports plain objects, arrays, strings, numbers, booleans, and null.
ArrayBuffer and views are a part of ECMA standard, a part of JavaScript.… The arguments are similar to array.slice, negative numbers are allowed too.… By clicking on a link you download a dynamically-generated Blob with hello world contents as a file:… A generated URL (and hence the link with it) is only valid within the current document, while it’s open… a URL.
Currying is a transformation of functions that translates a function from callable as f(a, b, c) into… In other words, curry(f) for two-argument f(a, b) translates it into a function that runs as f(a)(b):… The result of curry(func) is a wrapper function(a).… Fixed-length functions only The currying requires the function to have a fixed number of… Summary.Currying is a transform that makes f(a,b,c) callable as f(a)(b)(c).
For example, outputting goods from a list one after another or just running the same code for each number… For example, the loop below asks the user for a series of numbers, “breaking” when no number is entered… directive stops executing the body and passes control to the next iteration of for (with the next numberA label is an identifier with a colon before a loop:… A continue is only possible from inside a loop.
The total number of cookies per domain is limited to around 20+, the exact limit depends on the browser… All forms generated by bank.com have a special field, a so-called “XSRF protection token”, that an evil… page can’t generate or extract from a remote page.… Normally, if such a thing happens, and a user visits a web-page with a hacker’s JavaScript code, then… The number of cookies allowed on a domain is around 20+ (varies by browser).
code block is inside a function, then var becomes a function-level variable:… That’s because a long time ago in JavaScript, blocks had no Lexical Environments, and var is a remnant… variable any number of times.… But a Function Declaration must have a name, so this kind of code will give an error:… declare a variable.
While new RegExp is more often used when we need to create a regexp “on the fly” from a dynamically generated… This a very important nuance.… part of the string before the match $' inserts a part of the string after the match $n if n is a… 1-2 digit number, then it inserts the contents of n-th parentheses, more about it in the chapter Capturing… A regular expression consists of a pattern and optional flags: g, i, m, u, s, y.
Math operators.BigInt can mostly be used like a regular number, for example:… way to convert value to a number.… () to convert a bigint to a number.… This library implements big numbers using its own methods.… We can use them instead of native bigints: Operation native BigInt JSBI Creation from Number a
Or we have a class User and a class EventEmitter that implements event generation, and we’d like to add… The mixin will provide a method .trigger(name, [...data]) to “generate an event” when something important… Or, a menu can generate the event "select" when a menu item is selected, and other objects… Summary.Mixin – is a generic object-oriented programming term: a class that contains methods for other… So generally one should think well about the naming methods of a mixin, to minimize the probability of
way to tell a “real” user event from a script-generated one.… “default action”, such as navigating to a link, starting a selection, and so on.… Let’s see a practical example – a hiding rabbit (could be a closing menu or something else).… We shouldn’t generate browser events as it’s a hacky way to run handlers.… Native events might be generated: As a dirty hack to make 3rd-party libraries work the needed way, if
Let’s say we have a string like +7(903)-123-45-67 and want to find all numbers in it.… A number is a sequence of 1 or more digits \d.… Quantity {n}.The simplest quantifier is a number in curly braces: {n}.… A number is a sequence of one or more digits in a row.… Regexp for decimal fractions (a number with a floating point): \d+\.
We could also start it from somewhere in the middle of the transition, from an exact number… Steps.The timing function steps(number of steps[, start/end]) allows splitting an transition into multiple… The first argument of steps(9, start) is the number of steps.… For instance, width, color, font-size are all numbers.… When you animate them, the browser gradually changes these numbers frame by frame, creating a smooth
JavaScript allows us to work with primitives (strings, numbers, etc.) as if they were objects.… one would want to do with a primitive, like a string or a number.… A number has methods of its own, for instance, toFixed(n) rounds the number to the given precision:… us to explicitly create “wrapper objects” for primitives using a syntax like new Number(1) or new Boolean… They convert a value to the corresponding type: to a string, a number, or a boolean (primitive).
(value) function to explicitly convert a value to a number:… value from a string-based source like a text form but expect a number to be entered.… If the string is not a valid number, the result of such a conversion is NaN.… Can be performed with Number(value).… The notable exceptions where people usually make mistakes are: undefined is NaN as a number, not 0.
to numbers.… But if the operand is not a number, the unary plus converts it into a number.… Every operator has a corresponding precedence number.… decreasing a number by one is among the most common numerical operations.… Without them: a = 1 + 2, 3 + 4 evaluates + first, summing the numbers into a = 3, 7, then the assignment
For instance: Uint8Array – treats each byte in ArrayBuffer as a separate number, with possible values… Float64Array – treats every 8 bytes as a floating point number with possible values from 5.0x10-324 to… Its byte length will be length multiplied by the number of bytes in a single item TypedArray.BYTES_PER_ELEMENT… It saves 255 for any number that is greater than 255, and 0 for any negative number.… The i-th number is arr[i].
For instance, binary plus + can work both with strings (concatenates them) and numbers (adds them).… Also, if an object is compared using == with a string, number or a symbol, it’s also unclear which conversion… Still, they use the "number" hint, not "default".… a number for the hint "number".… Then "2" * 2 becomes 2 * 2 (the string is converted to number).
The syntax is: It accepts any number… It may contain numbers or strings or objects or whatever. We have a set of some items.… The default is a string order. The arr.sort(fn) method implements a generic sorting algorithm.… A comparison function may return any number Actually, a comparison function is only required… to return a positive number to say “greater” and a negative number to say “less”.
That’s rare, but such a thing may happen when a visitor loads outdated JavaScript code, e.g. from a proxy… A key must be one of these types – number, date, string, binary, or array.… newly stored object is generated automatically, as an ever-incrementing number.… The store.add method generates a "ConstraintError" in that case.… The index will enforce that by generating an error if we try to add a duplicate. multiEntry – only used
And Number property means that it’s a digit: maybe Arabic or Chinese, and so on.… Number N: decimal digit Nd, letter number Nl, other No.… Nl (e.g. Ⅻ – a character for the roman number 12), plus some other symbols Other_Alphabetic (OAlpha)… Example: hexadecimal numbers.For instance, let’s look for hexadecimal numbers, written as xFF, where… and {n} we’ll see how to look for numbers that contain many digits.
But there’s a pitfall.… usually it’s a stringified object.… There’s also a keepalive flag for doing such “after-page-left” requests in fetch method for generic… DOMContentLoaded [3] iframe onload [4] img onload [4] readyState:complete [4] window onload The numbers… Events labeled with the same digit happen approximately at the same time (± a few ms).
The curve order equals the number of points minus one.… For two points we have a linear curve (that’s a straight line), for three points – quadratic curve (parabolic… The algorithm is recursive and can be generalized for any number of control points.… Sometimes we have another task: to draw a curve through several points, so that all of them are on a… Using a mathematical formulas.
In this case the numbering also goes from left to right.… Then groups, numbered from left to right by an opening paren.… Named groups.Remembering groups by their numbers is hard.… That’s done using $n, where n is the group number.… A group may be excluded from numbering by adding ?: in its start.
Consider a practical task – we have a phone number like "+7(903)-123-45-67", and we need to… turn it into pure numbers: 79031234567.… To do so, we can find and remove anything that’s not a number.… For instance, let’s find the first digit in the phone number:… In the beginning of the chapter we saw how to make a number-only phone number from a string like +7(903
The idea is that if we have a lot of elements handled in a similar way, then instead of assigning a handler… Our task is to highlight a cell <td> on click.… As the result, we have a fast, efficient highlighting code, that doesn’t care about the total number… But there’s a more elegant solution.… Just make a method and put it in the markup.
Date object with the time equal to number of milliseconds (1/1000 of a second) passed after the Jan 1st… UTC-variant: getTime() Returns the timestamp for the date – a number of milliseconds passed from the… , date diff.When a Date object is converted to number, it becomes the timestamp same as date.getTime(… date-to-number transform.… That’s because a Date becomes the timestamp when converted to a number.
As we know, fetch returns a promise.… And JavaScript generally has no concept of “aborting” a promise.… Generally, we have two parties in the process: The one that performs a cancelable operation, it sets… a listener on controller.signal.… AbortController is a simple object that generates an abort event on its signal property when the abort
Digit keys have codes: "Digit<number>": "Digit0", "Digit1" etc.… There’s a dilemma here: in such a listener, should we check the value of event.key or event.code?… Or we want a hotkey to work even after a language switch? Then event.code may be better.… For instance, the <input> below expects a phone number, so it does not accept keys except digits… Summary.Pressing a key always generates a keyboard event, be it symbol keys or special keys like Shift
We can use both the name or the number in the document to get the form.… subelements, select.value – the value of the currently selected <option>, select.selectedIndex – the number… They provide three different ways of setting a value for a <select>: Find the corresponding <… If we know the new option number: set select.selectedIndex to that number.… Option elements have properties: option.selected Is the option selected. option.index The number
The remote server another.com dynamically generates a script that calls gotWeather(...) with the data… The essential difference is that a safe request can be made with a <form> or a <script>,… Additionally, the header Access-Control-Max-Age may specify a number of seconds to cache the permissions… If there’s the header Access-Control-Max-Age with a number of seconds, then the preflight permissions… with a number of seconds to cache the permissions.
Only first 50 results are shown.