It stores the date, time and provides methods for date/time management.… Without arguments – create a Date object for the current date and time:… We can always create a date from a timestamp using new Date(timestamp) and convert the existing Date… Date and time in JavaScript are represented with the Date object.… We can’t create “only date” or “only time”: Date objects always carry both.
Create an empty article with today’s date.
…or else somehow.… And for the second one we can make a static method of the class.… methods.Static properties and methods are inherited.… For instance, Animal.compare and Animal.planet in the code below are inherited and accessible as Rabbit.compare… As a result, inheritance works both for regular and static methods.
E.g. subtracting or comparing dates (Date objects). We’ll come across them later.… For instance, Date objects (to be covered in the chapter Date and time) can be subtracted, and the result… of date1 - date2 is the time difference between two dates.… The greater and less comparison operators, such as < >, can work with both strings and numbers… Methods toString and valueOf come from ancient times.
Updating such toString every time can become a pain.… Symbolic keys and values.… Previously, all stringified objects had no indents and extra spaces.… arrays can include other objects and arrays.… The value of meetup.date is a string, not a Date object.
A File object inherits from Blob and is extended with filesystem-related capabilities.… values.
fileName – file name string.
options – optional object:
lastModified – the timestamp (integer date… It delivers the data using events, as reading from disk may take time.… 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,
The second one has the name "age" and the value 30.… We can add, remove and read files from it at any time.… $ and _ are allowed).… So most of the time, when property names are known and simple, the dot is used.… store the information about the date and time,
Error to store the information about an error.
…and so on…
For instance, we’d like to find HTML tags <.*?>, and process them.… , the corresponding result array item is present and equals undefined.… The search is performed each time we iterate over it, e.g. in the loop.… Then the engine won’t spend time finding other 95 matches.… To look for all dates, we can add flag g.
There are many tricky things about cookies and their attributes.… Technically, name and value can have any characters.… expires=Tue, 19 Jan 2038 03:14:07 GMT
The cookie expiration date defines the time when the browser will… Such a protection takes time to implement though.… Next time when ads.com is accessed, the remote server gets the id cookie and
Much shorter than using literals every time, and also easy to read.… It can be run with new, and it will execute the algorithm above.… JavaScript provides constructor functions for many built-in language objects: like Date for dates, Set… for sets and others that we plan to study.… and Classes.
, Function and others also keep methods in prototypes.… Even functions – they are objects of a built-in Function constructor, and their methods (call/apply and… They provide the methods and disappear.… Values null and undefined have no object wrappers
Special values null and undefined stand… And there are no corresponding prototypes either.
and so on.… Example: “time-formatted”.For example, there already exists <time> element in HTML, for date/time… Let’s create <time-formatted> element that displays the time in a nice, language-aware format:… …and re-renders the element.
At the end, we can easily make a live timer.… For instance, inner elements can dispatch events like initialized, and outer ones can listen and react
JavaScript can send network requests to the server and load new information whenever it’s needed.… …And all of that without reloading the page!… The fetch() method is modern and versatile, so we’ll start with it.… The JSON format is used most of the time.… In the next chapters we’ll see more options and use cases of fetch.
One of the ways – use similar variable names, like date and data.
Mix them where you can.… And when there’s a typo… Ummm… We’re stuck for long, time to drink tea.… Note how much more interesting and diverse the code became.
…And now the hat trick!… And also where it comes from.… time.
A Proxy object wraps another object and intercepts operations, like reading/writing properties and others… They are described in the article Private and protected properties and methods.… And very simple to implement.… Built-in objects: Internal slots.Many built-in objects, for example Map, Set, Date, Promise and others… object and the proxy.
and have no database, and also for version 1, for upgrades.… And it can’t be both version 1 and 2.… And then we can do updates depending on what exists and what doesn’t.… , and we fail to do the 2nd.… closed at that time.
Our code must be as clean and easy to read as possible.… and human-readable.… Most of time, the second variant is preferred.… and “What can help us avoid errors?”… trends and best practices.
That’s why dates have access to generic object methods.… Overriding a method.Now let’s move forward and override a method.… And we’ll get an error.… And that’s what we naturally expect.… It goes up from rabbit and takes the method from animal.
When the user moves and then removes a finger, we get pointermove and pointerup events with the same… And then the surprise happens!… Now we can add the code to actually move the ball, and our drag’n’drop will work for mouse devices and… It’s time to see a real-life example.… For drag’n’drops and complex touch interactions that the browser may decide to hijack and handle on its
It can do everything: insert, remove and replace elements.… methods arr.indexOf and arr.includes have the similar syntax and do essentially the same as their string… uses the more up-to-date comparison algorithm internally.… On the 3rd run, sum = 3 and we add one more element to it, and so on…
The calculation flow:… at the cheat sheet and find the right method.
New proposals to the language appear regularly, they are analyzed and, if considered worthy, are appended… to the list at https://tc39.github.io/ecma262/ and then progress to the specification.… It can parse (“read and understand”) modern code and rewrite it using older syntax constructs, so that… A transpiler would analyze our code and rewrite height ?? 100 into (height !… It “fills in” the gap and adds missing implementations.
And here sayHi() runs the function, and the result of its execution is passed to setTimeout.… 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,… Each call remembers the real time from the previous one in the times array.… That limitation comes from ancient times and many scripts rely on it, so it exists for historical reasons
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… It sometimes happens that a property must be set at creation time only, and then never modified.… But most of the time get...… We can have both private #waterAmount and public waterAmount fields at the same time.
It also saves memory and time in case of reusing cached objects.… In order not to complicate our work, and not to notify third-party code every time our DOM-element is… In this case, the logger stops displaying messages and clears the timer.… again:
But this time not all images were downloaded from the network, and one… more, by replacing one of the images again and creating a new collage:
This time
Let’s say we have a string like +7(903)-123-45-67 and want to find all numbers in it.… A quantifier is appended to a character (or a character class, or a [...] set etc) and specifies how… The range: {3,5}, match 3-5 times
To find numbers from 3 to 5 digits we can put the limits into curly… r looks for o followed by zero or one u, and then r.
So, colou?… That is, the character may repeat any times or be absent.
JavaScript can modify both classes and style properties.… That’s more flexible and easier to support.
className and classList.Changing a class is one of the most… infers style.marginLeft and style.marginTop from it.… The browser takes the computed value and makes all units fixed and absolute, for instance: height:20px… values are much more convenient, and the standard changed.
; and her "broom".… , the engine doesn’t try to match a dot one more time, but stops and tries to match the rest of the pattern… time:
Failure again.… and ??… There are times when we need one or another.
There may be any pattern instead of X and Y.… If it’s not so, then the potential match is skipped, and the search continues.… In other words, such pattern means that we’re looking for X followed by Y and Z at the same time.… =\s), and there’s 30 somewhere after it (?… , so we know where exactly in the text it is, and can check the context.
When the time is due for a scheduled setTimeout, the task is to run its callback.
…and so on.… It doesn’t matter if the task takes a long time.… …and so on.… There’s not much difference in the overall counting time.… And its overall execution time isn’t much longer.
And the optimization may be unneeded and totally not worth the efforts.… And they, potentially, can split even more.… if the array is big, it takes time.… But in the list we need to start from the first item and go next N times to get the Nth element.… But for many tasks a recursive solution is fast enough and easier to write and support.
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”… Slashes are used when we know the regular expression at the code writing time – and that’s the most common… A regular expression consists of a pattern and optional flags: g, i, m, u, s, y.
Loops are a way to repeat the same code multiple times.… 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.… , while it’s truthy, execute it again and again.… body
alert(i)
Runs again and again while the condition is truthy.
from the chapter Garbage collection, JavaScript engine keeps a value in memory while it is “reachable” and… It occupies memory and may not be garbage collected.… , and then just takes it from cache.… Like Set, it supports add, has and delete, but not size, keys() and no iterations.… WeakSet is the absence of iterations, and the inability to get all current content.
Export and import directives have several syntax variants.… It makes code support and refactoring easier.… modules together and optimize them to speedup loading.… Summary.Here are all types of export that we covered in this and previous articles.… Or at the right time? Like, load a module upon request, when it’s really needed?
Getters and setters.Accessor properties are represented by “getter” and “setter” methods.… It is readable and writable.… the access is done via getter and setter.… a setter and tweak its behavior.… We can try to find all such places and fix them, but that takes time and can be hard to do if that code
The caret ^ and dollar $ characters have special meaning in a regexp. They are called “anchors”.… The caret ^ matches at the beginning of the text, and the dollar $ – at the end.… Let’s check whether or not a string is a time in 12:34 format.… That is: two digits, then a colon, and then another two digits.… Anchors have “zero width”
Anchors ^ and $ are tests. They have zero width.
And asynchronous generators make it even more convenient.… It calls range[Symbol.asyncIterator]() once, and then its next() for values.… Most of the time, when we’d like to make an iterable, we’ll use generators.… Then we can use that link for the next request, to get more commits, and so on.… Summary.Regular iterators and generators work fine with the data that doesn’t take time to generate.
Popups exist from really ancient times.… and switches elsewhere.… ads and evils pages.… Methods focus() and blur() allow to focus/unfocus a window. But they don’t work all the time.… Events focus and blur allow to track switching in and out of the window.
They can be passed around, used as objects, and now we’ll see how to forward calls between them and decorate… …And for objects that are both iterable and array-like, such as a real array, we can use any of them,… Because we are calling hash(arguments), and arguments object is both iterable and array-like, but not… Append glue and this[1].
Append glue and this[2].
…Do so until this.length items are glued.… E.g. a decorator may count how many times a function was invoked and how much time it took, and expose
How do we find the width and height of the browser window?… How do we get the full width and height of the document, including the scrolled out part?… But there are additional methods and peculiarities to consider.… These inconsistencies come from ancient times, not a “smart” logic.… If it occupied some space, then that space is now free and the content “jumps” to fill it.
And it may be a better choice for such task.… down, and then keyup – when it’s released.
event.code and event.key.The key property of the event object… The event.key is exactly the character, and it will be different.… triggers again and again, and then when it’s released we finally get keyup.… The browser opens the “Save Page” dialog (Ctrl+S)
…and so on.
…and so on.
In this chapter we’ll learn how to do the same.… And also, how to pass arrays to such functions as parameters.… And it still works, we can find it in the old code.… And that would get ugly.
Spread syntax to the rescue!… and iterables.
The underlying Range and Selection objects are easy to grasp, and then you’ll need no recipes to make… lt;b> and 3.… We’ve already seen setStart and setEnd, here are other similar methods.… Optional arguments start and end, if provided, set the range start and end, otherwise user selection… For input, textarea: additional methods and properties.
And so on upwards till the document object.… Normally it goes upwards till <html>, and then to document object, and some events even reach window… Don’t stop it without a real need: obvious and architecturally well thought out.… And there’s a logical explanation for that.… top element that handles general concepts and runs the last one.
When the browser loads the page, it “reads” (another word: “parses”) the HTML and generates DOM objects… But technically no one limits us, and if there aren’t enough, we can add our own.… The attributes collection is iterable and has all the attributes of the element (standard and non-standard… ) as objects with name and value properties.… What if we use a non-standard attribute for our purposes and later the standard introduces it and makes
That’s why Map and Set also exist.… So we should use map methods: set, get and so on.
Map can also use objects as keys.… 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.… But this may help to replace Map with Set in certain cases with ease, and vice versa.
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… …And then decode:
input – BufferSource… This options tells TextDecoder to memorize “unfinished” characters and decode them when the next chunk
For instance, [a-z] is a character in range from a to z, and [0-5] is a digit from 0 to 5.… similar characters,
Join_Control (Join_C) – two special codes 200c and 200d, used in ligatures, e.g.… Unicode properties are covered in more details in the article Unicode: flag "u" and class \… They are denoted by a caret character ^ at the start and match any character except the given ones.… And if we need a backslash, then we use \\, and so on.
Specification.The ECMA-262 specification contains the most in-depth, detailed and formalized information… MDN (Mozilla) JavaScript Reference is the main manual with examples and other information.… To see their support among browser-based and other engines, see:
https://caniuse.com – per-feature tables… caniuse.com/#feat=cryptography.
https://kangax.github.io/compat-table – a table with language features and
If the regexp doesn’t have flag g, then it returns the first match as an array with capturing groups and… 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:
And, as it happens with strings, that may lead to odd results.… We’ll see that a bit later, in the article Sets and ranges [...].… And Number property means that it’s a digit: maybe Arabic or Chinese, and so on.… …And so on.… and {n} we’ll see how to look for numbers that contain many digits.
Only first 50 results are shown.