If no case is matched then the default code is executed (if it exists).… Then 4. That’s a match, so the execution starts from case 4 until the nearest break.… But for 3, the result of the prompt is a string "3", which is not strictly equal === to the… number 3.… So we’ve got a dead code in case 3! The default variant will execute.
We already saw a similar thing… Otherwise, if the first digit is 2, then the next must be [0-3].… If we glue hours and minutes together, we get the pattern: [01]\d|2[0-3]:[0-5]\d.… The alternation | now happens to be between [01]\d and 2[0-3]:[0-5]\d.… Let’s correct that by enclosing “hours” into parentheses: ([01]\d|2[0-3]):[0-5]\d.
They are a very simple thing, worth to study once and then feel comfortable in the world of vector graphics… There may be 2, 3, 4 or more.… In the demo above they are labeled: 1, 2, 3.
Build segments between control points 1 → 2 → 3.… 3 → 4.… There will be 3 brown segments.
numbers are widely used in JavaScript to represent colors, encode characters, and for many other things… 4
3
3
3.5
3
4
4
3
3.6
3
4
4
3
-1.1
-2
-1
-1
-1
-1.5
-2
-1
-1
-1
-1.6
-2
-1
-2
-1
These functions… Compare it to one-third: 1/3. It becomes an endless fraction 0.33333(3).… The funny thing
Try running this:… more reliable for two edge cases:
It works with NaN: Object.is(NaN, NaN) === true, that’s a good thing
Let’s see what happens during the pow(2, 3) call.
pow(2, 3).In the beginning of the call pow(2, 3) the… We can sketch it as:
Context: { x: 2, n: 3, at line 1 }
pow(2, 3)
That’s when the function… Then the previous context is restored:
Context: { x: 2, n: 3, at line 5 }
pow(2, 3)
When… it finishes, we have a result of pow(2, 3) = 8.… The recursion depth in this case was: 3.
The range: {3,5}, match 3-5 times
To find numbers from 3 to 5 digits we can put the limits into curly… Then a regexp \d{3,} looks for sequences of digits of length 3 or more:… r looks for o followed by zero or one u, and then r.
So, colou?… The regexp looks for character '<' followed by one or more Latin letters, and then
When an event happens on an element, it first runs the handlers on it, then on its parent, then all the… Then on the outer <div>.
Then on the outer <form>.… So if we click on <p>, then we’ll see 3 alerts: p → div → form.… Then handlers are called on the target element itself.… recommended, because we can’t really be sure we won’t need it above, maybe for completely different things
They are things like addition +, multiplication *, subtraction -, and so on.… That’s exactly the precedence thing.… One line does multiple things – not good.… Then, 3 + 4 is evaluated and returned as the result.… Without them: a = 1 + 2, 3 + 4 evaluates + first, summing the numbers into a = 3, 7, then the assignment
If yes, then all right, go on with XMLHttpRequest. Otherwise, please head on to Fetch.… To do the request, we need 3 steps:
Create XMLHttpRequest:… → … → 3 → 4.… State 3 repeats every time a data packet is received over the network.… Or, if we like JSON more, then JSON.stringify and send as a string.
To make things easier, in this chapter, they are split into groups.… elements, we can see that arr.length == 3.… In real life, arrays of objects are a common thing… If it is provided, then the extra elements are ignored.… the third call
3
3
6
the fourth call
6
4
10
the fifth call
10
5
15
Here we can clearly see how
Then groups, numbered from left to right by an opening paren.… Then in result[2] goes the group from the second opening paren ([a-z]+) – tag name, then in result[3]… The array length is permanent: 3.… Just like match, it looks for matches, but there are 3 differences:
It returns not an array, but an… Then the engine won’t spend time finding other 95 matches.
For instance, the Promise.all below settles after 3 seconds, and then its result is an array [1, 2, 3… A common trick is to map an array of job data into an array of promises, and then wrap that into Promise.all… adds .then handler to every one.… If all of the given promises are rejected, then the returned promise is rejected with AggregateError… We can always use .then after loadCached. That’s the purpose of Promise.resolve in the line (*).
It has 3 modes:
If the regexp doesn’t have flag g, then it returns the first match as an array with… If the regexp has flag g, then… There are 3 differences from match:
It returns an iterable object with matches instead of an array.… If there are no parentheses in the regexp, then there are only 3 arguments: func(str, offset, input).… If there’s no g, then regexp.exec(str) returns the first match exactly as str.match(regexp).
Although, we’ll try to make things clear anyway.… Then callback(err) is called.… Then callback(null, result1, result2…) is called.… if there’s no error…
We load 2.js, then if there’s no error…
We load 3.js, then if there’s no error… It does the same thing, and there’s no deep nesting now because we made every action a separate top-level
First we’ll look at the details, and then how to use it for adding new capabilities to built-in objects… For instance, when we create an array [1, 2, 3], the default new Array() constructor is used internally… Here’s the overall picture (for 3 built-ins to fit):
Let’s check… Primitives.The most intricate thing happens with strings, numbers and booleans.… We may then implement it manually and populate the built-in prototype with it.
Sets.For instance, [eao] means any of the 3 characters: 'a', 'e', or 'o'.
That’s called a set.… The pattern searches for:
V,
then… one of the letters [oi],
then la.… For instance, if we’d like to look for a wordly character \w or a hyphen -, then the set is [\w-].… And if we need a backslash, then we use \\, and so on.
For instance, the loop below outputs i while i < 3:… The loop will first execute the body, then… condition
i < 3
Checked before every loop iteration. If false, the loop stops.… That is, begin executes once, and then… Summary.We covered 3 types of loops:
while – The condition is checked before each iteration.
do..while
The similar thing holds true for for and while loops:… It can then be used somewhere else.… Understanding such things is great for the overall knowledge of JavaScript and beneficial for more complex… specification object: it only exists “theoretically” in the language specification to describe how things… Step 3.
So it becomes easy to fix one thing and break another one.… BDD is three things in one: tests AND documentation AND examples.… Here it checks that the result of pow(2, 3) equals 8.… Let’s add one more test to check that pow(3, 4) = 81.… One test checks one thing.
If both strings end at the same length, then they are equal.… The same thing… Now let’s see some funny things that happen when we apply these rules.… That’s why (3) null >= 0 is true and (1) null > 0 is false.… Actually, these tricky things will gradually become familiar over time, but there’s a solid way to avoid
But of course in the result only the first two will be counted, so the result in the code above is 3.… So when we need these features, then rest parameters are preferred.… Now let’s say we have an array [3,… It is possible to do the same thing with the spread syntax.… Note that it is possible to do the same thing to make a copy of an object:
As we can see, the pattern found an opening quote ", then… Similar to that, \2 would mean the contents of the second group, \3 – the 3rd group, and so on.… : in the group, then we can’t reference it. Groups that are excluded from capturing (?
That’s rare, but such a thing may happen when a visitor loads outdated JavaScript code, e.g. from a proxy… …In other words, here we do two things:
The db.onversionchange listener informs us about a parallel… We can handle things more gracefully in db.onversionchange, prompt the visitor to save the data before… by step, for every intermediate version (2 to 3, then 3 to 4).… workaround is the same as when working with native IndexedDB: either make a new transaction or just split things
mousemove
Every mouse move over an element triggers that event.
click
Triggers after mousedown and then… For instance, a left-button click first triggers mousedown, when the button is pressed, then mouseup… possible values:
event.which == 1 – left button,
event.which == 2 – middle button,
event.which == 3… So if we want to support combinations like Ctrl+click, then for Mac it makes sense to use Cmd+click.… But if their device doesn’t have it – then there should be a way to live without modifier keys.
Iteration over Map.For looping over a map, there are 3… Set is just the right thing for that:… Note the funny thing… The callback function passed in forEach has 3 arguments: a value, then the same value valueAgain, and… then the target object.
read about new bleeding-edge features, including those that are “almost standard” (so-called “stage 3”… Also, if you’re developing for the browser, then there are other specifications covered in the second
But then the call str.match(/\w+/g) will look for all words in the text, while we need one word at position… And, if it finds a match, then sets regexp.lastIndex to the index immediately after the match.… Please note: the regexp.exec call starts searching at position lastIndex and then goes further.… If there’s no word at position lastIndex, but it’s somewhere after it, then it will be found:… As we can see, regexp /\w+/y doesn’t match at position 3
In practice though, things are a bit simpler.… Still, it’s important to know about all 3 hints, soon we’ll see why.… A conversion can return any primitive type.The important thing to know about all primitive-conversion… The only mandatory thing: these methods must return a primitive, not an object.… Then "2" * 2 becomes 2 * 2 (the string is converted to number).
Then we get that text in the result.… Or they can cancel the input by pressing Cancel or hitting the Esc key, then we get null as the result… Summary.We covered 3
called, it runs the execution until the nearest yield <value> statement (value can be omitted, then… Then the function execution pauses, and the yielded value is returned to the outer code.… We should see it from done:true and process value:3 as the final result.… …But please note: the example above shows 1, then 2, and that’s all. It doesn’t show 3!… To make things more obvious, here’s another example, with more calls:
So if DOMContentLoaded is postponed by long-loading scripts, then autofill also awaits.… You can try it by running this code and then reloading the page:… There are 3 possible values:
"loading" – the document is loading.… These two things actually mean the same.
document.readyState becomes complete when all resources (iframe… unload event on window triggers when the user is finally leaving, in the handler we can only do simple things
b is:
if a is defined, then a,
if a isn’t defined, then b.
In other words, ??… If any of these is the first argument of ||, then we’ll get the second argument as the result.… does just the right thing.
Precedence.The precedence of the ?? operator is the same as ||.… They both equal 3 in the MDN table.… Otherwise, if we omit parentheses, then
Will it start slowly and then go fast, or vice versa.… Then it goes forward, a little bit farther than 400px.
And then back again – to 400px.… If we put y values like -99 and 99 then the train would jump out of the range much more.… Select the Elements tab, then pay attention to the Styles sub-panel at the right side.… Limitations of CSS animations compared to JavaScript animations:
MeritsSimple things done
The special thing about FormData is that network methods, such as fetch, can accept a FormData object… The difference is that .set removes all fields with the given name, and then appends a new field.… either create new FormData(form) from an HTML form, or create an object without a form at all, and then… To send a file, 3-argument syntax is needed, the last argument is a file name, that normally is taken
Here’s what should show up:
The Sources panel has 3 parts:
The… Console.If we press Esc, then a console opens below.… For example, here 1+2 results in 3, while the function call hello("debugger") returns nothing… The execution is then paused immediately after that function call.… Then we can analyze variables in the debugger to see what went wrong.
Selecting the text partially.The interesting thing is that the first argument node in both methods can… If node is a text node, then offset must be the position in its text.… In other words, when the mouse button is pressed, and then it moves forward in the document, then its… The same thing… Then it’s exactly the cursor position.
Here the flow is:
The initial promise resolves in 1 second (*),
Then the .then handler is called (**… The whole thing works, because every call to a .then returns a new promise, so that we can call the next… .then on it.… That handler is in the line (**), it shows 2 and does the same thing.… handler in line (*): if it has a callable method named then, then it calls that method providing native
We can replace mouse<event> events with pointer<event> in our code and expect things… Multi-touch.One of the things that mouse events totally don’t support is multi-touch: a user can touch… We need to do two things:
Prevent native drag’n’drop from happening:
We can do this by setting ball.ondragstart… Then our code will start working on touch devices.… Pointer capturing events.There’s one more thing to mention here, for the sake of completeness.
Note that \n is a single “special” character, so the length is indeed 3.… If pos is negative, then it’s counted from the end of the string.… If there is no second argument, then… Capital characters go first, then a few special ones, then lowercase characters, and Ö near the end of… There are 3 types of quotes.
The condition is evaluated: if it’s truthy then… This example will do the same thing as the previous one:… see that it’s just an ordinary sequence of tests:
The first question mark checks whether age < 3.
There’s a great rule about that: “if the code is so unclear that it requires a comment, then maybe it… have a long “code sheet” like this:
Then… Also, there are tools like JSDoc 3 that can generate HTML-documentation from the comments.… You think: “How stupid I was then, and how much smarter I’m now”, and rewrite using the “more obvious
When we have a form, then any element is available in the named collection form.elements.… That also works, but there’s a minor issue: if we access an element, and then change its name, then it… select and option.A <select> element has 3 important properties:
select.options – the collection… parameters:
text – the text inside the option,
value – the option value,
defaultSelected – if true, then… selected HTML-attribute is created,
selected – if true, then the option is selected.
They both call func with arguments 1, 2 and 3.… Here we use a simple “joining” function that turns arguments (3, 5) into the key "3,5".… properties.It is generally safe to replace a function or a method with a decorated one, except for one little thing… If the original function had properties on it, like func.calledCount or whatever, then the decorated… E.g. in the example above if slow function had any properties on it, then cachingDecorator(slow) is a
of these three notations:
\xXX
XX must be two hexadecimal digits with a value between 00 and FF, then… \uXXXX
XXXX must be exactly 4 hex digits with the value between 0000 and FFFF, then \uXXXX is the character… are also detectable by their codes: if a character has the code in the interval of 0xd800..0xdbff, then… For instance, if we append a character “dot below” (code \u0323), then we’ll have “S with dots above… It’s funny that in our situation normalize() actually brings together a sequence of 3 characters to one
To make things clear, the <iframe> is half-transparent (in real evil pages it’s fully transparent… Technically, if we have a text field to hack, then we can position an iframe in such a way that text… But then there’s a problem.… In action:
Resultiframe.htmlindex.htmlSandbox attribute.One of the things restricted by the sandbox attribute… The header may have 3 values:
DENY
Never ever show the page inside a frame.
JavaScript animations can handle things that CSS can’t.… If we run them separately, then even though each one has setInterval(..., 20), then the browser would… There’s one more thing to keep in mind.… First we “pull the bowstring”, and then “shoot”.… It falls down, then bounces back a few times and stops.
Logical operators
Logical AND && and OR || perform short-circuit evaluation and then return… b is a unless it’s null/undefined, then b.… We covered 3 types of loops:
The… If there’s no return statement, then the result is undefined.
And then we can use it everywhere.… created and connected to DOM first, and then <inner>.… setTimeout triggers first, and then the inner one.… If needed, we can implement such thing on our own.… But such things can be important.
In this chapter we first cover theoretical details about how things work, and then see practical applications… Sleep until a task appears, then go to 1.… It may happen that a task comes while the engine is busy, then it’s enqueued.… The notable thing is that both variants – with and without splitting the job by setTimeout – are comparable… An important thing, right?
It has 3 working modes:
If the regular expression has flag g, it returns an array of all matches:… 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 groups
$<name
Only first 50 results are shown.