Search results

should be accessible from outside the current module. import allows the import of functionality from… In other words, with modules we use import/export instead of relying on global variables.… Further imports use the module.… Modules without any path are called “bare” modules. Such modules are not allowed in import.… Build a single file with all modules (or multiple files, that’s tunable), replacing native import calls
First, we can’t dynamically generate any parameters of import.… But how can we import a module dynamically, on-demand?… The import() expression.The import(module) expression loads the module and returns a promise that resolves… into a module object that contains all its exports.… So we can’t copy import to a variable or use call/apply with it. It’s not a function.
Imagine, we’re writing a “package”: a folder with a lot of modules, with some of the functionality exported… Import: Importing named exports: import {x [as y], ...} from "module" Importing the default… export: import x from "module" import {default as x} from "module" Import all… : import * as obj from "module" Import the module (its code runs), but do not assign any… of its exports to variables: import "module" We can put import/export statements at the
The function loads a script with the given src, and then calls callback(err) in case of an error, or… when the load is successful, and rejects with the error otherwise.… Here, promisify assumes that the original function expects a callback with exactly two arguments (err… But what if the original f expects a callback with more arguments callback(err, res1, res2, ...)?… There are also modules with a bit more flexible promisification functions, e.g. es6-promisify.
In the modern HTML standard there’s a section about Drag and Drop with special events such as dragstart… Then on mousemove move it by changing left/top with position:absolute.… Here’s an example in action: Try to drag’n’drop with the mouse and you’ll see such behavior… It runs automatically and conflicts with ours.… In action: Another important aspect – we track mousemove on document, not on ball.
see the current state of support for language features is https://compat-table.github.io/compat-table/es6with the babel-loader plugin.… show the current state of support for various features: https://compat-table.github.io/compat-table/es6… Google Chrome is usually the most up-to-date with language features, try it if a tutorial demo fails.… Most tutorial demos work with any modern browser though.
Now we have a working initial implementation with tests.… Chai – the library with many assertions.… The <script> with the function to test, in our case – with the code for pow.… So let’s continue with the second variant.… If the project is covered with tests, there’s just no such problem.
In a browser, global functions and variables declared with… Function declarations have the same effect (statements with… Modern scripts use JavaScript modules where such a thing doesn’t happen.… If a value is so important… In-browser, unless we’re using modules, global functions and variables declared with var become a property
Or, maybe, everything is all right with the site, but the response is not valid JSON.… In the example below we see the other situation with .catch.… In practice, just like with regular unhandled errors in code, it means that something has gone terribly… The script dies with a message in the console.… A similar thing happens with unhandled promise rejections.
There’s a special syntax to work with promises in a more comfortable fashion, called “async/await”.… Async functions.Let’s start with the async keyword.… The function execution “pauses” at the line (*) and resumes when the promise settles, with… just fine, when we’re inside a module.… We’ll cover modules in article Modules, introduction.
You need to explicitly enable them with a special directive: "use strict".… One could recommend to start scripts with "use strict"… But you know what’s cool?… Modern JavaScript supports “classes” and “modules” – advanced language structures (we’ll surely get to… Later, when your code is all in classes and modules, you may omit it.
For server-side environments (like Node.js), you can execute the script with a command like "node… Now, it can be used for JavaScript modules.… But that’s an advanced topic, we’ll talk about modules in another part of the tutorial.… A script in an external file can be inserted with <script src="path/to/script.js"><… There is much more to learn about browser scripts and their interaction with the webpage.
When the regexp engine (program module that implements searching for regexps) comes across \b, it checks… We can use \b not only with words, but with digits as well.
Please note: For our own scripts we could use JavaScript modules here, but they are not widely… Important: Events onload/onerror track only the loading itself.… So even if we have a subdomain, or just another port, these are different origins with no access to each… the header Access-Control-Allow-Origin with * or our origin.… use-credentials" – access allowed if the server sends back the header Access-Control-Allow-Origin with
Long polling is the simplest way of having persistent connection with server, that doesn’t use any specific… Even if there are no messages, the server is bombed with requests every 10 seconds, even if the user… When a message appears – the server responds to the request with it.… work with many pending connections.… and can install modules): Resultbrowser.jsserver.jsindex.htmlBrowser code is in browser.js.
simple: long, long time ago JavaScript was a much weaker language, many things could only be done with… If someone is using it, there’s a good chance they can replace it with a modern language construct or… a JavaScript Module.
Creation.To create a new Date object call new Date() with one of the following arguments: new Date()… new Date(milliseconds) Create a Date object with… new Date(year, month, date, hours, minutes, seconds, ms) Create the date with the given components in… The month count starts with 0 (Jan), up to 11 (Dec).… Date and time in JavaScript are represented with the Date object.
As we know from the chapter Code structure, comments can be single-line: starting with // and multiline… What’s written is important.… But what’s not written may be even more important to understand what’s going on.… Comments that explain the solution are very important.… Important solutions, especially when not immediately obvious.
It responds with “Hello from server, John”, then waits 5 seconds and closes the connection.… But the Origin header is important, as it allows the server to decide whether or not to talk WebSocket… with this website.… In the browser, we directly work only with text or binary frames.… Other platforms also have their means to work with WebSocket.
Scripts with defer always execute when the DOM is ready (but before DOMContentLoaded event).… But it has important differences in the behavior.… Here’s an example similar to what we’ve seen with defer: two scripts long.js and small.js, but now with… Dynamic scripts.There’s one more important way of adding a script to the page.… So the user can read page content and get acquainted with the page immediately.
Currying is an advanced technique of working with functions.… Then this wrapper is called with 2 as an argument, and it passes the call to the original sum.… For instance, we have the logging function log(date, importance, message) that formats and outputs the… current logs: Now logNow is log with… (date, importance)).
important, for such properties, local styles take precedence.… important) can be overridden by the document.… Styling slotted content.Now let’s consider the situation with slots.… But just as we expose methods to interact with our component, we can expose CSS variables (custom CSS… important. Then local styles have precedence. CSS custom properties pierce through shadow DOM.
If you’re not familiar with these methods, and their usage in the examples is confusing, you may want… There are other real-world examples of asynchronous actions, e.g. loading scripts and modules (we’ll… Take a look at the function loadScript(src), that loads a script with the given src:… It inserts into the document a new, dynamically created, tag <script src="…"> with… That’s inconvenient, especially if the reader is not familiar with the code and doesn’t know where to
A mixin example.The simplest way to implement a mixin in JavaScript is to make an object with useful… An important feature of many browser objects (for instance) is that they can generate events.… The name argument is a name of the event, optionally followed by additional arguments with event data… Also the method .on(name, handler) that adds handler function as the listener to events with the given… It will be called when an event with the given name triggers, and get the arguments from the .trigger
First, we create an observer with a callback-function:… a DOM node: config is an object with… For example, here’s a <div> with a contentEditable attribute.… And what if the content is loaded by a third-party module?… A demo-element with id="highlight-demo", run the code above to observe it.
As we already know from the chapter Constructor, operator "new", new function can help with… Then use new MyClass() to create a new object with… The constructor runs with the given argument and assigns it to this.name.… The notation here is not to be confused with object literals.… Still, there are important differences.
Important: To scroll the page with JavaScript, its DOM must be fully built.… For instance, if we try to scroll the page with a script in <head>, it won’t work.… The upper edge of the element will be aligned with the window top.… The bottom edge of the element will be aligned with the window bottom.… we want the visitor to interact with that message, not with the document.
Mouseout when leaving for a child.An important feature of mouseout – it triggers, when the pointer moves… Please note another important detail of event processing.… But there are two important differences: Transitions inside the element, to/from descendants, are not… So we can’t use event delegation with them.… Here’s the full example with all details: Resultscript.jsstyle.cssindex.htmlTry to move the cursor in
That’s an important limitation: the result of obj1 + obj2 (or another math operation) can’t be another… So, because we can’t technically do much here, there’s no maths with objects in real projects.… When it happens, with rare exceptions, it’s because of a coding mistake.… For instance, binary plus + can work both with strings (concatenates them) and numbers (adds them).… Still, it’s important to know about all 3 hints, soon we’ll see why.
The moment of losing the focus (“blur”) can be even more important.… There are important peculiarities when working with focus events.… That is, when we switch elements, elements with tabindex=0 go after elements with tabindex ≥ 1.… To make an element a part of the form on par with <input>.… with :focus.
And there’s an object with methods save, load, search… How to match them?… Not buttons, but the general approach is important here.… There can be as many attributes with data-counter as we want.… A click on an element with the attribute data-toggle-id will show/hide the element with the given id:… DOM modifications: we can mass add/remove elements with innerHTML and the like.
article we’ll learn more about different types of comparisons, how JavaScript makes them, including important… Comparison with null and undefined.There’s a non-intuitive behavior when null or undefined are compared… And, what’s more important, how to not fall into a trap with them.… them: Treat any comparison with undefined/null except the strict equality === with exceptional care… Don’t use comparisons >= > < <= with a variable which may be null/undefined, unless you’re
Understanding how event loop works is important for optimizations, and sometimes for the right architecture… The general algorithm of the engine: While there are tasks: execute them, starting with the oldest… When the engine browser is done with the script, it handles mousemove event, then setTimeout handler,… So after some time, it raises an alert like “Page Unresponsive”, suggesting killing the task with the… An important thing, right?
Let’s start with a primitive, such as a string.… We may think of an object variable, such as user, like a sheet of paper with the address of the object… When we perform actions with the object, e.g. take a property user.name, the JavaScript engine looks… Now here’s why it’s important.… same object: As you can see, there’s still one object, but now with
In this article we’ll cover various methods that work with regexps in-depth. str.match(regexp).The method… That’s an important nuance. If there are no matches, we don’t get an empty array, but null.… It’s used mainly to search for all matches with all groups.… With g flag, it works the same as replace.… Let’s replace flag g with y in the example above.
That’s an important difference of inheritance between built-in objects compared to what we get with extends
function: The function is created with… Here’s a function with two arguments:… And here there’s a function without arguments, with… Our new function needs to interact with the main script.… If new Function had access to outer variables, it would have problems with minifiers.
Naturally, such a string should include all important properties.… Please note that a JSON-encoded object has several important differences from the object literal: Strings… The important… key, value). space Amount of space to use for formatting Most of the time, JSON.stringify is used with… Here space = 2 tells JavaScript to show nested objects on multiple lines, with indentation of 2 spaces
Before we get into JavaScript’s ways of dealing with styles and classes – here’s an important rule.… The elem.classList is a special object with methods to add/remove/toggle a single class.… The result is an object with styles, like elem.style, but now with respect to all CSS classes.… To change the styles: The style property is an object with camelCased styles.… To see how to apply important and other rare stuff – there’s a list of methods at MDN.
Remember, new objects can be created with a constructor function, like new F().… It sounds something similar to the term “prototype”, but here we really mean a regular property with… The default "prototype" is an object with the only property constructor that points back to… But probably the most important thing about "constructor" is that… …JavaScript itself does… What happens with it later – is totally on us.
The result of await reader.read() call is an object with… Please note: Streams API also describes asynchronous iteration over ReadableStream with for… s some code to do that: We create chunksAll = new Uint8Array(receivedLength) – a same-typed array with… Replace steps 4 and 5 with a single line that creates a Blob from all chunks:… Once again, please note, that’s not for upload progress (no way now with fetch), only for download progress
The DOM allows us to do anything with elements and their contents, but first we need to reach the corresponding… All operations on the DOM start with the document object. That’s the main “entry point” to DOM.… DOM collections are live Almost all DOM collections with minor exceptions are live.… With the one exception of document.documentElement:… We’ll look at them later when we start working with forms.
Once a custom element is defined, we can use it on par with built-in HTML elements.… That’s done by making a class with special methods.… Such “undefined” elements can be styled with CSS selector :not(:defined).… That leads to important consequences for custom elements.… But such things can be important.
A File object inherits from Blob and is extended with filesystem-related capabilities.… Please note: The input may select multiple files, so input.files is an array-like object with… FileReader.FileReader is an object with the sole purpose of reading data from Blob (and hence File too… , reading complete. abort – abort() called. error – error has occurred. loadend – reading finished with… Just as we did with blobs, we can create a short url with URL.createObjectURL(file) and assign it to
The important difference between them is that: || returns the first truthy value. ??… In practice, the zero height is often a valid value, that shouldn’t be replaced with the default.… with && or ||.Due to safety reasons, JavaScript forbids using ??… together with && and || operators, unless the precedence is explicitly specified with parentheses… It’s forbidden to use it with || or && without explicit parentheses.
Writing lexical analyzers is a special area, with its own tools and algorithms, so we don’t go deep in… Such use of regexp.exec is an alternative to method str.matchAll, with… Here’s the same search with flag y:… Not only that’s what we need, there’s an important performance gain when using flag y.… more time than the search with flag y, that checks only the exact position.
It’s not important. Many experienced developers live fine without knowing it.… Then the method is immediately called with parentheses (). But it doesn’t work correctly!… Reference type is a special “intermediary” internal type, with the purpose to pass information from dot… Reading a property, such as with dot . in obj.method() returns not exactly the property value, but a
The in-memory picture becomes: This example demonstrates how important… Now let’s see how “mark-and-sweep” garbage collector deals with it.… And, what’s even more important, things change as engines develop, so studying deeper “in advance”, without… If you are familiar with low-level programming, more detailed information about V8’s garbage collector… It would be wise to plan that as the next step after you’re familiar with the language.
Most of the time, a JavaScript application needs to work with information.… The statement below creates (in other words: declares) a variable with the name “message”:… For instance, the variable message can be imagined as a box labelled "message" with the value… Name things right.Talking about variables, there’s one more extremely important thing.… Variable naming is one of the most important and complex skills in programming.
It’s only important that the end is after the start in the document.… With these methods we can do basically anything with selected nodes.… compared with a Range start/end.… An important edge case is when selectionStart and selectionEnd equal each other.… The second API is very simple, as it works with text.
Only first 50 results are shown.