There are many tasks where recursive way of thinking gives simpler code, easier to maintain.… at line 5 }
pow(2, 3)
To calculate x * pow(x, n - 1), we need to make a subcall of pow with… Recursion can give a shorter code, easier to understand and support.… If we put 3-4 nested subloops in the code to traverse a single object, it becomes rather ugly.… Or it’s an object with N subdepartments – then we can make N recursive calls to get the sum for each
To make things easier, in this chapter, they are split into groups.… It’s similar to a string method str.slice, but instead of substrings, it makes subarrays.… The easiest way to grasp that is by example.… The latter is used more often, as it’s a bit easier to understand for most people.… But actually, that’s much easier.
Look through the cheat sheet just to be aware of them.
It also allows to trace the code step by step to see what exactly is going on.… Now you could click the same toggler again to hide the resources list and give the code some space.… It allows us to:
Quickly jump to the breakpoint in the code (by clicking on it in the right panel).… Then we can analyze variables in the debugger to see what went wrong.… Logging.To output something to console from our code, there’s console.log function.
If we want to execute more than one statement, we have to wrap our code block inside curly braces:… This example will do the same thing as the previous one:… But parentheses make the code more readable, so we recommend using them.… Code blocks which span several lines are easier to understand than a long, horizontal instruction set… Use if when you need to execute different branches of code.
So it becomes easy to fix one thing and break another one.… We need to add more use cases to it.
Let’s add one more test to check that pow(3, 4) = 81.… And besides that, there’s one more rule that’s good to follow.
One test checks one thing.… functions, and then the code becomes outdated, no one wants to get into it.… Naturally, that’s because auto-tested code is easier to modify and improve.
They are things like addition +, multiplication *, subtraction -, and so on.… That’s exactly the precedence thing.… Such tricks definitely don’t make code clearer or readable.… One line does multiple things – not good.… Sometimes, it’s used to write shorter code, so we need to know it in order to understand what’s going
JavaScript animations can handle things that CSS can’t.… make the redraw easier for the browser and hence load less CPU load and look smoother.… There’s one more thing to keep in mind.… After easeOut – it first jumps to the top, then bounces there.… We covered a lot of examples and transformations to make them even more versatile.
That’s rare, but such a thing may happen when a visitor loads outdated JavaScript code, e.g. from a proxy… We can handle things more gracefully in db.onversionchange, prompt the visitor to save the data before… functions: from 1 to 2, from 2 to 3, from 3 to 4 etc.… by step, for every intermediate version (2 to 3, then 3 to 4).… split things apart.
Our code must be as clean and easy to read as possible.… make the code more readable.… A lot of minor things.… code more readable and easier to understand?”… These are the main things to keep in mind when choosing and debating code styles.
Laozi (Tao Te Ching)
Another way to code shorter is to use single-letter variable names everywhere… And will ultimately fail to alter your well-thought code.… Laozi (Tao Te Ching)
Using similar names for same things makes life more interesting and shows… code, then Peter could use render.., and Ann – paint....… A true ninja coder will make them not obvious from the code as well.
The first thing we’ll study is the building blocks of code.… For now, just remember the result of running the code: it shows Hello, then 1, then 2.… We need to put a semicolon after alert for the code to work correctly.… It becomes necessary to add comments which describe what the code does and why.… There are many tools which minify code before publishing to a production server.
A code editor is the place where programmers spend most of their time.… There are two main types of code editors: IDEs and lightweight editors.… For Windows, there’s also “Visual Studio”, not to be confused with “Visual Studio Code”.… They are mainly used to open and edit a file instantly.… Vim and Emacs are also cool if you know how to use them.
Handlers are a way to run JavaScript code in case of user actions.… An HTML-attribute is not a convenient place to write a lot of code, so we’d better create a JavaScript… Let’s say, one part of our code wants to highlight a button on click, and another one wants to show a… to support.… Summary.There are 3 ways to assign event handlers:
HTML attribute: onclick="...".
The built-in eval function allows to execute a string of code.… Code minifiers (tools used before JS gets to production, to compress it) rename local variables into… shorter ones (like a, b etc) to make the code smaller.… Summary.A call to eval(code) runs the string of code and returns the result of the last statement.… Instead, to eval the code in the global scope, use window.eval(code).
In case of such operations, objects are auto-converted to primitives, and then the operation is carried… 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… Then "2" * 2 becomes 2 * 2 (the string is converted to number).
JavaScript was initially created to “make web pages alive”.… Then it converts (“compiles”) the script to machine code.… And then the machine code runs, pretty fast.… JavaScript is the only browser technology that combines these three things.… Modern tools make the transpilation very fast and transparent, actually allowing developers to code in
If your script may run in other environments, it’s better to use globalThis instead.… Modern scripts use JavaScript modules where such a thing doesn’t happen.… If we used let instead, such thing wouldn’t happen:… prone to errors and easier to test than if it uses outer or global variables.… To make our code future-proof and easier to understand, we should access properties of the global object
The multiline variant is a bit longer, but easier to read:… It is much easier to mistype "#FF7F00" than COLOR_ORANGE.… Name things right.Talking about variables, there’s one more extremely important thing.… When we return to some code after doing something else for a while, it’s much easier to find information… It’s only okay to use them if the context of the code makes it exceptionally obvious which data or value
It makes code support and refactoring easier.… For instance, if you import * as library from a huge code library, and then use only few methods, then… Modules provide a special export default (“the default export”) syntax to make the “one thing per module… import the same thing, and that’s not good.… “Re-export” syntax export ... from ... allows to import things and immediately export them (possibly
They allow the code to be called many times without repetition.… If that thing is big, maybe it’s worth it to split the function into a few smaller functions.… Sometimes people refer to such code as self-describing.… They structure the code and make it readable.… To make the code clean and easy to understand, it’s recommended to use mainly local variables and parameters
They are a very simple thing, worth to study once and then feel comfortable in the world of vector graphics… As t runs from 0 to 1, every value of t adds a point to the curve.… 3 → 4.… Then for each t from 0 to 1, we take a point on each segment on the distance proportional to t and connect… control points, and then as t moves from 0 to 1, for each value of t we’ll have (x,y) of the curve.
The word “async” before a function means one simple thing… And, it’s easier to read and write.… use await, so it’s a normal practice to add .then/catch to handle the final result or falling-through… The await keyword before a promise makes JavaScript wait until that promise settles, and then:
If it… Together they provide a great framework to write asynchronous code that is easy to both read and write
the value from the first case (that is, value1) then to the second (value2) and so on.… If no case is matched then the default code is executed (if it exists).… For example, if we want the same code to run for case 3 and case 5:… But for 3, the result of the prompt is a string "3", which is not strictly equal === to the… So we’ve got a dead code in case 3! The default variant will execute.
The notation here is not to be confused with object literals.… So the object has access to class methods.… make things easier to read, but doesn’t introduce anything new), because we could actually declare the… same thing without using the class keyword at all:… Bind the method to object, e.g. in the constructor.
Although, we’ll try to make things clear anyway.… Pyramid of Doom.At first glance, it looks like a viable approach to asynchronous coding.… ’s no error…
We load 2.js, then if there’s no error…
We load 3.js, then if there’s no error – do something… We can try to alleviate the problem by making every action a standalone function, like this:… That’s inconvenient, especially if the reader is not familiar with the code and doesn’t know where to
Loops are a way to repeat the same code multiple times.… The loop below runs alert(i) for i from 0 up to (but not including) 3:… the loop identical to while (i < 3).… In this case, code execution jumps to the next iteration of the labeled loop.… To make an “infinite” loop, usually the while(true) construct is used.
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… promises (just in case a non-promise was passed) with p => Promise.resolve(p), and then adds .then… handler to every one.… to return a promise.
We already saw a similar thing… To apply alternation to a chosen part of the pattern, we can enclose it in parentheses:
I love HTML|… Otherwise, if the first digit is 2, then the next must be [0-3].… The alternation | now happens to be between [01]\d and 2[0-3]:[0-5]\d.… allow [01]\d OR 2[0-3].
Then the function execution pauses, and the yielded value is returned to the outer code.… New calls to generator.next() don’t make sense any more.… …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:… The result is returned to the outer code.
Makes it easier to add/remove/move around properties, because all lines become alike.… And if we need something more complex, then we switch to square brackets.… shorthand to make it shorter.… If we’re making a site mainly for a German audience then we probably want 49 to be the first.… fix the issue with the phone codes, we can “cheat” by making the codes non-integer.
How can we code it well?
Promises provide a couple of recipes to do that.… The whole thing works, because every call to a .then returns a new promise, so that we can call the next… Sometimes it’s ok to write .then directly, because the nested function has access to the outer scope.… The code below makes a request to user.json and loads its text from the server:… That makes it possible to plan actions after it; even if we don’t plan to extend the chain now, we may
XMLHttpRequest is a built-in browser object that allows to make HTTP requests in JavaScript.… 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:… URL – the URL to request, a string, can be URL object.
async – if explicitly set to false, then the request… If we need to track uploading specifically, then we should listen to same events on xhr.upload object
To mark how many we need, we can append a quantifier.… 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:… To make a regexp more precise, we often need make it more complex
We can see one common rule… Depends on how tolerant we can be to “extra” matches and whether it’s difficult or not to remove them
It’s easier to understand by looking at an example.… All previous declarations required us, programmers, to write the function code in the script.… That’s usually a safe thing to do, because the variable is local, nothing outside the function can access… Besides, such code would be architecturally bad and prone to errors.… To pass something to a function, created as new Function, we should use its arguments.
To make clear why that’s helpful, let’s consider a task.… We need to find quoted strings: either single-quoted '...' or a double-quoted "...… To make sure that the pattern looks for the closing quote exactly the same as the opening one, we can… Similar to that, \2 would mean the contents of the second group, \3 – the 3rd group, and so on.… To reference a named group we can use \k<name>.
And also, how to pass arrays to such functions as parameters.… But of course in the result only the first two will be counted, so the result in the code above is 3.… Spread syntax to the rescue!… 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:
The easiest way to catch all errors is to append .catch to the end of chain:… The same thing is possible for promises.… And if we handle the error and finish normally, then it continues to the next closest successful .then… There’s no code to handle it.… A similar thing happens with unhandled promise rejections.
, for example, to make a short url.… If we want to call a method directly on a number, like toString in the example above, then we need to… In the middle cases 3.5 rounds up to 4, and -3.5 rounds up to -3.… But what if we’d like to round the number to n-th digit after the decimal?… Compare it to one-third: 1/3. It becomes an endless fraction 0.33333(3).
Recall generators.Now let’s recall generators, as they allow to make iteration code much shorter.… A common practice for Symbol.iterator is to return a generator, it makes the code shorter, as you can… Let’s switch to asynchronous generators to make it possible.… Async iterable range.Regular generators can be used as Symbol.iterator to make the iteration code shorter… In practice though, that would be a weird thing to do.
For instance, [a-z] is a character in range from a to z, and [0-5] is a digit from 0 to 5.… 9 or a letter from A to F.… For instance, if we’d like to look for a wordly character \w or a hyphen -, then the set is [\w-].… Similar to \w, we’re making a set of our own that includes characters with following Unicode properties… Now it’s easy to see that the range 56499-55349 is invalid: its starting code 56499 is greater than the
is to apply cachingDecorator to them.… To make it all clear, let’s see more deeply how this is passed along:
After the decoration worker.slow… For flexibility, we can allow to provide a hashing function for the decorator, that knows how to make… Then (**) uses func.call(this, ...arguments) to pass both the context and all arguments the wrapper got… one, except for one little thing.
We normally use them to describe how and why the code works.… Bad comments.Novices tend to use comments to explain “what is going on in the code”.… Seriously, the code should be easy to understand without them.… Good comments allow us to maintain the code well, come back to it after a delay and use it more effectively… Put them in only if it’s impossible to make the code so simple and self-descriptive that it doesn’t require
Here we immediately assign it to the variable, so the meaning of these code samples is the same: “create… First, the syntax: how to differentiate between them in the code.… And then we plan to use it some time later.… As a rule of thumb, when we need to declare a function, the first thing to consider is Function Declaration… That’s also better for readability, as it’s easier to look up function f(…) {…} in the code than let
A function can be created at any moment, passed as an argument to another function, and then called from… A reference to the outer lexical environment, the one associated with the outer code.… describe how things work.… When the code wants to access a variable – the inner Lexical Environment is searched first, then the… When it wants to access phrase, then there is no phrase locally, so it follows the reference to the outer
So if we click on <p>, then we’ll see 3 alerts: p → div → form.… Normally it goes upwards till <html>, and then to document object, and some events even reach window… Usually the code uses document.addEventListener('click'…) to catch all clicks.… ., true), then we should mention the same phase in removeEventListener(..., true) to correctly remove… Then the event bubbles up from event.target to the root, calling handlers assigned using on<event&
CSS animations make it possible to do simple animations without JavaScript at all.… JavaScript can be used to control CSS animations and make them even better, with little code.… Then it goes forward, a little bit farther than 400px.
And then back again – to 400px.… 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
First we’ll look at the details, and then how to use it for adding new capabilities to built-in objects… 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.… have, and we may be tempted to add them to native prototypes.… For instance, if we’re making an array-like object, we may want to copy some Array methods to it.
Taking something and dragging and dropping it is a clear and simple way to do many things, from copying… But if “take” it from its edge, then the ball suddenly “jumps” to become centered under the mouse pointer… Then while dragging we position the ball on the same shift relative to the pointer, like… We can use that code to check what element we’re “flying over” at any time.… An extended code of onMouseMove to find “droppable” elements:
Then your code will work well with both touch and mouse devices.… ;event> events with pointer<event> in our code and expect things to continue working fine with… 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.
E.g. we have a code string let varName = "value", and we need to read the variable name from… And, if it finds a match, then sets regexp.lastIndex to the index immediately after the match.… Let’s go back to our task.… We can manually set lastIndex to 4, to start the search from the given position!… The flag y makes regexp.exec to search exactly at position lastIndex, not “starting from” it.
Only first 50 results are shown.