Search results

This chapter briefly recaps the features of JavaScript that we’ve learned by now, paying special attention… Strict mode.To fully enable all features of modern JavaScript, we should start scripts with "use… The directive must be at the top of a script or at the beginning of a function body.… More to come.That was a brief list of JavaScript features. As of now we’ve studied only basics.… Further in the tutorial you’ll find more specials and advanced features of JavaScript.
JavaScript’s abilities in the browser are limited to protect the user’s safety.… Such limitations do not exist if JavaScript is used outside of the browser, for example on a server.… That said, JavaScript can be used to create servers, mobile applications, etc.… Examples of such languages: CoffeeScript is “syntactic sugar” for JavaScript.… Of course, even if we use one of these transpiled languages, we should also know JavaScript to really
JavaScript animations can handle things that CSS can’t.… Using setInterval.An animation can be implemented as a sequence of frames – usually small changes to… Let’s see more of them.… Power of n.If we want to speed up the animation, we can use progress in the power n.… JavaScript animations can use any timing function.
JavaScript allows us to work with primitives (strings, numbers, etc.) as if they were objects.… A primitive Is a value of a primitive type.… There are other kinds of objects in JavaScript: functions, for example, are objects.… One of the best things about objects is that we can store a function as one of its properties.… A primitive as an object.Here’s the paradox faced by the creator of JavaScript: There are many things
use strict”.The directive looks like a string: "use strict" or 'use strict'.… Should we “use strict”?.… So we don’t need to add the "use strict" directive, if we use them.… So, for now "use strict"; is a welcome guest at the top of your scripts.… As of now, we’ve got to know about use strict in general.
If we need positions of further matches, we should use other means, such as finding them all with str.matchAll… most useful ones.… The main use case for replaceAll is replacing all occurrences of a string.… In the past, before the method str.matchAll was added to JavaScript, calls of regexp.exec were used in… Or instead of calling methods on regexp, use string methods str.match/search/..., they don’t use lastIndex
This part of the tutorial is about core JavaScript, the language itself.… We’ll focus on JavaScript in the browser in the next part of the tutorial.… Now, it can be used for JavaScript modules.… External scripts.If we have a lot of JavaScript code, we can put it into a separate file.… We can use a <script> tag to add JavaScript code to a page.
The JavaScript language steadily evolves.… So it’s quite common for an engine to implement only part of the standard.… Now the rewritten code is suitable for older JavaScript engines.… Speaking of names, Babel is one of the most prominent transpilers out there.… Just don’t forget to use a transpiler (if using modern syntax or operators) and polyfills (to add functions
One of them is to use the special name __proto__, like this:… So if animal has a lot of useful properties and methods, then they become automatically available in… It exists for historical reasons, modern JavaScript suggests that we should use Object.getPrototypeOf… For instance, here animal represents a “method storage”, and rabbit makes use of it.… If we want to read a property of obj or call a method, and it doesn’t exist, then JavaScript tries to
A value in JavaScript is always of a certain type. For example, a string or a number.… In JavaScript, there are 3 types of quotes. Double quotes: "Hello".… In contrast, objects are used to store collections of data and more complex entities.… That also comes from the early days of JavaScript.… It’s the kind of parentheses used for mathematical grouping.
The JavaScript language was initially created for web browsers.… Each of these provides platform-specific functionality.… The JavaScript specification calls that a host environment.… Here’s a bird’s-eye view of what we have when JavaScript runs in a web browser:… There are non-browser instruments that use DOM too.
So it’s easy to use JSON for data exchange when the client uses JavaScript and the server is written… Most of the time, JSON.stringify is used with the first argument only.… Fortunately, we can use a function instead of an array as the replacer.… Here space = 2 tells JavaScript to show nested objects on multiple lines, with indentation of 2 spaces… In this case, the string is used for indentation instead of a number of spaces.
But in the browser, users don’t see errors by default.… To see errors and get a lot of other useful information about scripts, “developer tools” have been embedded… of Chrome.… This way one can enter long fragments of JavaScript code.… Once you know how to use one of these tools (you can start with Chrome), you can easily switch to another
A lot of minor things.… When all members of a team use the same style guide, the code looks uniform, regardless of which team… Because of this feature, using a linter is recommended even if you don’t want to stick to one particular… All of them can do the job. The author uses ESLint.… Create a config file named .eslintrc in the root of your JavaScript project (in the folder that contains
The result of eval is the result of the last statement.… Using “eval”.In modern programming eval is used very sparingly.… a JavaScript Module.… Summary.A call to eval(code) runs the string of code and returns the result of the last statement.… Rarely used in modern JavaScript, as there’s usually no need. Can access outer local variables.
In JavaScript, a function is not a “magical language structure”, but a special kind of value.… It allows us to create a new function in the middle of any expression.… There are programming languages where any mention of a function name causes its execution, but JavaScript… Callback functions.Let’s look at more examples of passing functions as values and using function expressions… Such code appears in our scripts very naturally, it’s in the spirit of JavaScript.
But it’s not for everyday use. A new specification version is released every year.… MDN (Mozilla) JavaScript Reference is the main manual with examples and other information.… You can find it at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference.… Although, it’s often best to use an internet search instead.… Just use “MDN [term]” in the query, e.g. https://google.com/search?
In this article we’ll learn more about different types of comparisons, how JavaScript makes them, including… Because the lowercase character has a greater index in the internal encoding table JavaScript uses (Unicode… Comparison of different types.When comparing values of different types, JavaScript converts the values… the explicit Boolean conversion uses another set of rules.… really sure of what you’re doing.
As we already know, a function in JavaScript is a value. Every value in JavaScript has a type.… We can pass two kinds of handlers: A zero-argument function, which is only called when the user gives… The idea does have a use in JavaScript libraries.… Many well-known JavaScript libraries make great use of this feature.… So, a function can do a useful job by itself and also carry a bunch of other functionality in properties
milliseconds (1/1000 of a second) passed after the Jan 1st of 1970 UTC+0.… An integer number representing the number of milliseconds that has passed since the beginning of 1970… It is used mostly for convenience or when performance matters, like in games in JavaScript or other specialized… These two do exactly the same thing, but one of them uses an explicit date.getTime() to get the date… JavaScript itself does not have a way to measure time in microseconds (1 millionth of a second), but
Using scripts.Another trick was to use a script tag.… (JSON with padding)” protocol was used.… callback=gotWeather", using the name of our function as the callback URL-parameter.… If allowed, it grants JavaScript the full power to act on behalf of the user and access sensitive information… using their credentials.
But in order to hide inner details, we’ll use not a protective cover, but rather special syntax of the… In JavaScript, there are two types of object fields (properties and methods): Public: accessible from… Now we’ll make a coffee machine in JavaScript with all these types of properties.… Imagine, there’s a team of developers using a coffee machine.… If a user of a class will change things not intended to be changed from the outside – the consequences
All of them may be not defined, if the user decided not to fill in the corresponding values.… We’d like to display the user name using one of these variables, or show “Anonymous” if all of them are… Let’s use the ??… It’s been there since the beginning of JavaScript, so developers were using it for such purposes for… Using ?? with && or ||.Due to safety reasons, JavaScript forbids using ??
sequence of 1-4 bytes.… JavaScript allows us to insert a character into a string by specifying its hexadecimal Unicode code with… of 2.… 0xd800..0xdbff, then it is the first part of the surrogate pair.… To support arbitrary compositions, the Unicode standard allows us to use several Unicode characters:
JavaScript is a very function-oriented language. It gives us a lot of freedom.… It can then be used somewhere else.… Understanding such things is great for the overall knowledge of JavaScript and beneficial for more complex… , a valid answer would be a definition of the closure and an explanation that all functions in JavaScript… One of them – we can see a same-named outer variable instead of the expected one:
In modern JavaScript, there are two types of numbers: Regular numbers in JavaScript are stored in 64… These are numbers that we’re using most of the time, and we’ll talk about them in this chapter.… Rounding.One of the most used operations when working with numbers is rounding.… them are used to store the digits, 11 of them store the position of the decimal point, and 1 bit is… We mention Object.is here, because it’s often used in JavaScript specification.
A value of this type can be created using Symbol():… The third-party code won’t be aware of newly defined symbols, so it’s safe to add symbols to the user… …But if we used a string "id" instead of a symbol for the same purpose, then there would be… uses internally, and we can use them to fine-tune various aspects of our objects.… There are many system symbols used by JavaScript which are accessible as Symbol.*.
It’s generally not used in modern scripts, but still lurks in the old ones.… If we used let test instead of var test, then the variable would only be visible inside if:… of that.… The var inside it is processed in the beginning of the function, so at the moment of (*) the variable… These differences make var worse than let most of the time.
So we use <a> in the markup. But normally we intend to handle clicks in JavaScript.… There’s an interesting use case for it.… If we have nested elements, and each of them has a context menu of its own, that would also work.… But then each piece of code that wants a context menu should know about that object and use its help… But if we make a button behave as a link using JavaScript and even look like a link using CSS, then &
Before we get into JavaScript’s ways of dealing with styles and classes – here’s an important rule.… JavaScript can modify both classes and style properties.… The latter should only be used if classes “can’t handle it”.… often used actions in scripts.… className or on individual classes using classList.
The code that makes use of <custom-menu> can look like this:… " attribute is only valid for direct children of the shadow host (in our example, <user-card&… If we’d like to track internal modifications of light DOM from JavaScript, that’s also possible using… The content of <slot> element is used as a fallback.… Composition does not really move nodes, from JavaScript point of view the DOM is still same.
In JavaScript, objects penetrate almost every aspect of the language.… And then we use it to access the property. That gives us a great deal of flexibility.… So most of the time, when property names are known and simple, the dot is used.… Also, we could use another variable name here instead of key.… to suggest a list of options to the user.
Wikipedia In practice, we often need to create many objects of the same kind, like users, or goods… In JavaScript, a class is a kind of function.… {...} construct really does is: Creates a function named User, that becomes the result of the class… We can illustrate the result of class User declaration as: Here’… It depends on the context of the call.
The result of a % b is the remainder of the integer division of a by b.… Here’s a demo that uses an assignment as part of a more complex expression:… Yes, but we can only see it if we use the returned value of ++/--. Let’s clarify.… To summarize: If the result of increment/decrement is not used, there is no difference in which form… We won’t need these operators any time soon, as web development has little use of them, but in some special
Currying is an advanced technique of working with functions.… It’s used not only in JavaScript, but in other languages as well.… The result of curry(func) is a wrapper function(a).… But most implementations of currying in JavaScript are advanced, as described: they also keep the function… Currying allows us to easily get partials.
We’ll use window here, assuming that our environment is a browser.… Modern scripts use JavaScript modules where such a thing doesn’t happen.… Using for polyfills.We use the global object to test for support of modern language features.… of the global object.… To make our code future-proof and easier to understand, we should access properties of the global object
In JavaScript we can only inherit from a single object.… the functionality of EventEmitter to User, so that our users can emit events.… A mixin example.The simplest way to implement a mixin in JavaScript is to make an object with useful… For instance here the mixin sayHiMixin is used to add some “speech” for User:… like this: Mixins can make use of
__proto__ is considered outdated and somewhat deprecated (moved to the so-called “Annex B” of the JavaScript… is used on server-side.… First, we can just switch to using Map for storage instead of plain objects, then everything’s fine:… Now, if we intend to use an object as an associative array and be free of such problems, we can do it… These objects are used as dictionaries, to store any (possibly user-generated) keys.
They may occur because of our mistakes, an unexpected user input, an erroneous server response, and for… One of most widely used and supported is: stack Current call stack: a string with information about… “try…catch”.Let’s explore a real-life use case of try...catch.… And in our case, the absence of name is an error, as users must have a name.… If an error object is not needed, we can omit it by using catch { instead of catch (err) {.
The "prototype" property is widely used by the core of JavaScript itself.… All built-in constructor functions use it.… of the other.… , but is not yet supported by a particular JavaScript engine.… Some methods of native prototypes are often borrowed.
Use a local web-server, such as static-server or use the “live server” capability of your editor, such… In other words, with modules we use import/export instead of relying on global variables.… There’s a rule: top-level module code should be used for initialization, creation of module-specific… run after that, so the user may see the page before the JavaScript application is ready.… One of the benefits of using bundlers – they give more control over how modules are resolved, allowing
As we can recall from the chapter Native prototypes, JavaScript itself uses prototypal inheritance for… If it becomes a problem, one can fix it by using methods or getters/setters instead of fields.… Without classes, using plain objects for the sake of simplicity.… Without any use of this.… The difference may be non-essential for us, but it’s important for JavaScript.
So, here we’ve got a method sayHi of the object user.… For instance, the code inside user.sayHi() may need the name of the user.… The value of this is the object “before dot”, the one used to call the method.… user.sayHi(), the value of this will be user.… It can be used in any function, even if it’s not a method of an object.
An element receives the focus when the user either clicks on it or uses the Tab key on the keyboard.… Let’s use them for validation of an input field.… JavaScript can be used when we want more flexibility.… The value of the attribute is the order number of the element when Tab (or something like that) is used… The property elem.tabIndex works too We can add tabindex from JavaScript by using the elem.tabIndex
regular JavaScript objects: They can have any value.… Also one can read all attributes using elem.attributes: a collection of objects that belong to a built-in… Non-standard attributes, dataset.When writing HTML, we use a lot of standard attributes.… Sometimes non-standard attributes are used to pass custom data from HTML to JavaScript, or to “mark”… HTML-elements for JavaScript.
JavaScript can be used to control CSS animations and make them even better, with little code.… So instead of left/margin-left properties we can use transform: translateX(…), use transform: scale for… We’re also able to use JavaScript for animations, the next chapter is devoted to that.… We can create new elements in JavaScript as part of the animation.… The majority of animations can be implemented using CSS as described in this chapter.
That leads us to the regexp ^(\w+\s?)… The time needed to try a lot of (actually most of) combinations is now saved.… That is, we use \d++ instead of \d+ to stop + from backtracking.… Of course, we could take another pattern instead of \w.… of the pattern.
In JavaScript, the textual data is stored as strings.… Quotes.Let’s recall the kinds of quotes.… In contrast with the previous methods, this one allows us to specify the length instead of the ending… It means that only browser-hosted Javascript engines should support it, and it’s not recommended to use… To understand what happens, we should be aware that strings in Javascript are encoded using UTF-16.
The two most used data structures in JavaScript are Object and Array.… It’s a kind of syntax sugar for calling for..of over the value to the right of = and assigning the values… We can use it with destructuring to loop over the keys-and-values of an object:… We can use any other variable name in place of rest, just make sure it has three dots before it and goes… Of course, we could use existing variables too, without let. But there’s a catch.
In JavaScript, they are available via the RegExp object, as well as being integrated in methods of strings… There are only 6 of them in JavaScript: i With this flag the search is case-insensitive: no difference… The flag enables correct processing of surrogate pairs.… We can use special character combinations in it to insert fragments of the match: Symbols Action in… of them if there’s g flag, otherwise only the first one.
Only first 50 results are shown.