Javascript.info Ebook Part 1 The JavaScript language (Ilya Kantor, javascript.info) (Z-Library)
Author: Ilya Kantor, javascript.info
技术
No Description
📄 File Format:
PDF
💾 File Size:
7.3 MB
42
Views
0
Downloads
0.00
Total Donations
📄 Text Preview (First 20 pages)
ℹ️
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
📄 Page
1
The JavaScript language Part 1 Ilya Kantor
📄 Page
2
● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● Built at July 10, 2019 The last version of the tutorial is at https://javascript.info. We constantly work to improve the tutorial. If you find any mistakes, please write at our github. An introduction An Introduction to JavaScript Manuals and specifications Code editors Developer console JavaScript Fundamentals Hello, world! Code structure The modern mode, "use strict" Variables Data types Type Conversions Operators Comparisons Interaction: alert, prompt, confirm Conditional operators: if, '?' Logical operators Loops: while and for The "switch" statement Functions Function expressions and arrows JavaScript specials Code quality Debugging in Chrome Coding Style Comments Ninja code Automated testing with mocha Polyfills Objects: the basics Objects Garbage collection Symbol type Object methods, "this" Object to primitive conversion Constructor, operator "new" Data types
📄 Page
3
● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● Methods of primitives Numbers Strings Arrays Array methods Iterables Map, Set, WeakMap and WeakSet Object.keys, values, entries Destructuring assignment Date and time JSON methods, toJSON Advanced working with functions Recursion and stack Rest parameters and spread operator Closure The old "var" Global object Function object, NFE The "new Function" syntax Scheduling: setTimeout and setInterval Decorators and forwarding, call/apply Function binding Currying and partials Arrow functions revisited Object properties configuration Property flags and descriptors Property getters and setters Prototypes, inheritance Prototypal inheritance F.prototype Native prototypes Prototype methods, objects without __proto__ Classes Class basic syntax Class inheritance Static properties and methods Private and protected properties and methods Extending built-in classes Class checking: "instanceof" Mixins Error handling
📄 Page
4
● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● Error handling, "try..catch" Custom errors, extending Error Promises, async/await Introduction: callbacks Promise Promises chaining Error handling with promises Promise API Promisification Microtasks Async/await Generators, advanced iteration Generators Async iterators and generators Modules Modules, introduction Export and Import Dynamic imports Miscellaneous Proxy and Reflect Eval: run a code string
📄 Page
5
● ● ● Here we learn JavaScript, starting from scratch and go on to advanced concepts like OOP. We concentrate on the language itself here, with the minimum of environment-specific notes. About the JavaScript language and the environment to develop with it. Let’s see what’s so special about JavaScript, what we can achieve with it, and which other technologies play well with it. JavaScript was initially created to “make web pages alive”. The programs in this language are called scripts. They can be written right in a web page’s HTML and run automatically as the page loads. Scripts are provided and executed as plain text. They don’t need special preparation or compilation to run. In this aspect, JavaScript is very different from another language called Java . Why JavaScript? When JavaScript was created, it initially had another name: “LiveScript”. But Java was very popular at that time, so it was decided that positioning a new language as a “younger brother” of Java would help. But as it evolved, JavaScript became a fully independent language with its own specification called ECMAScript , and now it has no relation to Java at all. Today, JavaScript can execute not only in the browser, but also on the server, or actually on any device that has a special program called the JavaScript engine . The browser has an embedded engine sometimes called a “JavaScript virtual machine”. Different engines have different “codenames”. For example: V8 – in Chrome and Opera. SpiderMonkey – in Firefox. …There are other codenames like “Trident” and “Chakra” for different versions of IE, “ChakraCore” for Microsoft Edge, “Nitro” and “SquirrelFish” for Safari, etc. The terms above are good to remember because they are used in developer articles on the internet. We’ll use them too. For instance, if “a feature X is supported by V8”, then it probably works in Chrome and Opera. An introduction An Introduction to JavaScript What is JavaScript?
📄 Page
6
● ● ● ● ● ● How do engines work? Engines are complicated. But the basics are easy. 1. The engine (embedded if it’s a browser) reads (“parses”) the script. 2. Then it converts (“compiles”) the script to the machine language. 3. And then the machine code runs, pretty fast. The engine applies optimizations at each step of the process. It even watches the compiled script as it runs, analyzes the data that flows through it, and applies optimizations to the machine code based on that knowledge. When it’s done, scripts run quite fast. Modern JavaScript is a “safe” programming language. It does not provide low-level access to memory or CPU, because it was initially created for browsers which do not require it. JavaScript’s capabilities greatly depend on the environment it’s running in. For instance, Node.js supports functions that allow JavaScript to read/write arbitrary files, perform network requests, etc. In-browser JavaScript can do everything related to webpage manipulation, interaction with the user, and the webserver. For instance, in-browser JavaScript is able to: Add new HTML to the page, change the existing content, modify styles. React to user actions, run on mouse clicks, pointer movements, key presses. Send requests over the network to remote servers, download and upload files (so-called AJAX and COMET technologies). Get and set cookies, ask questions to the visitor, show messages. Remember the data on the client-side (“local storage”). JavaScript’s abilities in the browser are limited for the sake of the user’s safety. The aim is to prevent an evil webpage from accessing private information or harming the user’s data. Examples of such restrictions include: JavaScript on a webpage may not read/write arbitrary files on the hard disk, copy them or execute programs. It has no direct access to OS system functions. Modern browsers allow it to work with files, but the access is limited and only provided if the user does certain actions, like “dropping” a file into a browser window or selecting it via an <input> tag. There are ways to interact with camera/microphone and other devices, but they require a user’s explicit permission. So a JavaScript-enabled page may not sneakily enable a web- camera, observe the surroundings and send the information to the NSA . What can in-browser JavaScript do? What CAN’T in-browser JavaScript do?
📄 Page
7
● ● Different tabs/windows generally do not know about each other. Sometimes they do, for example when one window uses JavaScript to open the other one. But even in this case, JavaScript from one page may not access the other if they come from different sites (from a different domain, protocol or port). This is called the “Same Origin Policy”. To work around that, both pages must agree for data exchange and contain a special JavaScript code that handles it. We’ll cover that in the tutorial. This limitation is, again, for the user’s safety. A page from http://anysite.com which a user has opened must not be able to access another browser tab with the URL http://gmail.com and steal information from there. JavaScript can easily communicate over the net to the server where the current page came from. But its ability to receive data from other sites/domains is crippled. Though possible, it requires explicit agreement (expressed in HTTP headers) from the remote side. Once again, that’s a safety limitation. Such limits do not exist if JavaScript is used outside of the browser, for example on a server. Modern browsers also allow plugin/extensions which may ask for extended permissions. There are at least three great things about JavaScript: What makes JavaScript unique? ● ● ● Full integration with HTML/CSS. Simple things are done simply. Support by all major browsers and enabled by default.
📄 Page
8
● ● ● ● ● ● ● JavaScript is the only browser technology that combines these three things. That’s what makes JavaScript unique. That’s why it’s the most widespread tool for creating browser interfaces. While planning to learn a new technology, it’s beneficial to check its perspectives. So let’s move on to the modern trends affecting it, including new languages and browser abilities. The syntax of JavaScript does not suit everyone’s needs. Different people want different features. That’s to be expected, because projects and requirements are different for everyone. So recently a plethora of new languages appeared, which are transpiled (converted) to JavaScript before they run in the browser. Modern tools make the transpilation very fast and transparent, actually allowing developers to code in another language and auto-converting it “under the hood”. Examples of such languages: CoffeeScript is a “syntactic sugar” for JavaScript. It introduces shorter syntax, allowing us to write clearer and more precise code. Usually, Ruby devs like it. TypeScript is concentrated on adding “strict data typing” to simplify the development and support of complex systems. It is developed by Microsoft. Flow also adds data typing, but in a different way. Developed by Facebook. Dart is a standalone language that has its own engine that runs in non-browser environments (like mobile apps), but also can be transpiled to JavaScript. Developed by Google. There are more. Of course, even if we use one of transpiled languages, we should also know JavaScript to really understand what we’re doing. JavaScript was initially created as a browser-only language, but is now used in many other environments as well. Today, JavaScript has a unique position as the most widely-adopted browser language with full integration with HTML/CSS. There are many languages that get “transpiled” to JavaScript and provide certain features. It is recommended to take a look at them, at least briefly, after mastering JavaScript. This book is a tutorial. It aims to help you gradually learn the language. But once you’re familiar with the basics, you’ll need other sources. Languages “over” JavaScript Summary Manuals and specifications Specification
📄 Page
9
● ● ● ● The ECMA-262 specification contains the most in-depth, detailed and formalized information about JavaScript. It defines the language. But being that formalized, it’s difficult to understand at first. So if you need the most trustworthy source of information about the language details, the specification is the right place. But it’s not for everyday use. The latest draft is at https://tc39.es/ecma262/ . To read about new bleeding-edge features, that are “almost standard”, see proposals at https://github.com/tc39/proposals . Also, if you’re in developing for the browser, then there are other specs covered in the second part of the tutorial. MDN (Mozilla) JavaScript Reference is a manual with examples and other information. It’s great to get in-depth information about individual language functions, methods etc. One 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?q=MDN+parseInt to search for parseInt function. MSDN – Microsoft manual with a lot of information, including JavaScript (often referrerd to as JScript). If one needs something specific to Internet Explorer, better go there: http://msdn.microsoft.com/ . Also, we can use an internet search with phrases such as “RegExp MSDN” or “RegExp MSDN jscript”. JavaScript is a developing language, new features get added regularly. To see their support among browser-based and other engines, see: http://caniuse.com – per-feature tables of support, e.g. to see which engines support modern cryptography functions: http://caniuse.com/#feat=cryptography . https://kangax.github.io/compat-table – a table with language features and engines that support those or don’t support. All these resources are useful in real-life development, as they contain valuable information about language details, their support etc. Please remember them (or this page) for the cases when you need in-depth information about a particular feature. A code editor is the place where programmers spend most of their time. Manuals Feature support Code editors
📄 Page
10
● ● ● ● ● ● There are two main types of code editors: IDEs and lightweight editors. Many people use one tool of each type. The term IDE (Integrated Development Environment) refers to a powerful editor with many features that usually operates on a “whole project.” As the name suggests, it’s not just an editor, but a full-scale “development environment.” An IDE loads the project (which can be many files), allows navigation between files, provides autocompletion based on the whole project (not just the open file), and integrates with a version management system (like git ), a testing environment, and other “project-level” stuff. If you haven’t selected an IDE yet, consider the following options: Visual Studio Code (cross-platform, free). WebStorm (cross-platform, paid). For Windows, there’s also “Visual Studio”, not to be confused with “Visual Studio Code”. “Visual Studio” is a paid and mighty Windows-only editor, well-suited for the .NET platform. It’s also good at JavaScript. There’s also a free version Visual Studio Community . Many IDEs are paid, but have a trial period. Their cost is usually negligible compared to a qualified developer’s salary, so just choose the best one for you. “Lightweight editors” are not as powerful as IDEs, but they’re fast, elegant and simple. They are mainly used to open and edit a file instantly. The main difference between a “lightweight editor” and an “IDE” is that an IDE works on a project-level, so it loads much more data on start, analyzes the project structure if needed and so on. A lightweight editor is much faster if we need only one file. In practice, lightweight editors may have a lot of plugins including directory-level syntax analyzers and autocompleters, so there’s no strict border between a lightweight editor and an IDE. The following options deserve your attention: Atom (cross-platform, free). Sublime Text (cross-platform, shareware). Notepad++ (Windows, free). Vim and Emacs are also cool if you know how to use them. The editors in the lists above are those that either I or my friends whom I consider good developers have been using for a long time and are happy with. There are other great editors in our big world. Please choose the one you like the most. IDE Lightweight editors Let’s not argue
📄 Page
11
● ● The choice of an editor, like any other tool, is individual and depends on your projects, habits, and personal preferences. Code is prone to errors. You will quite likely make errors… Oh, what am I talking about? You are absolutely going to make errors, at least if you’re a human, not a robot . But in the browser, users don’t see errors by default. So, if something goes wrong in the script, we won’t see what’s broken and can’t fix it. To see errors and get a lot of other useful information about scripts, “developer tools” have been embedded in browsers. Most developers lean towards Chrome or Firefox for development because those browsers have the best developer tools. Other browsers also provide developer tools, sometimes with special features, but are usually playing “catch-up” to Chrome or Firefox. So most developers have a “favorite” browser and switch to others if a problem is browser-specific. Developer tools are potent; they have many features. To start, we’ll learn how to open them, look at errors, and run JavaScript commands. Open the page bug.html. There’s an error in the JavaScript code on it. It’s hidden from a regular visitor’s eyes, so let’s open developer tools to see it. Press F12 or, if you’re on Mac, then Cmd+Opt+J . The developer tools will open on the Console tab by default. It looks somewhat like this: The exact look of developer tools depends on your version of Chrome. It changes from time to time but should be similar. Here we can see the red-colored error message. In this case, the script contains an unknown “lalala” command. On the right, there is a clickable link to the source bug.html:12 with the line number where the error has occurred. Developer console Google Chrome
📄 Page
12
● Below the error message, there is a blue > symbol. It marks a “command line” where we can type JavaScript commands. Press Enter to run them ( Shift+Enter to input multi-line commands). Now we can see errors, and that’s enough for a start. We’ll come back to developer tools later and cover debugging more in-depth in the chapter Debugging in Chrome. Most other browsers use F12 to open developer tools. The look & feel of them is quite similar. Once you know how to use one of these tools (you can start with Chrome), you can easily switch to another. Safari (Mac browser, not supported by Windows/Linux) is a little bit special here. We need to enable the “Develop menu” first. Open Preferences and go to the “Advanced” pane. There’s a checkbox at the bottom: Now Cmd+Opt+C can toggle the console. Also, note that the new top menu item named “Develop” has appeared. It has many commands and options. Usually, when we put a line of code into the console, and then press Enter , it executes. To insert multiple lines, press Shift+Enter . Developer tools allow us to see errors, run commands, examine variables, and much more. Firefox, Edge, and others Safari Multi-line input Summary
📄 Page
13
● They can be opened with F12 for most browsers on Windows. Chrome for Mac needs Cmd+Opt+J , Safari: Cmd+Opt+C (need to enable first). Now we have the environment ready. In the next section, we’ll get down to JavaScript. Let’s learn the fundamentals of script building. This part of the tutorial is about core JavaScript, the language itself. Later on, you’ll learn about Node.js and other platforms that use it. But we need a working environment to run our scripts and, since this book is online, the browser is a good choice. We’ll keep the amount of browser-specific commands (like alert ) to a minimum so that you don’t spend time on them if you plan to concentrate on another environment (like Node.js). We’ll focus on JavaScript in the browser in the next part of the tutorial. So first, let’s see how we attach a script to a webpage. For server-side environments (like Node.js), you can execute the script with a command like "node my.js" . JavaScript programs can be inserted into any part of an HTML document with the help of the <script> tag. For instance: The <script> tag contains JavaScript code which is automatically executed when the browser processes the tag. JavaScript Fundamentals Hello, world! The “script” tag <!DOCTYPE HTML> <html> <body> <p>Before the script...</p> <script> alert( 'Hello, world!' ); </script> <p>...After the script.</p> </body> </html> Modern markup
📄 Page
14
The <script> tag has a few attributes that are rarely used nowadays but can still be found in old code: The type attribute: <script type=…> The old HTML standard, HTML4, required a script to have a type . Usually it was type="text/javascript" . It’s not required anymore. Also, the modern HTML standard, HTML5, totally changed the meaning of this attribute. 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. The language attribute: <script language=…> This attribute was meant to show the language of the script. This attribute no longer makes sense because JavaScript is the default language. There is no need to use it. Comments before and after scripts. In really ancient books and guides, you may find comments inside <script> tags, like this: This trick isn’t used in modern JavaScript. These comments hid JavaScript code from old browsers that didn’t know how to process the <script> tag. Since browsers released in the last 15 years don’t have this issue, this kind of comment can help you identify really old code. If we have a lot of JavaScript code, we can put it into a separate file. Script files are attached to HTML with the src attribute: Here, /path/to/script.js is an absolute path to the script file (from the site root). You can also provide a relative path from the current page. For instance, src="script.js" would mean a file "script.js" in the current folder. We can give a full URL as well. For instance: To attach several scripts, use multiple tags: <script type="text/javascript"><!-- ... //--></script> External scripts <script src="/path/to/script.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js"></script> <script src="/js/script1.js"></script> <script src="/js/script2.js"></script> …
📄 Page
15
● ● ● Please note: As a rule, only the simplest scripts are put into HTML. More complex ones reside in separate files. The benefit of a separate file is that the browser will download it and store it in its cache . Other pages that reference the same script will take it from the cache instead of downloading it, so the file is actually downloaded only once. That reduces traffic and makes pages faster. ⚠ If src is set, the script content is ignored. A single <script> tag can’t have both the src attribute and code inside. This won’t work: We must choose either an external <script src="…"> or a regular <script> with code. The example above can be split into two scripts to work: We can use a <script> tag to add JavaScript code to a page. The type and language attributes are not required. A script in an external file can be inserted with <script src="path/to/script.js"> </script> . There is much more to learn about browser scripts and their interaction with the webpage. But let’s keep in mind that this part of the tutorial is devoted to the JavaScript language, so we shouldn’t distract ourselves with browser-specific implementations of it. We’ll be using the browser as a way to run JavaScript, which is very convenient for online reading, but only one of many. Show an alert <script src="file.js"> alert(1); // the content is ignored, because src is set </script> <script src="file.js"></script> <script> alert(1); </script> Summary ✔ Tasks
📄 Page
16
importance: 5 Create a page that shows a message “I’m JavaScript!”. Do it in a sandbox, or on your hard drive, doesn’t matter, just ensure that it works. Demo in new window To solution Show an alert with an external script importance: 5 Take the solution of the previous task Show an alert. Modify it by extracting the script content into an external file alert.js , residing in the same folder. Open the page, ensure that the alert works. To solution The first thing we’ll study is the building blocks of code. Statements are syntax constructs and commands that perform actions. We’ve already seen a statement, alert('Hello, world!') , which shows the message “Hello, world!”. We can have as many statements in our code as we want. Statements can be separated with a semicolon. For example, here we split “Hello World” into two alerts: Usually, statements are written on separate lines to make the code more readable: A semicolon may be omitted in most cases when a line break exists. This would also work: Code structure Statements alert('Hello'); alert('World'); alert('Hello'); alert('World'); Semicolons
📄 Page
17
Here, JavaScript interprets the line break as an “implicit” semicolon. This is called an automatic semicolon insertion . In most cases, a newline implies a semicolon. But “in most cases” does not mean “always”! There are cases when a newline does not mean a semicolon. For example: The code outputs 6 because JavaScript does not insert semicolons here. It is intuitively obvious that if the line ends with a plus "+" , then it is an “incomplete expression”, so the semicolon is not required. And in this case that works as intended. But there are situations where JavaScript “fails” to assume a semicolon where it is really needed. Errors which occur in such cases are quite hard to find and fix. alert('Hello') alert('World') alert(3 + 1 + 2);
📄 Page
18
An example of an error If you’re curious to see a concrete example of such an error, check this code out: No need to think about the meaning of the brackets [] and forEach yet. We’ll study them later. For now, just remember the result of the code: it shows 1 then 2 . Now, let’s add an alert before the code and not finish it with a semicolon: Now if we run the code, only the first alert is shown and then we have an error! But everything is fine again if we add a semicolon after alert : Now we have the “All fine now” message followed by 1 and 2 . The error in the no-semicolon variant occurs because JavaScript does not assume a semicolon before square brackets [...] . So, because the semicolon is not auto-inserted, the code in the first example is treated as a single statement. Here’s how the engine sees it: But it should be two separate statements, not one. Such a merging in this case is just wrong, hence the error. This can happen in other situations. We recommend putting semicolons between statements even if they are separated by newlines. This rule is widely adopted by the community. Let’s note once again – it is possible to leave out semicolons most of the time. But it’s safer – especially for a beginner – to use them. As time goes on, programs become more and more complex. It becomes necessary to add comments which describe what the code does and why. Comments can be put into any place of a script. They don’t affect its execution because the engine simply ignores them. [1, 2].forEach(alert) alert("There will be an error") [1, 2].forEach(alert) alert("All fine now"); [1, 2].forEach(alert) alert("There will be an error")[1, 2].forEach(alert) Comments
📄 Page
19
One-line comments start with two forward slash characters // . The rest of the line is a comment. It may occupy a full line of its own or follow a statement. Like here: Multiline comments start with a forward slash and an asterisk /* and end with an asterisk and a forward slash */ . Like this: The content of comments is ignored, so if we put code inside /* … */ , it won’t execute. Sometimes it can be handy to temporarily disable a part of code: Use hotkeys! In most editors, a line of code can be commented out by pressing the Ctrl+/ hotkey for a single-line comment and something like Ctrl+Shift+/ – for multiline comments (select a piece of code and press the hotkey). For Mac, try Cmd instead of Ctrl . ⚠ Nested comments are not supported! There may not be /*...*/ inside another /*...*/ . Such code will die with an error: // This comment occupies a line of its own alert('Hello'); alert('World'); // This comment follows the statement /* An example with two messages. This is a multiline comment. */ alert('Hello'); alert('World'); /* Commenting out the code alert('Hello'); */ alert('World'); /* /* nested comment ?!? */ */ alert( 'World' );
📄 Page
20
Please, don’t hesitate to comment your code. Comments increase the overall code footprint, but that’s not a problem at all. There are many tools which minify code before publishing to a production server. They remove comments, so they don’t appear in the working scripts. Therefore, comments do not have negative effects on production at all. Later in the tutorial there will be a chapter Code quality that also explains how to write better comments. For a long time, JavaScript evolved without compatibility issues. New features were added to the language while old functionality didn’t change. That had the benefit of never breaking existing code. But the downside was that any mistake or an imperfect decision made by JavaScript’s creators got stuck in the language forever. This was the case until 2009 when ECMAScript 5 (ES5) appeared. It added new features to the language and modified some of the existing ones. To keep the old code working, most modifications are off by default. You need to explicitly enable them with a special directive: "use strict" . The directive looks like a string: "use strict" or 'use strict' . When it is located at the top of a script, the whole script works the “modern” way. For example: We will learn functions (a way to group commands) soon. Looking ahead, let’s just note that "use strict" can be put at the start of most kinds of functions instead of the whole script. Doing that enables strict mode in that function only. But usually, people use it for the whole script. The modern mode, "use strict" “use strict” "use strict"; // this code works the modern way ...
The above is a preview of the first 20 pages. Register to read the complete e-book.