Search results

The for…of and for…in loops A small announcement for advanced readers.… This article covers only basic loops: while, do..while and for(..;..;..).… See for…of and iterables for looping over arrays and iterable objects. Otherwise, please read on.… For instance, the loop below outputs i while i < 3:… For example, in the code below we loop over i and j, prompting for the coordinates (i, j) from (0,0)
Understanding how event loop works is important for optimizations, and sometimes for the right architecture… There’s an endless loop, where the JavaScript engine waits for tasks, executes them and then sleeps,… When the time is due for a scheduled setTimeout, the task is to run its callback. …and so on.… Tasks are set – the engine handles them – then waits for more tasks (while sleeping and consuming close… Highlight the first 100 lines, then schedule setTimeout (with zero-delay) for the next 100 lines, and
we’d like to use for..of loop on it, such as for(value of range), to get values from 1 to 5.… It calls range[Symbol.asyncIterator]() once, and then its next() for values.… use for..of to loop over them.… object, so it’s both synchronously (for..of) and asynchronously (for await..of) iterable.… And let it care about all pagination stuff. For us it’ll be a simple async iteration for await..of.
both floating-point and integer numbers, bigint for integer numbers of arbitrary length, string for… symbol – for complex data structures and unique identifiers, we haven’t learnt them yet.… remainder and ** for power of a number.… variable declared in for(let...) loop is visible only inside the loop.… Use labels to break nested loops. Details in: Loops: while and for.
For that purpose, please use XMLHttpRequest, we’ll cover it later.… await..of loop, but it’s not yet widely supported (see browser issues), so we use while loop.… It may be absent for cross-origin requests (see chapter Fetch: Cross-Origin Requests) and, well, technically… Once again, please note, that’s not for upload progress (no way now with fetch), only for download progress… Also, if the size is unknown, we should check receivedLength in the loop and break it once it reaches
Then it won’t appear in a for..in loop, just like the built-in one:… For instance, Math.PI is non-writable, non-enumerable and non-configurable:… Please note: configurable: false prevents changes of property flags and its deletion, while allowing… Another difference is that for..in ignores symbolic and non-enumerable properties, but Object.getOwnPropertyDescriptors… And also there are tests for them: Object.isExtensible(obj) Returns false if adding properties is forbidden
There’s a special syntax for that, called “lookahead” and “lookbehind”, together referred to as “lookaround… That’s only possible if patterns Y and Z aren’t mutually exclusive. For example, \d+(?=\s)(?… =.*30) looks for \d+ that is followed by a space (?=\s), and there’s 30 somewhere after it (?… That’s natural: we look for a number \d+, while (?… That is: match everything, in any context, and then filter by context in the loop.
For instance, sales department has 2 employees: John and Alice.… For instance, the sites department in the future may be split into teams for siteA and siteB.… For web-developers there are much better-known examples: HTML and XML documents.… For instance, arr.unshift(obj) operation has to renumber all elements to make room for a new obj, and… But for many tasks a recursive solution is fast enough and easier to write and support.
A real ninja will never use i as the counter in a "for" loop. Anywhere, but not here.… Like obj, data, value, item, elem and so on. The ideal name for a variable is data.… And when there’s a typo… Ummm… We’re stuck for long, time to drink tea.… A reader may decide to look for a hidden meaning and meditate for an hour or two of their paid working… Follow all, and your code will become a valuable lesson for young developers looking for enlightenment
Loops.One of the oldest ways to cycle array items is the for loop over indexes:… The for..in loop will list them though.… The for..in loop is optimized for generic objects, not arrays, and thus is 10-100 times slower.… So the array [] gets converted to primitive for the purpose of comparison and becomes an empty string… Instead you can use for..of loop to compare arrays item-by-item.
So if you run the code above and don’t dismiss the alert window for some time, then the next alert will… In this case the engine waits for func to complete, then checks the scheduler and if the time is up,… And here is the picture for the nested setTimeout: The nested setTimeout… That limitation comes from ancient times and many scripts rely on it, so it exists for historical reasons… For server-side JavaScript, that limitation does not exist, and there exist other ways to schedule an
What’s interesting about them is that the data survives a page refresh (for sessionStorage) and even… a full browser restart (for localStorage).… For that reason, sessionStorage is used sparingly.… Also, event.storageArea contains the storage object – the event is the same for both sessionStorage and… sessionStorage, globally for localStorage).
searching and replacing, one of most useful ones.… The swiss army knife for searching and replacing.… It will be called for each match, and the returned value will be inserted as a replacement.… …And so on. If there are no matches, regexp.exec returns null and resets regexp.lastIndex to 0.… For instance, here we call regexp.test twice on the same text, and the second time fails:
used one of them (admin) to get into it and make changes.… For instance, here a and b reference the same object, thus they are equal:… and copying them on the primitive level.… make user and clone truly separate objects, we should use a cloning loop that examines each value of… Summary.Objects are assigned and copied by reference.
For instance, HTML has tags and attributes, JavaScript code has functions, variables, and so on.… But then the call str.match(/\w+/g) will look for all words in the text, while we need one word at position… For a regexp without flags g and y, this method looks only for the first match, it works exactly like… And that’s what the flag y is for.… Using flag y is the key for correct implementations and a good performance.
For instance, here we create the generator and get its first yielded value:… We can loop over their values using for..of:… Otherwise, the loop would repeat forever and hang.… And, surely, they are great for making iterable objects.… await ... of loops.
For instance, <head> and <body> are children of <html> element.… For instance, here <body> has children <div> and <ul> (and few blank text nodes):… Don’t use for..in to loop over collections Collections are iterable using for..of.… The for..in loop iterates over all enumerable properties.… For instance, in childNodes we can see both text nodes, element nodes, and even comment nodes if they
reading a property of target, set trap for writing a property into target, and so on.… Iteration with “ownKeys” and “getOwnPropertyDescriptor”.Object.keys, for..in loop and most other methods… descriptors). for..in loops over non-symbol keys with enumerable flag, and also prototype keys.… In the example below we use ownKeys trap to make for..in loop over user, and also Object.keys and Object.values… We have an object user with _name property and a getter for it.
And what if a function is passed along as an argument and called from another place of code, will it… if, for, while and so on, variables declared in {...} are also only visible inside:… The similar thing holds true for for and while loops:… Understanding such things is great for the overall knowledge of JavaScript and beneficial for more complex… Later, when counter() is called, a new Lexical Environment is created for the call, and its outer Lexical
Bezier curves are used in computer graphics to draw shapes, for CSS animation and in many other places… For instance, for t=0 – both points will be at the beginning of segments, and for t=0.25 – on the 25%… and for t=0.5 (the right picture) – in the middle of the segment.… It’s red and parabolic on the pictures above. That was a process for 3 points.… In web development – for graphics on Canvas and in the SVG format.
The second argument (and the next ones if needed) are for the successful result.… So the single callback function is used both for reporting errors and passing back results.… And indeed it is. For one or maybe two nested calls it looks fine.… if we have real code instead of ... that may include more loops, conditional statements and so on.… It’s difficult to read, and you probably noticed that one needs to eye-jump between pieces while reading
There is no separate type for a single character.… The function func is called automatically, receives the string and embedded expressions and can process… It looks for the substr in str, starting from the given position pos, and returns the position where… There are special methods that allow to get the character for the code and back: str.codePointAt(pos… The code for a (97) is greater than the code for Z (90).
For instance, if we put an object into an array, then while the array is alive, the object will be alive… For instance, we have code that keeps a visit count for users.… Like Set, it supports add, has and delete, but not size, keys() and no iterations.… But not for arbitrary data, rather for “yes/no” facts.… That comes at the cost of not having support for clear, size, keys, values… WeakMap and WeakSet are used
Arrays are used for storing ordered collections. But that’s not enough for real life.… in for..of.… And the standard iteration for map returns same key/value pairs as map.entries().… For example, we have visitors coming, and we’d like to remember everyone.… Iteration over Set.We can loop over a set either with for..of or using forEach:
And it may be a better choice for such task.… For instance, to react on arrow keys Up and Down or hotkeys (including combinations of keys).… There are several widespread keyboard layouts, and the specification gives key codes for each of them… For instance, most keyboards have two Shift keys: on the left and on the right side.… The event.code tells us exactly which one was pressed, and event.key is responsible for the “meaning”
A File object inherits from Blob and is extended with filesystem-related capabilities.… readAsArrayBuffer – for binary files, to do low-level binary operations.… to use this data in src for img or another tag.… The most widely used events are for sure load and error.… In addition to Blob methods and properties, File objects also have name and lastModified properties,
Regular expressions are patterns that provide a powerful way to search and replace in text.… Regular Expressions.A regular expression (also “regexp”, or just “reg”) consists of a pattern and optional… The “long” syntax: And the “short”… They play the same role as quotes for strings.… A regular expression consists of a pattern and optional flags: g, i, m, u, s, y.
That’s why there’s no need for a semicolon at the end of export class and export function:… For instance, if you import * as library from a huge code library, and then use only few methods, then… For instance, let’s import sayHi into the local variable hi for brevity, and import sayBye as bye:… Now hi and bye are official names for outsiders, to be used in imports:… So, remember, import needs curly braces for named exports and doesn’t need them for the default one.
Normally it goes upwards till <html>, and then to document object, and some events even reach window… for a click event on a <td> inside a table: That is: forAnd there’s a logical explanation for that.… The same for event handlers.… Bubbling and capturing lay the foundation for “event delegation” – an extremely powerful event handling
Forms and control elements, such as <input> have a lot of special properties and events.… That’s a so-called “named collection”: it’s both named and ordered.… This is typical with radio buttons and checkboxes.… and radio buttons.… (For checkboxes and radio buttons, use input.checked to determine whether a value is selected.)
How do we find the width and height of the browser window?… But there are additional methods and peculiarities to consider.… Also available as window properties scrollX and scrollY For historical reasons, both properties… For instance, when we need to cover the page with a large message requiring immediate attention, and… We can use the same technique to freeze the scroll for other elements, not just for document.body.
of characters, while for element nodes that many child nodes.… For this to work, the range must contain both opening and closing tags for all elements inside it: no… For instance, when the user presses the mouse button on it and starts to move the pointer.… different APIs for selections: For document: Selection and Range objects.… For input, textarea: additional methods and properties.
Otherwise, we re-download it again and put it in the cache for further possible reuse:… If the cache contains a value for the specified key, and the WeakRef object has not been deleted by the… For example, it could be an external utility for monitoring and notifying about the system’s state (commonly… If not, it downloads it from the cloud and puts it in the cache for further use.… This is beneficial for addressing excessive memory usage and optimizing the utilization of system resources
for them.… For <body> and <html>. For elements with position:fixed.… For example, offsetParent is null, and offsetWidth, offsetHeight are 0 when we created an element, but… On the picture below we can see scrollHeight and scrollTop for a block with a vertical scroll.… But Firefox shows 300px, while Chrome and Edge show less.
We can use one for years, and only if something goes wrong – bring it for repairs.… The secret of reliability and simplicity of a coffee machine – all details are well-tuned and hidden… Internal and external interface.In object-oriented programming, properties and methods are split into… private properties and methods.… For instance, here’s a private #waterLimit property and the water-checking private method #fixWaterAmount
For instance, an element node corresponding to tag <a> has link-related properties, and the one… For instance, DOMString, boolean and so on.… For instance, let’s compare tagName and nodeName for the document and a comment node:… Let’s say we have an arbitrary string, for instance entered by a user, and want to show it.… It has a numeric value: 1 for elements,3 for text nodes, and a few others for other node types.
≈ occupy 2 bytes, while codes for 𝒳, 𝒴 and 😄 are longer, they have 4 bytes.… …And so on.… letters: \p{sc=Cyrillic}, for Chinese hieroglyphs: \p{sc=Han}, and so on:… and {n} we’ll see how to look for numbers that contain many digits.… ) and so on.
['"], but it would find strings with mixed quotes, like "...' and '...".… To make sure that the pattern looks for the closing quote exactly the same as the opening one, we can… wrap it into a capturing group and backreference it: (['"])(.*?)… The regular expression engine finds the first quote (['"]) and memorizes its content.… pattern \1, in the replacement: $1 In the replacement string we use a dollar sign: $1, while
For example, style is acceptable if we calculate coordinates of an element dynamically and want to set… That’s more flexible and easier to support. className and classList.Changing a class is one of the most… The browser takes the computed value and makes all units fixed and absolute, for instance: height:20px… For instance, if there are properties paddingLeft/paddingTop, then what should we get for getComputedStyle… That’s to guarantee that there’s no side way for an evil page to test if a link was visited and hence
When the browser parses the HTML to create DOM objects for tags, it recognizes standard attributes andFor instance, "type" is standard for <input> (HTMLInputElement), but not for <body… The attributes collection is iterable and has all the attributes of the element (standard and non-standard… What for?… What if we use a non-standard attribute for our purposes and later the standard introduces it and makes
There are two tools for that: Transpilers. Polyfills.… It can parse (“read and understand”) modern code and rewrite it using older syntax constructs, so that… It “fills in” the gap and adds missing implementations.… For this particular case, the polyfill for Math.trunc is a script that implements it, like this:… /compat-table/es6/ – for pure JavaScript. https://caniuse.com/ – for browser-related functions.
For instance, [a-z] is a character in range from a to z, and [0-5] is a digit from 0 to 5.… letters, Mark (M) – for accents, Decimal_Number (Nd) – for digits, Connector_Punctuation (Pc) – for… [а-я] for Cyrillic letters.… The example below looks for any characters except letters, digits and spaces:… And if we need a backslash, then we use \\, and so on.
It stores the date, time and provides methods for date/time management.… For compatibility, 2 digits are also accepted and considered 19xx, e.g. 98 is the same as 1998 here,… There is getFullYear() for the year.… There are also their UTC-counterparts, that return day, month, year and so on for the time zone UTC+0… For instance, let’s get the date for “70 seconds after now”:
For instance, \d+ looks for numbers:… For instance, the pattern ou?r looks for o followed by zero or one u, and then r. So, colou?… For example, \d0* looks for a digit followed by any number of zeroes (may be many or none):… Regexp for decimal fractions (a number with a floating point): \d+\.… For instance, for HTML tags we could use a simpler regexp: <\w+>.
They can be passed around, used as objects, and now we’ll see how to forward calls between them and decorate… The idea is that we can call cachingDecorator for any function, and it will return the caching wrapper… Previously, for a single argument x we could just cache.set(x, result) to save the result and cache.get… The only syntax difference between call and apply is that call expects a list of arguments, while apply… …And for objects that are both iterable and array-like, such as a real array, we can use any of them,
For instance, we received a file with textual data.… TextDecoder object allows one to read the value into an actual JavaScript string, given the buffer and… label – the encoding, utf-8 by default, but big5, windows-1251 and… other are also supported. options – optional object: fatal – boolean, if true then throw an exception for… This options tells TextDecoder to memorize “unfinished” characters and decode them when the next chunk
Specification.The ECMA-262 specification contains the most in-depth, detailed and formalized information… But it’s not for everyday use. A new specification version is released every year.… Also, if you’re developing for the browser, then there are other specifications covered in the second… MDN (Mozilla) JavaScript Reference is the main manual with examples and other information.… q=MDN+parseInt to search for the parseInt function.
Getters and setters.Accessor properties are represented by “getter” and “setter” methods.… For instance, we have a user object with name and surname:… For accessor properties, there is no value or writable, but instead there are get and set functions.… For instance, to create an accessor fullName with defineProperty, we can pass a descriptor with get andFor instance, if we want to forbid too short names for user, we can have a setter name and keep the value
The quote is detected, and then the engine tries to find a match for the rest of the pattern… The regexp engine adds to the match as many characters as it can for .+, and then shortens that one by… Then the regular expression engine increases the number of repetitions for the dot and tries one more… Then the number of repetitions is increased again and again… …Till the match for the rest of the pattern… and ??
Each window has a window.name, and here we can specify which window to use for the popup.… for user safety reasons.… and switches elsewhere.… ads and evils pages.… Events focus and blur allow to track switching in and out of the window.
Only first 50 results are shown.