Basics of Functional Programming in JavaScript

Basics of Functional Programming in JavaScript from Coding compiler – This tutorial explains the basics of functional programming with simple examples to create a concise and easily supported code. In recent years, an even greater distinction has been made between traditional and functional programming in JavaScript. Its essence is not in the superiority of one over the other but in personal preferences.

Continue reading “Basics of Functional Programming in JavaScript”

33 Most Useful Regular Expressions For Web Developers 2019

33 most useful regular expressions for web developers with examples 2019 from Coding compiler. Use these regular expressions to quickly solve the most common tasks of web development. Let’s start learning about the most used regular expressions in web development.

Types of Regular Expressions

  1. Regular Expressions to Validate User Data
  2. Regular Expression to Validate Common Formats
  3. Regular Expressions Related to Numbers
  4. Regular Expressions Related to Files and URLs
  5. Regular Expressions Related to Social Networks
  6. Regular Expressions Related to HTML and CSS
  7. Regular Expressions Related to other Web Developer Tasks
Continue reading “33 Most Useful Regular Expressions For Web Developers 2019”

11 JavaScript Animation Libraries For 2019

11 JavaScript Animation Libraries For 2019. Let’s not forget about using pure CSS, why because it can improve graphics performance (GPU), provide backward and forward compatibility, and this may just be the most effective way to create animations.

Continue reading “11 JavaScript Animation Libraries For 2019”

12 JavaScript Libraries For Data Visualization 2019

12 JavaScript Libraries For Data Visualization 2019 from Coding compiler. Data visualization has quickly become a standard for the dissemination of web information, and data visualization can help us understand and transfer insight between information. This tool is used in business intelligence to journalism.

Top 12 JavaScript Libraries For Data Visualization

  1. D3.js
  2. ChartJS
  3. ThreeJS
  4. Echarts & Highcharts
  5. Metric-Graphics
  6. Recharts
  7. Raphael
  8. C3js
  9. React Virtualized + React Vis + Victory
  10. CartoDB
  11. Raw graphs
  12. Metabase

JavaScript Data Visualization Libraries

D3.js JavaScript Library

With 80,000 stars in the hub’s gateway, D3.js is built to create data-driven documents and create data into life using HTML, SVG, and CSS. The D3 emphasis on web standards allows you to create modern browsers without connecting to a dedicated framework, combining visual components, and a data-driven approach for the DOM. This allows you to assign arbitrary data to an Object Model (DOM) and then apply the transformations to the document.

Chart.JS JavaScript Library

With 40,000 stars in the Github, this Chart.js open-source library is built with HTML5 and canvas standards. It provides various graphs, graph axes and beautiful animations. Simple and elegant designs with 8 types of base diagrams and you can combine the library with moment.js for the time axis.

Three.JS JavaScript Library

With 47,000 stars in the Github, this Three.js library is made to create 3D animations using WebGL. The flexibility and abstraction of the project means that it is useful for data visualization in two or three dimensions.

Echarts & Highcharts JavaScript Library

With 30,000 stars in the GitHub, it’s an interactive library of graphs and visualization for the browser. Echarts & Highcharts is written with pure javascript and is based on the zrender canvas library. The program supports rendering charts in the form of Canvas, SVG (4.0+) and VML. In addition to computer and mobile browsers, ECharts can also be used with a node node in the grid to provide server-side processing (SSR).

Highcharts JS with 8,000 stars in the Goethe Hub, this library is based on SVG, with VBI and band for older browsers. Claims that 72 of the 100 world’s companies use the library, such as Facebook and Twitter.

MetricsGraphics.js

With 7,000 stars in the GitHub, MetricGraphics.js is a library that is optimized for visualization and estimation of time series data. With a volume of 80 KB, it provides a slim but beautiful selection of line charts, sparse pages, histograms, bar graphs and data tables, as well as features such as linear regression carpet.

Recharts JavaScript Library

Recharts – With 10,000 stars in the GitHub, there is a React and D3 structural library that allows you to apply as React Announcement components. With support for native SVG, the lightweight dependency tree (submodules D3) provides highly customizable through the component booth.

Raphael JavaScript Library

With 10,000 stars in the GitHub, the “vector library” is designed to work with vector graphics on the web. This Raphael library uses the SVG W3C Recommendation and VML as the basis for creating graphics, so any graphical object is also a DOM object, and you can attach Java event categories. Raphael now supports Firefox 3.0+, Safari 3.0+, Chrome 5.0+, Opera 9.5+ and Internet Explorer 6.0+.

C3.js JavaScript Library

With 8,000 stars in the Github, C3.js is a D3-based integrated chart library for web applications. This library provides classes for each element, so you can define a custom style by class and directly expand the structure of D3. It also provides a variety of programming interface and callbacks to access the chart state. With them, you can update the chart even after rendering.

React Virtualized + React Vis + Victory JavaScript Libraries

With 4,000 stars in the Github, React Virtualized + React Vis + Victory is a set of React Uber components is suited for displaying data in a consistent manner, including line / area / bar graphs, heat maps, scatter plates, meter plots, hexagonal heaters, and much more. This library has no previous knowledge with D3 or any other information library, and provides modular building block components such as the X / Y axis.

With a 12,000 star in the GitHub, there is a set of React components for rendering large lists and tabular data. ES6, CommonJS and UMD are available in each distribution, and the project supports Webpack.

Victory is a collection of composite reactions designed to create interactive data visualization that is created using the same web programming interface for the Web and React Native applications for simple and cross-platform applications. A delicate and flexible method for levering React Components in favor of practical information visualization.

CartoDB

With 2000 stars in the GitHub, Carto is a smart tool and visual information to discover insights based on location data. You can upload geographic data (Shapefiles, GeoJSON, etc.) using a web form and view it in a dataset or map, search it using SQL, and use the map styles Apply CartoCSS.

RAWGraphs

RAWGraphs – With 5000 stars in the Github, there is a link between spreadsheets and data visualization created to create custom vector images for the d3.js library. This works with tabular data (spreadsheets and comma separated values) as well as texts copied and pasted from other programs. Based on the SVG format, visualizations can be embedded with vector graphics programs for further refinement, or directly on web pages.

Metabase

With 11,000 stars in the Github, Metabase is a quick and easy way to create a data warehouse without knowing SQL. You can create focal areas and criteria, send information to Slack. It’s probably a great tool to visualize data internally for your team, although some maintenance may be needed.

Related JavaScript Tutorials For Beginners

JavaScript Introduction Tutorials
Introduction to JavaScript
Javascript Code editors
Javascript Reference and Specifications
Javascript Developer Console
Javascript Basics
JavaScript Hello World.!
External JavaScript Files
JavaScript Code Structure
JavaScript Variables
Use Strict in JavaScript


JavaScript Design Patterns Tutorial With Examples

This this JavaScript design patterns tutorial, we are going to implement popular design patterns in JavaScript and at the same time we understand this difficult topic with real examples. JavaScript design patterns have a number of features. The language has no interfaces, so you have to resort to some agreements. We assume that a class implements a certain interface if it has inherent methods and properties. The interfaces themselves are described in the comments. The examples use ES6 syntax.

Continue reading “JavaScript Design Patterns Tutorial With Examples”

ECMAScript 2018 Introduction

This standard defines the ECMAScript 2018 language and is the ninth edition of the ECMAScript language specification. Since its first release in 1997, ECMAScript has become one of the most widely used programming languages ​​in the world. He is best known as a language embedded in web browsers, but is also widely used in servers and embedded applications.

ECMAScript is based on several originating technologies, the most famous being Netscape’s JavaScript and Microsoft’s JScript. The language was invented by Netscape’s Brendan Eich and first appeared in the company’s Navigator 2.0 browser. It has appeared in all subsequent Netscape browsers and in all browsers that Microsoft has started since Internet Explorer 3.0.

ECMAScript Language Development

The development of the ECMAScript language specification began in November 1996. The first edition of the Ecma standard was adopted by the Ecma Joint Conference in June 1997.

The First Edition of ECMAScript

This (first edition) Ecma standard was submitted to ISO/IEC JIC 1 for fast channel adoption and was approved as an international standard ISO/IEC 16262 in April 1998. The second edition of ECMA-262 was adopted at the 1998 Ecma Joint Conference to ensure full compliance with ISO/IEC 16262. The changes in the first and second editions are at the editorial level.

The third edition of the standard introduces powerful regular expressions, better string handling, new control statements, try/catch exception handling, stricter error definitions, formatting of digital output, and minor changes in expected future language development. The third edition of the ECMAScript standard was adopted by the Ecma Joint Conference in December 1999 and as ISO/IEC 16262:2002 in June 2002.

ECMAScript and World Wide Web

After the third edition was released, ECMAScript was heavily used on the World Wide Web, and it became the programming language supported by all Web browsers. In order to develop the fourth edition of ECMAScript, a lot of meaningful work was done. However, this work was not completed and was not released as the fourth edition of ECMAScript, but some of them were included in the sixth edition of development (work).

The fifth edition of ECMAScript (262-5 to the ECMA TH release) for those languages have been widely implemented in browser specifications compiled substantial explanation, and adds support for new features since the third edition of the publication appears.

ECMAScript Features

These features include Accessor properties, Reverse and create the object under examination , control attributes characteristic of the object , More array manipulation functions, support for JSON object encoding format , and an enhanced error checking and program security in strict mode . The fifth edition was adopted at the December 2009 Ecma Joint Conference.

The fifth edition was submitted to ISO/IEC JIC 1 for rapid channel adoption and was approved as the international standard ISO/IEC 16262:2011. The 5.1 version of the ECMAScript standard contains fewer corrections and is consistent with ISO/IEC 16262:2011. It was adopted in June 2011 at the Ecma Joint Conference.

The sixth edition began as a key development in 2009, when the fifth edition was being prepared for publication.

However, the previous focus of the experiment and the language enhancement design work can be traced back to the third edition of 1999. In fact, the completion of the sixth edition is the result of fifteen years of hard work. This release adds support for large applications, library creation , and compilation goals with ECMAScript as the other language. The main enhancements include modularity , class declarations , lexical block scopes , iterators and generators , asynchronous programming promises , destructuring patterns , and correct tail calls .

ECMAScript Built-in Library Extension Support

The ECMAScript built-in library extension supports additional data abstractions, including Map , Set , and arrays of binary values , as well as Unicode supplemental characters for use in strings and regular expressions . The built-in library is also extended by subclasses. The sixth edition provides the basis for regular , progressive languages and library enhancements . The sixth edition was adopted by the Ecma Joint Conference in June 2015.

ECMAScript 2016 uses the new annual release strategy of the Ecma TC39 committee and the first ECMAScript version of the open development process. Build a plain text source document from the ECMAScript 2015 source document as a base to support further development on GitHub.

In the year of this standard development, hundreds pull requests and issues were submitted, representing thousands of bug fixes, editor fixes and other improvements. In addition, many software tools were developed to help with this work, including Ecmarkup, Ecmarkdown and Grammarkdown. ES2016 also includes support for a new exponentiation operator and include a new method called Array.prototype.

ECMAScript 2017

The ECMAScript 2017 specification introduces Async functions , shared memory , and smaller language and library enhancements for atomic , bug fixes , and editor updates. The Async function promise-returning improves the asynchronous programming experience by providing function syntax.

Shared memory and atoms introduce a new memory model that allows multiple agents to communicate using atomic operations to ensure that programs have a well-defined execution order even on parallel CPUs. This specification also includes new static methods for Object: Object.values, Object.entries and Object.getOwnPropertyDescriptors.

This specification, version 9 supports asynchronous iteration by introducing asynchronous iterator protocols and asynchronous generators. The specification also includes four new regular expression features: the dotAll flag, named capture groups, Unicode attribute escaping, and backsight assertions. It also includes REST parameters and extended operators to support object properties. There are also many small updates, edits and specifications that contribute to our community.

Ecma TC39

Many individuals and organizations have made a significant contribution to the current and previous versions of the Ecma TC39. In addition, there is a vibrant community that supports TC39’s efforts for ECMAScript. The community reviewed many drafts, submitted a large number of bug reports, performed implementation experiments, and provided test suites, which could benefit from ECMAScript developers around the world.

Regrettably, however, everyone and organizations that contribute to this cannot be acknowledged.

Wirfs-Brock allen

the ECMA-262, 6 TH version Project Editor

Terlson Brian

the ECMA-262, 7 TH version Project Editor

ECMAScript Standards

This standard defines the ECMAScript 2018 general programming language.

ECMAScript Consistency

An implementation that conforms to the ECMAScript standard should meet the following recommendations:

All types, values, objects, properties, functions, and program syntax and semantics described in this specification must be provided and supported.

The input to interpret the source text must be consistent with the latest versions of the Unicode standard and the ISO/IEC 10646 standard.

The program provided by the application interface needs to adapt to the language and cultural habits of countries using different natural languages, and ECMA-402 the implementation of the latest version must be compatible with the interface of this specification.

Additional types, values, objects, properties, and methods that are beyond the specification should be provided. Especially for those objects that are mentioned in the documentation but do not describe their properties, those properties and the values ​​corresponding to the properties should be provided.

Some programs or regular expression syntax that are not mentioned in the specification should be supported.

ECMAScript Reference Standard

In order to implement an application that conforms to this specification, the following referenced documents are indispensable. For documents marked with a date, only the version of the label is applied. For documents that are not dated, the latest version of the document (including any revisions).

ISO/IEC 10646:2003: Information Technology – Generic Multiple Octet Coded Character Set (UCS) and Amendment 1:2005, Amendment 2:2006, Amendment 3:2008, and Amendment 4:2008 , and other amendments, corrections, successor standards

ECMA-402, ECMAScript 2015 Internationalization API Specification . http://www.ecma-international.org/publications/standards/Ecma-402.htm

ECMA-404, JSON Data Exchange Formatting . http://www.ecma-international.org/publications/standards/Ecma-404.htm

ECMAScript Overview

This section contains a non-normative overview of the ECMAScript language.

ECMAScript is an object-oriented programming language that performs computations and manipulates computational objects in a hosted environment.

The ECMAScript defined here is not intended to be self-sufficient in calculation; in fact, the specification does not specify the input of external data or the output of the calculation result. Instead, we expect that the computing environment of the ECMAScript program will not only provide the objects and capabilities described in this specification, but also specific environment objects.

In addition to the description that these objects should provide certain properties that can be accessed by ECMAScript programs, some methods are called. In addition, other descriptions and actions regarding it are outside the scope of this Code.

ECMAScript – Scripting Language to General Purpose Language

ECMAScript was originally designed as a scripting language, but is now widely used as a general-purpose programming language. A scripting language is a programming language used to manipulate, customize, and automate existing system capabilities. In such systems, useful functionality is already available through the user interface, and scripting languages ​​are mechanisms that expose these functions to program control.

In this way, the existing system is called a host environment that provides objects and capabilities, thus completing the functions of the scripting language. The scripting language is for professional and non-professional programmers.

Originally designed as a web scripting language , ECMAScript provides a mechanism for making web pages more vibrant and capable of server-side computing based on the Web B/S architecture. ECMAScript is now used to provide core scripting capabilities across multiple hosts. This document therefore describes the language core in addition to the specific hosting environment.

ECMAScript usage has gone far beyond simple scripting and is now used for a full range of programming tasks in many different environments and sizes. As the scope of use of ECMAScript has expanded, its capabilities and capabilities have also expanded. ECMAScript is now a full-featured general-purpose programming language.

EMCAScript Vs Other Programming Languages

Some of ECMAScript’s capabilities are similar to those in other programming languages, especially C, Java, Self, and the following:

  • ISO/IEC 9899:1996, Programming Languages ​​– C .
  • Gosling, James, Bill Joy and Guy Steele. The Java TM Language Specification . Addison Wesley Publishing Co., 1996.
  • Ungar, David, and Smith, Randall B. Self: The Power of Simplicity. OOPSLA ’87 Conference Proceedings , pp. 227-241, Orlando, FL, October 1987.
  • IEEE Standard for the Scheme Programming Language . IEEE Std 1178-1990.

ECMA Web Script

The web browser provides an ECMAScript hosting environment for client-side computing, including instance objects such as delegate windows, menus, pop-ups, dialogs, text fields, anchors, frames, history, cookies, and input/output.

In addition, the host environment provides the ability for script code to handle events such as focus changes, page and image loading, unloading, errors and interruptions, selections, form submissions, and mouse interactions. Combine user interface elements with script code in HTML, pin and calculate text, and images to display pages. The script code does not require a main program to respond to user interaction.

The WEB server provides a different mechanism than the client, such as requests, clients, files, etc., as well as data locking and sharing. Provides a customized user interface for web-based applications that can be used for distributed computing between the client and server through the use of browser-side scripts and server-side scripts.

Both WEB browsers and servers that support ECMAScript complement their own hosting environment as ECMAScript to complete the ECMAScript execution environment.

ECMAScript Overview

The following is an informal overview of ECMAScript – just a part of the language. This overview is not part of the standard.

ECMAScript is object-based: the underlying language and the main capabilities are provided through objects, and an ECMAScript program is a set of communicable objects. In ECMAScript, an object is a collection of zero or more properties.

Each attribute has to be used to determine how their properties , such as when a characteristic property to Writable False Any ECMAScript code that attempts to assign a different value to this property will fail.

ECMAScript Built-in Data Types

Attributes are containers of other objects, primitive values , and functions . The original value is one of the following built-in type members: Undefined , Null , Boolean , Number , String , and Symbol; An object is one of the built-in type Object members, and a function is a callable object. The function called by the object through the property is called the method.

ECMAScript Built-in Objects

ECMAScript defines a set of built-in objects to outline the definition of ECMAScript entities.

These built-in objects include global objects ; basic language Runtime semantics Objects, including Object, Function, Boolean, Symbol, various Error objects; and values representative of operation of the object, including Math, Number, Date; text processing object String, ; RegExp index value set Array objects, and the specific digital data having a value of nine kinds of representation Typed Array objects; generic objects  Map , Set; support for structured data JSON, ArrayBuffer, SharedArrayBuffer, DataView and other objects; support for controlling abstract generator functions, Promise objects; and reflection objects Proxy, Reflect.

ECMAScript also defines a set of built-in operators.

The ECMAScript operators include various unary operations, multiplication operators, addition operators, displacement operators, relational operators, equality operators, binary operators, binary logical operators, assignment operators, and comma operators.

Large ECMAScript programs are supported through modules that allow programs to be split into multiple statements and definition sequences. Each module explicitly identifies the declarations provided by other modules it uses, and which declarations are available to other modules.

The ECMAScript syntax is intentionally similar to the Java syntax. The ECMAScript syntax is loose, making it an easy-to-use scripting language. For example, a variable does not need to declare its concrete type, nor does it need to associate a property type with a declaration, nor does it require a textual declaration before calling the defined function.

ECMAScript Objects

Although ECMAScript includes syntax for defining classes, ECMAScript objects are not class-based like C++, Smalltalk, and Java. Instead, objects can be created in a variety of ways, including literal symbols, or through Constructor Create an object and then run the code to initialize all or part of its property values, assigning initial values ​​to those properties.

Each Constructor Has named a “prototype”property of a function, this property is used to implement prototype-based inheritance and shared properties .

Constructor Create an object with a new expression: for example, new Date(2009, 11)create a new Date object. Call one without using new Constructor Result by Constructor It is decided by itself. For example, Date()generate a string that represents the current date and time, not an object.

Each by Constructor The created object has an implicit reference (called the prototype of the object ) linked to Constructor The “prototype”property value. Furthermore, a prototype may have a non-empty implicit reference linked to its prototype, and so on, which is called a prototype chain .

When a reference is made to an attribute of an object, the reference points to the attribute of the first object in the prototype chain that contains the name of the attribute. In other words, first check the property of the same name of the directly mentioned object.

If the object contains an attribute with the same name, the reference points to this attribute. If the object does not contain the attribute with the same name, the next step is to check the prototype of the object; and so on.

Figure 1: Object/Prototype Relationships

In general, an instance of a class-based object-oriented language has a state, a class owns a method, and can only inherit structures and behaviors. In ECMAScript, objects have states and methods, and structures, behaviors, and states are all inherited.

All objects that do not directly contain specific properties share this property and property values ​​contained in their prototype. Figure 1 illustrates this:

CF is a Constructor(Also an object). Five objects have been used new to create an expression: cf 1 , cf 2 , cf 3 , cf 4 ,cf 5 . Each object has the name q1and q2 attributes.

The dotted line indicates the implicit prototype relationship; for example: The prototype of cf 3 is CF p .Constructor CF it has named P1and P2two properties, which CF P , CF2 . 1 , CF2 2 , CF2 . 3 , CF2 . 4 , CF2 . 5 is not visible. CF2 P named CFP1 attribute shared CF2 . 1 , CF2 2 , CF2 . 3 , CF2 . 4 , and CF2 . 5 (no CF2 ), and the CF2 P can not find implicit in any named prototype chain q1, q2or CFP1 attributes . Please note that CF and CF p There are no implicit prototype links between them.

Unlike class-based object languages, properties can be dynamically added to objects by way of assignment.

That is,Constructor It is not necessary to name or assign all or any of the attributes of the constructed object. In the above figure, you can add a new attribute attribute to CF p by adding a new shared attribute to cf 1 , cf 2 , cf 3 , cf 4 , and cf 5 .

Although ECMAScript objects are not class-based in nature, it is convenient to implement a class-like abstraction based on constructors, prototype objects, and method generic patterns. The ECMAScript built-in object itself follows this class pattern. Starting with ECMAScript 2015, the ECMAScript language includes class definition syntax that allows programmers to define objects as concisely as built-in objects.

ECMAScript Strict Variations

The ECMAScript language recognizes that some developers may wish to limit the use of new features in the language. They may do this for security reasons, avoid features that they think are error-prone, gain an enhanced error check, or other reasons. Therefore, strict variants of the language are defined in ECMAScript.

Strict variations of the language, excluding certain specific syntax and semantic features of the ECMAScript language, and modifying the detailed semantics of certain functions. Strict variants also specify additional error conditions that must be thrown for error exception reporting, even if they are not errors in a non-strict language form.

The strict variant of ECMAScript is often referred to as the strict mode of language . Strict mode selection and use are explicitly applied to the unique ECMAScript code unit level, ECMAScript strict mode syntax and semantics. Since the strict mode of the grammar code unit level is selected, the strict mode imposes a local effect limitation only in this code unit. Strict mode does not limit or modify ECMAScript semantics at any level and must operate consistently across multiple code units. An ECMAScript program can contain both rigorous and non-strict mode code units. In this case, the strict mode only applies to code that is actually executed within the strict mode code unit.

To comply with this specification, ECMAScript implementations must implement both the unrestricted ECMAScript language and the strict schema variants of ECMAScript defined by this specification. In addition, the implementation must also support the use of unrestricted and strict mode code units in the same program.

ECMAScript Terms and Definitions

The following terms and definitions are used in this document.

1) Type – In this specification, A collection of data values ​​defined in.

2) Original value – Means One of the Undefined, Null, Boolean, Number, Symbol, String types defined in

NOTE: A raw value directly represents the lowest level of data implemented by the language

3) Object – Members of type Object

NOTE: An object is a collection of properties and has a single prototype object. The prototype may be null.

4) Constructor – Create and initialize objects Function object

NOTE: Constructor The prototype property value is used to implement inheritance and shared a prototype object.

5) Prototype – An object that provides shared properties for other objects

NOTE: When Constructor Create an object that is implicitly referenced in order to resolve an object’s property reference Constructor Of prototype property. By program expressions_constructor_.prototype can refer to Constructor The prototype property, added to the object in the prototype property is shared by inheritance, all objects are shared prototype. In addition, you can use Object.create built-in functions to create a new object by explicitly specifying the prototype.

6) Ordinary object – The default behavior has objects that have internal methods that all objects must support.

7) Exception object – The default behavior is missing one or more objects of the necessary internal methods

NOTE: Any object is not Ordinary object It is an exception object.

8) Standard object – Object whose semantics are defined by this specification

9) Built-in object – ECMAScript implementation specifies and provides objects

NOTE: Standard built-in objects are defined by this specification, and ECMAScript implementations can specify and define other built-in ones. Constructor Is a built-in object, also a Constructor.

10) Undefined value – An original value that is used when the variable is not assigned a value

11) Undefined type – Value only Undefined Type of value

12) null value – Indicates the original value of any object value deliberately defaulted

13) Null type – Value only Null Type of value

14) Boolean value – Member of type Boolean

NOTE: There are only two values, True with False.

15) Boolean type – Original value True with False Type of composition

16) Boolean object – Standard built-in constructor Boolean Instance of one of the Object type members

NOTE: By using newan expression to a Boolean value as a parameter to call Boolean Constructor To create a Boolean object. The resulting object contains an internal property whose value is this Boolean value. A Boolean object can be cast to a Boolean value.

17) String value – Finite ordered sequence original value consisting of zero or more 16-bit unsigned integers

NOTE: A String value is a member of type String. Usually each integer value in the sequence represents a single 16-bit unit of UTF-16 text. However, for its value, ECMAScript only requires a 16-bit unsigned integer, and there are no restrictions or requirements.

18) String type – A collection of all possible String values

19) String object – Standard built-in Constructor String Instance, one of the Object type members

NOTE: By using newan expression to a String parameter called value String Constructor To create a String object. The resulting object contains an internal property with a value of this String. Will String Constructor Called as a function to cast a String object to a String value.

20) Number value – Original value of 64-bit double-precision binary in IEEE 754-2008 format

NOTE: A numeric value is a member of a numeric type that directly represents a number.

21) Number type – A collection of all possible Number values, including special “Not-a-Number” (NaN) values, positive infinity ,negative infinity

22) Number object – Standard built-in Constructor Number An instance of one of the Object type members

NOTE: By using newan expression to a parameter called digital value Number Constructor To create a Number object. The resulting object contains an internal property with a value of this Number. Will Number Constructor Called as a function to cast a Number object to a numeric value.

23) Endless – Positive infinity

24) NaN – Value of IEEE 754-2008 “Not-a-Number”

25) Symbol value – Represents the original value of a unique, non-string attribute key object

26) Symbol type – All possible sets of Symbol values

27) Symbol object – Standard built-in Constructor Symbol An instance of one of the Object type members

28) Function – One of the Object type members that can be called as a subroutine

NOTE: In addition to its properties, functions contain executable code and state to determine the behavior when called. The code for the function is not limited to ECMAScript.

29) built-in functions – Built-in object as a function

NOTE: For example, parseInt and Math.exp are built-in functions. An implementation can provide implementation-dependent built-in functions not described in this specification.

30) properties – Part of an object that associates a key (a String value or a Symbol value) with a value

NOTE: Attributes may appear as direct data values ​​(original values, objects, or one) depending on the value of the attribute Function object) or an indirect pair of accessor functions.

31) Method – Function as a property value

NOTE: When a function is called as a method of an object, this object will act as This The value is passed to the function.

32) Built-in method – As a method of built-in functions

NOTE: The standard built-in methods are defined by this specification, and the ECMAScript implementation can be specified to provide additional additional built-in methods.

33) Characteristic – Define internal values ​​for some properties of an attribute

34) Own attribute – Attributes directly owned by the object

35) Inherited properties – Not the object’s own property, but the property of the object’s prototype (the prototype’s own or inherited properties)

ECMAScript Symbol Convention Grammar and lexical – Context-free grammar

A context-free grammar consists of multiple productions . On the left side of each production there is anl value of an abstract symbol called a nonterminal , and on the right there is one or more right values ​​of a sequence of nonterminals and terminators . Any grammar whose terminator comes from the specified set of letters.

A production chain is a production that contains only one nonterminal and zero or more terminators as its rvalue.

A single distinguishable nonterminal term in a sentence—the target character , given a language context-free grammar. In other words, iteratively replaces any set of terminal sequences (possibly infinite) consisting of any left-valued non-terminals in the sequence with a production right-value.

Lexical and regular grammar

Word French law has a match 10.1 Defined Source Character The terminator of the rule is a Unicode code point . It defines a set of productions, fromTarget symbol InputElementDiv, InputElementTemplateTail,or InputElementRegExp, InputElementRegExpOrTemplateTail Start, describes how to translate such a sequence of characters into a sequence of input elements.

Input elements other than blanks and comments form the terminator of the ECMAScript syntax grammar, which are called ECMAScript tokens . These tokens are reserved words, identifiers, literals, punctuation marks in the ECMAScript language.

In addition, the line terminator, although not considered a tokens, will be part of the input element stream and will be used to guide the process to automatically insert a semicolon. Discarding of single blank and single-line comments will not occur in the stream of input elements of the grammar grammar.

If one MultiLineComment (Ie, in the form of /**/comments, whether or not span multiple lines) does not contain a line terminator will be directly discarded, but if a MultiLineComment Contains one or more terminators, then the comment is replaced with a line terminator that becomes part of the stream of grammar grammar input elements.

The regular grammar of ECMAScript is given . The terminator character of this grammar is also SourceCharacter definition. It defines a set of productions, from Target symbol Pattern Initially, it describes how to translate such a sequence of characters into a regular expression pattern.

The two colons “::” are used as separators to separate grammatical and regular grammar productions. Lexical and regular grammars share certain productions.

Numeric string grammar

A grammar used to convert a string to a numeric value. This grammar is similar to a part of the digital literal grammar method and has a terminator SourceCharacter.

The three colons “:::” are used as separators to separate the production of numeric string grammars.

Grammatical grammar

The ECMAScript tokens defined by the word French method are the terminators of this grammar. It defines a series of productions, from two optional Target symbol number Script as well as Module Initially, it describes the sequence of tokens that form the normal independent components of the ECMAScript program.

When a code point stream is parsed into an ECMAScript Script or ModuleIt is first converted into a stream of input elements by the lexical program; then the stream of input elements is parsed using a single grammar grammar. There is a syntax error – the token in the input element stream cannot be parsed into a single target nonterminal (Script or Module) – The input stream will not leave any tokens.

When a parse is successful, it constructs a parse tree. One root tree structure is that each node is a Parse Node . Each Parse Node is an instance of a symbol in the grammar . It represents a span of source code text derived from such symbols.

The root node of the parse tree represents the entire source code text and is parsed Target symbol An example of this. When a Parse Node is an instance of a non-terminal, it is also an instance of a production whose lvalue is a non-terminal. In addition, it has zero or more children , producing each symbol in the right-value: each child’s Parse Node is an instance of the corresponding symbol.

The new Parse Nodes are re-instantiated each time the parser is called, which means that parsing the same source text will never be reused. Considered to be the same Parse Node if and only if they represent the same source text range, are instances of the same syntax symbol, and are resolved nodes that are invoked by the same parser

NOTE 1: Parsing the same string multiple times will result in different Parse Nodes, for example:

eval(str); eval(str);

NOTE 2: Parse Nodes are artificial definitions of the specification and do not need to be implemented using similar data structures.

Use only the colon ” : ” as a separator to separate the production of grammatical lexical grammars.

But for which token sequences are correct by ECMAScript Script or Module The explanation accepted is not complete. Some additional token sequences can also be accepted. In other words, those sequences will be described by grammar as long as the semicolon is added to some part of the sequence (such as before the line terminator). In addition, some token sequences described by grammar are not accepted if a row terminator appears in some “awkward” places.

In some cases, to avoid ambiguity, the grammar grammar uses a generalized production that allows the token sequence to form an illegal ECMAScript. Script or Module.

For example, this technique is used in object literals and object deconstruction modes. In this case, a more restrictive supplemental grammar is provided that further limits the acceptable token sequence.

In general, if ” P is not covering an N “, an early error rule would define an error condition, where P is a Parse Node (an instance of a normal production) and N is a non-terminal character that complements the grammar. Here, the token sequence that originally matched P is again used as N.

Target symbol Number analysis. (If N uses syntax parameters, set them to the same value that was used when P initially parsed). If the token sequence cannot be resolved to a single instance of N , an error will be generated and no token will be left. The algorithm then accesses the parsing result of the phrase “the N that is covered by P “. This will always be a parsing node ( an instance of N that is unique to a given P ), so any parsing failure will be detected by an early error rule.

Grammar Notation

Whether in the production of grammar or in this specification, the grammar, regular grammar, and the terminology of the numeric string grammar are displayed in monospaced fonts. These will appear as scripts. All terminal code points specified in this way are interpreted as appropriate basic Latin Unicode code points, rather than from any other code point similar to the Unicode range.

Nonterminals are shown in italics .

The definition of a nonterminal (also called a production) is given by a non-terminal name and one or more colons defined afterwards. (The number of colons represents the grammar to which the production belongs.) One or more alternative right-values ​​of the non-terminal are immediately following the next line. For example, the grammar definition:

WhileStatement: While(Expression)Statement

Indicates this nonterminal WhileStatement Represents while token, followed by left parenthesis token, followed by Expression, followed by the closing parenthesis token, followed by Statement. Appeared here Expression with Statement It is itself a non-terminal.

Another example, the grammar definition:

ArgumentList: AssignmentExpression ArgumentList,AssignmentExpression

Indicate this ArgumentList Can represent one AssignmentExpression,or ArgumentList, followed by a comma followed by a AssignmentExpression.

This one ArgumentList The definition is recursive, that is, it defines itself. The result is that one ArgumentList May contain any positive arguments separated by commas, each argument expression is a AssignmentExpression. Thus, nonterminals share the definition of recursion.

A suffix subscript ” opt ” may appear for a terminator or non-terminal , indicating that it is an optional symbol. The inclusion of optional symbols actually specifies the inclusion of two right-valued values, one for omitting optional elements and the other for optional elements. this means:

VariableDeclaration:BindingIdentifier InitializerOpt

Is a simple abbreviation for the following:

VariableDeclaration:BindingIdentifier BindingIdentifier Initializer

as well as:

IterationStatement: For(LexicalDeclaration ExpressionOpt;ExpressionOpt)Statement

Is a simple abbreviation for the following:

IterationStatement:For(LexicalDeclaration;ExpressionOpt)StatementFor(LexicalDeclaration Expression;ExpressionOpt)Statement

Also an abbreviation of the following:

IterationStatement: For(LexicalDeclaration😉Statement For(LexicalDeclaration;Expression)Statement For(LexicalDeclaration Expression😉StatementFor(LexicalDeclaration Expression;Expression)Statement

So in this example, the nonterminal IterationStatement There are actually four right-values ​​to choose from.

The production can be parameterized by a subscript such as ” [parameters] “, which appears as a suffix in the non-terminal of the production definition. ” parameters ” can be either a separate name or a comma-separated list of names. The parameterized production is a series of abbreviations that produce a combination of all the combinations of parameter names beginning with an underscore and appended to the parameterized non-terminal. This means:

StatementList[Return]:ReturnStatementExpressionStatement

Is the following abbreviation:

StatementList: ReturnStatement Expression Statement StatementList_Return:ReturnStatement Expression Statement

as well as:

StatementList[Return, In]:ReturnStatement Expression Statement

Is the following abbreviation:

StatementList: ReturnStatement ExpressionStatement StatementList_Return:ReturnStatement ExpressionStatement StatementList_In: ReturnStatement ExpressionStatement StatementList_Return_In:ReturnStatement ExpressionStatement

Multiple parameters produce a combination of several productions, and it is not necessary to reference all in one complete syntax.

References to production-type non-terminal right-values ​​can also be parameterized, for example:

StatementList: ReturnStatement ExpressionStatement[+In]

Is the following abbreviation:

StatementList: ReturnStatementExpressionStatement_In

Another example:

StatementList: ReturnStatement ExpressionStatement[~In]

Is the following abbreviation:

StatementList: ReturnStatement ExpressionStatement

A non-terminal reference may have both a parameter list and an ” opt ” suffix. E.g:

VariableDeclaration: BindingIdentifier Initializer[+In]Opt

Is the following abbreviation:

VariableDeclaration: BindingIdentifierBindingIdentifierInitializer_In

In the right non-terminal reference parameter name is preceded by ” ? “, so that the parameter value depends on whether the parameter name of the left symbol reference of the current production appears. E.g:

VariableDeclaration[In]:BindingIdentifierInitializer[?In]

Is the following abbreviation:

VariableDeclaration: BindingIdentifier InitializerVariableDeclaration_In: BindingIdentifierInitializer_In

If the r value selection is prefixed with “[+parameter]”, it means that the selection is only available when the named parameter is used to reference the non-terminal character of the production. If the r value selection is prefixed with “[~parameter]”, it means that the selection is only available if the named parameter is not a non-terminal character used to reference the production. this means:

StatementList[Return]:[+Return]ReturnStatement ExpressionStatement

Is the following abbreviation:

StatementList: ExpressionStatement StatementList_Return: ReturnStatement ExpressionStatement

Another example:

StatementList[Return]:[~Return]ReturnStatement ExpressionStatement

Is the following abbreviation:

StatementList: ReturnStatement ExpressionStatement StatementList_Return: ExpressionStatement

When the word ” one of ” follows one or more semicolons in the grammar definition , the subsequent one or more lines of the terminator are an optional definition. For example, ECMAScript’s lexical method contains the following productions:

NonZeroDigit::One of 123456789

It is just the following abbreviation:

NonZeroDigit::123456789

If “[empty]” appears in a production rvalue, it implies that the right value of this production does not contain a terminator or a nonterminal.

If “[lookahead ∉ set ]” appears in a production rvalue, it implies that if the immediately entered token sequence is a member of the given set ( set ), then this production may not be used.

This collection can be represented by a comma-separated list of one or two element termination sequences wrapped in curly braces. For convenience, this collection can also be represented by a non-terminal character, in which case it represents a collection of all the terminators that can be expanded by non-terminal symbols. If the collection contains a single terminator, the phrase “[lookahead ≠ terminal ]” may be used.

For example, give a definition:

DecimalDigit::One of 0123456789 DecimalDigits:: DecimalDigit DecimalDigits DecimalDigit

Then define:

LookaheadExample::n[lookahead ∉ { 1, 3, 5, 7, 9 }]DecimalDigits DecimalDigit[lookahead ∉ DecimalDigit]

Matches the letter n followed by one or more decimal digits starting with an even number, or a decimal number followed by a non-decimal number.

Similarly, if “[lookahead ∈ set ]” appears for the right-value of the production, it means that the production-only token sequence that is entered immediately after is a member of the given set ( set ) can be used. If the collection contains only a single terminator, you can use “[lookahead == terminal ]”.

If the right side of the production appears “[no LineTerminator Here]”, then it means that this production is a restricted production: if LineTerminator Appears at the specified location of the input stream, then this production will not be applied.

For example, production:

ThrowStatement: Throw[no LineTerminator Here]Expression;

If one LineTerminator The throw token that appears in the script and Expression At the time, it implies that this production may not be used.

Unless prohibited by a restricted production LineTerminator Appear, otherwise any number LineTerminator The occurrence of this may occur between any two consecutive tokens in the input element stream and does not affect the semantic acceptability of the script.

When a multi-code point token appears in an optional part of a word French or numeric string grammar, it means that the code point sequence will form a token.

A production right value may specify some extensions that are not allowed by ” but not “, and then imply that the extension will be excluded. For example, production:

Identifier::IdentifierName But not ReservedWord

Means non-terminal Identifier May be replaced by an arbitrary sequence of code points that can be replaced by the provided IdentifierName, but the code points of the same sequence cannot be replaced. ReservedWord.

Finally, some nonterminals are described by descriptive phrases written in sans-serif fonts. In such cases, it is impractical to list all the optional parts.

SourceCharacter::Any Unicode code point

Algorithm convention

This specification typically uses a numbered list to specify the steps of the algorithm. These algorithms are used to precisely specify the semantics required for the ECMAScript language structure. This algorithm is not intended to imply any technique used by any particular implementation. In practice, perhaps a more efficient algorithm can be used to implement a given function.

The algorithm may be explicitly parameterized, in which case the parameter name and usage must be provided as part of the algorithm definition.

Algorithm steps can be subdivided into multiple consecutive sub-steps. The sub-steps need to be represented by indentation and can be further divided into sub-steps of indentation.

The outline numbering convention is used as the identification substep, the first level substeps are marked with lowercase alphabetic characters, and the second level of small steps are marked with lowercase Roman numerals. If the step exceeds three levels, then these rules are marked from the fourth level starting with the number repeat. E.g:

  1. Top-level step
    1. Substep.
    2. Substep.
      • Subsubstep.
        1. Subsubsubstep
          • Subsubsubsubstep
            • Subsubsubsubsubstep

A step or substep may use “if” to assert the condition of its substeps. In such cases, these substeps can only be applied to situations where the “if” assertion is true. If a step or substep starts with “else”, then this indicates a negative assertion of the same level of the previous “if” assertion.

A step might specify an iterator of its substeps.

A step beginning with ” Assert :” asserts a condition that is constant in its algorithm. Such assertions are used to explicitly display algorithm invariants, otherwise it will be implicit. Such assertions do not add additional semantic requirements, so implementations do not have to be checked. They are used just to make the algorithm clearer.

For any value such as “Let x be someValue “, the algorithm step may declare a named alias. These aliases are all of a similar type, ie x and someValue point to the same underlying data, and their modifications are visible to each other. Algorithm steps similar to those cited want to avoid such a need to explicitly copy the value of the right: the “Let_x_ BE A Copy of someValue ” created a someValue shallow copy.

Once the declaration is complete, the alias can be referenced in any subsequent steps and not in the steps preceding the alias declaration. The alias may be modified by a form such as “Set x to someOtherValue “.

ECMAScript Abstract operations

To facilitate their use in multiple places in this specification, some algorithms, which we call abstract operations , are named and written in the form of parameterized functions so that they can be referenced by names in other algorithms. Abstract operations are usually referenced using the function’s application style, such as OperationName( arg1 , arg2 ).

Some abstract operations are treated as if they were abstract polymorphic feeds in a class specification. Such class-like method abstractions are usually referenced by a method application style, such as someValue .OperationName( arg1 , arg2 ).

ECMAScript Syntax-oriented operations

A grammatically oriented operation is a named operation whose definition contains a series of algorithms, each associated with the production of one or more ECMAScript grammars. A production with multiple optional definitions usually has a separate algorithm for each optional part.

When an algorithm is associated with a grammar production, it may refer to the terminal or non-terminal of the optional part of the production as if they were parameters of the algorithm. When this happens, the non-terminal character points to the definition of the optional part of the actual source code that matches it.

When an algorithm is associated with an optional part of a production, this optional part is usually not preceded by a “[ ]” grammar comment. Such comments should only affect the grammatical recognition of the optional parts and should not affect the semantics of the relevant optional parts.

The syntax-directed operation is called with the same parsing node.

  1. Let status be the result of performing SyntaxDirectedOperation of Some NonTerminal.
  2. Let someParseNode be the parse of some source text.
  3. Perform SyntaxDirectedOperation of someParseNode .
  4. Perform SyntaxDirectedOperation of someParseNode passing “value”as the argument.

Unless explicitly stated otherwise, all associated productions have an implicit definition for each operation that may be applied to the non-terminal of the production lvalue. If present, this implicit definition simply applies the same definition to the same parameters again, and for each of the associated production-only right-valued non-terminals, the processing result is then returned.

For example, suppose some algorithms have the following form of steps: “Return the result of evaluation Block“, and there is a production here:

Block:{StatementList}

But the parsing operation is not associated with this production algorithm. So in such cases, the parsing operation implicitly contains the following forms of association:

Runtime semantics: Analysis

Block:{StatementList}

  1. Return the result of evaluation StatementList.

ECMAScript Runtime Semantics

The algorithm that specifies the semantics that must be called at runtime is called runtime semantics . Runtime semantics Abstract operation Or specify a syntax action to define. Such an algorithm must return a completion record.

Implicit completion value

The algorithm of this specification often implicitly returns a [[Type]] value. Normal of Completion Records. Unless an algorithm statement that returns a value is explicitly specified in the context, it returns a Completion Record Value. E.g:

  1. Return “Infinity”.

The same meaning as the following:

  1. Return NormalCompletion( “Infinity”).

However, if the value expression of a “return” statement is one Completion Record Constructed literals, then Completion Record The result will be returned. If this value expression is a pair Abstract operation Call, then the “return” statement simply returns this Abstract operation produced Completion Record.

Abstract operation Completion( compoundRecord ) is used to emphasize the previous calculation Completion Record Was returned. Completion This one Abstract operationReceive a parameter, completionRecord , and then perform the following steps:

  1. Assert: completionRecord is a Completion Record.
  2. Return completionRecord as the Completion Record Of this abstract operation.

A “return” statement with no value in the algorithm step has the same meaning as the following:

  1. Return NormalCompletion( undefined).

Need a complete for any display that is not displayed in a context Completion Record a reference to a value, equivalent to an explicit pair Completion Record a reference to the [[Value]] field, unless Completion Record Is an interrupt completed .

ECMAScript Throwing an exception

Describe the algorithm steps that throw an exception, such as:

  1. Throw a TypeError exception.

The same meaning as the following:

  1. Return ThrowCompletion(a new created TypeError Object).

ECMAScript ReturnIfAbrupt

The algorithm step description or equivalent is:

  1. ReturnIfAbrupt( argument ).

it means:

  1. If argument is an Abrupt completion, return argument .
  2. Else if argument is a Completion Record, let argument be argument .[[Value]].

The algorithm step description or equivalent is:

  1. ReturnIfAbrupt(AbstractOperation()).

The same meaning as the following:

  1. Let hygienicTemp be AbstractOperation().
  2. If hygienicTemp is an Abrupt completion, return hygienicTemp .
  3. Else if hygienicTemp is a Completion Record, let hygienicTemp be hygienicTemp .[[Value]].

The hygienicTemp here is temporary and is only visible in the steps related to ReturnIfAbrupt.

The algorithm step description or equivalent is:

  1. Let result be AbstractOperation(ReturnIfAbrupt( argument )).

The same meaning as the following:

  1. If argument is an Abrupt completion, return argument .
  2. If argument is a Completion Record, let argument be argument .[[Value]].
  3. Let result be AbstractOperation( argument ).

ECMAScript ReturnIfAbrupt Abbreviations

Correct Abstract operation And to ? imply that the calling prefix syntax specified operation ReturnIfAbrupt Need to be applied to the results Completion Record in. For example, the steps:

  1. ? OperationName().

Equivalent to the following steps:

  1. ReturnIfAbrupt(OperationName()).

Similarly, for the style of the program method, the steps are:

  1. ? someValue .OperationName().

Equivalent to:

  1. ReturnIfAbrupt( someValue .OperationName()).

Similarly, the prefix !is used to imply the following abstract syntax specified operation or calls will not return a value to complete interrupted, as a result of Completion Record The [[Value]] field should be used as the return value for the replacement operation. For example, the steps:

  1. Let val be ! OperationName().

Equivalent to the following steps:

  1. Let val be OperationName().
  2. Assert: val is never an Abrupt completion.
  3. If val is a Completion Record, set val to val .[[Value]].

For Runtime semantics Operation by replacing the specified syntax before calling the operation !or ?to use the acronym.

Perform ! SyntaxDirectedOperation of NonTerminal.

ECMAScript Static Semantics

Context-free grammars are not good enough to express all defined rules, whether it is a stream of input elements formed by a legal ECMAScript that will be parsed Script still is Module. In some cases, additional rules are required to be demonstrated using ECMAScript algorithm conventions or essay requirements. Such rules are always associated with a grammar production, called production static semantics.

Static semantic rules have names and are usually defined by an algorithm. A static semantic rule with a name is associated with a grammar production. For each static rule with a name that can be used, a production with multiple optional partial definitions usually defines a unique one for each optional part. algorithm.

Unless otherwise specified in this specification, the optional part of the grammar production implicitly contains a definition of a static semantic rule called symbol that accepts a symbol whose value contains the terminator or non-terminal of the relevant production grammar . The default inclusion definition is:

  1. For each child node child of this Parse Node, do
    • If child is an instance of symbol , return True.
    • If child is an instance of a nonterminal, then
      1. Let contained be the result of child Contains symbol .
      2. If contained is True Return True.
  2. Return False.

The above definition is an explicit rewrite of the production of the specification.

A special static semantic rule is an early (advanced) error rule . Early error rules set early error conditions, they are associated with a specific grammar production. The resolution of most early error rules is not explicitly invoked in the algorithms of this specification.

A conforming implementation must be parsed for the first time Script or Module Before, verify that all are used for parsing Script or Module The early error rules of the production. If any of the early error rules are violated, then Script or Module It is illegal and cannot be parsed.

ECMAScript Mathematical operations

Unless otherwise specified, not including infinity and not including negative 0 (in order to distinguish from positive 0), mathematical operations such as addition, subtraction, negation (logical NOT), multiplication, division, and subsequent mathematical functions defined in the clause should always It is considered to be an accurate result calculated for all real numbers in mathematics.

The floating-point operations in this specification algorithm contain explicit steps that are necessary to handle infinity, signed 0, and rounding. If a mathematical operation or function is applied to a floating point number, then it must be treated as a concrete mathematical value represented by a floating point number; such a floating point number must be finite, and if it is+0 or -0 If so, then the corresponding mathematical value is simply 0.

Mathematical function Abs( x )Used to calculate x absolute value, if x is negative, then the result is – x Otherwise the result is x itself.

Mathematical function Min( x1 , x2 , …, xN ) Calculated from X1 To xN The minimum value. Mathematical function Max( x1 , x2 , …, xN ) Calculated from X1 To xN The maximum value. The fields and scope of these mathematical functions include +∞ with -∞.

symbol”x modulo y( y must be finite and non-zero) to calculate a value k whose sign is consistent with y (or 0), such k is satisfied Abs(k) < Abs(y), and find an integer y such that x – k = q * y .

Mathematical function Floor( x )Produces a largest integer (closest to positive infinity) that is not greater than x .

NOTE

Floor( x ) = x -( x Modulo 1).

ECMAScript data types and values

The algorithm in this specification controls each value with a relevant type. The possible value types are directly defined in this section. These types are further divided into ECMAScript language types and specification types.

In this specification, the “Type( x )” notation is short for “the type of x “, where “type” refers to the ECMAScript language type and specification type defined in this section. When a value is named using the term “empty”, it is equivalent to saying “there is no type of value.”

ECMAScript language type

An ECMAScript language type corresponds to values ​​that are directly used by ECMAScript programmers in the ECMAScript language. The ECMAScript language types are Undefined, Null, Boolean, String, Symbol, Number, Object. An ECMAScript language value is a value that has the characteristics of an ECMAScript language type.

  1. Undefined type – The Undefined type has only one value, undefined. Any variable value that has not been assigned a value is undefined.
  2. Null type- The Null type has only one value, null.
  3. Boolean type – It represents a Boolean type trueand falsetwo values of a logical entity.
  4. String type – The String type is a collection of all ordered sequences of zero or more 16-bit unsigned integer values ​​(“elements”) with a maximum length of 2 53 -1 elements. The string type is typically used to represent text data in a running ECMAScript program, in which case each element in the String is treated as a UTF-16 symbol . Each element is considered to occupy a position within the sequence. These locations are indexed with non-negative integers. The first element (if any) is at index 0, the next element (if any) is at index 1, and so on. The length of a String is the number of elements in the sequence (for example, a sixteen-bit value). An empty string has a length of zero and therefore does not contain an element.

The ECMAScript operator does not apply different semantics to interpret string content. The operator interprets each element of the string as a single UTF-16 code unit. However, ECMAScript does not constrain the values ​​of these code units or the relationships between these code units, so further interpreting the contents of a string as a sequence of Unicode code points encoded in UTF-16 must take into account a subformat of the wrong format.

Such special handling operation rules are used for each code unit, so that the numerical ranges 0xD800 0xDBFF (Unicode standard is defined as the first agent , or more formally high symbol agent ) or to a range 0xDC00 0xDFFF (defined as the end of the agent , Or more formal low proxy symbols ):

  • Not First agent Nor is it Tail agent The symbols are interpreted as code points with the same value.
  • Two symbol sequences, the first symbol c1 is a First agent The second symbol c2 is a Tail agent, such two symbols are called Agent pair, is interpreted as a code point with a value of ( c1 – 0xD800) × 0x400 + ( c2 – 0xDC00) + 0x10000 .
  • One First agent or Tail agent But not one Agent pairA portion of the symbols are interpreted as code points having the same value.

Function String.prototype.normalize can explicitly standardize a string value. String.prototype.localeCompare Normalize string values ​​internally, but no other operations implicitly normalize the strings they run. Only words that are explicitly specified as language or locale sensitive will produce language-sensitive results.

NOTE: The rationale behind this design is to keep the implementation of String as simple and efficient as possible. If the ECMAScript source text conforms to Normalized Form C, the string literal guarantee is also standardized as long as they do not contain any Unicode escape sequences.

In this specification, the phrase “the string-concatenation of A , B , …” indicates that the sequence of string code units is the connection of the code units of each parameter.

Symbol type

The Symbol type is a collection of all non-string values ​​that can be used as the value of the Object property’s key.

Each possible Symbol value is unique and immutable.

Each Symbol value will always hold a value associated with it called [[Description]] (it is either Undefined Either a String value).

The well-known Symbol

The well-known Symbols are built-in Symbol values ​​that are explicitly referenced by the algorithms in this specification. They are usually used as keys for attributes whose values ​​are used as extension points for the specification algorithm. Unless otherwise stated, the value of the well-known Symbol is used by all domains shared.

Within this specification, a well-known Symbol value is referenced in the form of @@name, where “name” is a table Table 1 One of the listed values.

Table 1: Well-known Symbol

Canonical name [[Description]] Value and purpose
@@asyncIterator “Symbol.asyncIteratorReturns the object’s default Async Iterator method. By the for- await- of the semantics of the call statement.
@@hasInstance“Symbol.hasInstance”Determine the structure Function object Whether to identify the object as a method of one of the constructor instances. It made instanceof to call operator semantics.
@@isConcatSpreadable“Symbol.isConcatSpreadable”a Boolean value, if true, indicates that an object should be Array.prototype.concat Flattened into the array elements.
@@iterator“Symbol.iterator”Returns the method of an object’s default Iterator. Called by the semantics of the for-of declaration.
@@matchSymbol.match”A regular expression method that matches a string to a regular expression. By String.prototype.match Method call.
@@replace“Symbol.replace”Replace the regular expression method that matches the string substring. By String.prototype.replace Method call.
@@search“Symbol.search”A regular expression method that returns the index of the content in the string that the regular expression matches. By String.prototype.search Method call.
@@species“Symbol.species”A function value property that is used as a constructor to create a derived object.
@@split“Symbol.split”A regular expression method that splits a string at the index position where the regular expression matches. By String.prototype.split Method call.
@@toPrimitive“Symbol.toPrimitive”A method of converting an object to its corresponding original value. By Abstract operation ToPrimitive transfer.
@@toStringTag“Symbol.toStringTag”The String value property used to create the default string description for the object. Built-in method Object.prototype.toString access.
@@unscopables“Symbol.unscopables”
An object value attribute, its own and inherited attribute names are attribute names that are excluded from the with environment binding of the related object.

ECMAScript Number type

The Number type has 18437736874454810627 (ie,2 64 -2 53 +3 Values, indicating that the IEEE 754-2008 value for the double-precision 64-bit format is specified by the IEEE binary floating-point standard, except for 9007199254740990 (ie,2 53 -2 This unique “Not-a-Number” value in the IEEE standard, which is represented as a special in ECMAScript NaNvalue. (noteNaN Value in the program by NaN Expression generation) In some implementations, external code may be able to detect differences between various Not-a-Number values, but this behavior depends on the implementation; for ECMAScript code, all NaN Values ​​are indistinguishable from each other.

NOTE: After a Number value is stored, in an ArrayBuffer or a SharedArrayBuffer are not necessarily the same as the internal representation of the Number value used by the ECMAScript implementation.

There are two other special values ​​called Positive infinity with Negative infinity. For the sake of brevity, these values ​​are respectively represented by symbols. +∞ with -∞ Said. (Note that these two infinite values ​​are represented by procedural expressions +Infinity(or Infinity ) with -Infinityproduce. )

Other 18437736874454810624 (ie,2 64 -2 53 The values ​​are called finite values. Half of them are positive numbers, generally negative numbers; each finite positive number has a corresponding negative number of the same size.

Note that there is one Positive zero, One Negative zero. For the sake of simplicity, they also use+0 with -0 To illustrate. (note these two different 0, through the program expression+0 (or 0) with -0 produce. )

18437736874454810622 (ie 2 64 -2 53 -2 There are two kinds of finite non-zero values:

Of which 18428729675200069632 (ie 2 64 -2 54) values ​​are standard and have the following format

s × m × 2 e

Where s is +1 or -1, m is an integer less than 2 53 but greater than or equal to 2 52 , and e is an integer from -1074 to 971.

The remaining 9007199254740990 (ie 2 53 -2) values ​​are non-standard, with the following format

s × m × 2 e

Where s is +1 or -1, m is a positive integer less than 52, and e is -1074.

Note that all positive and negative integers with a size not greater than 2 53 can be represented in the Number type (in fact, the integer 0 has two representations, +0 with -0).

If a finite value is non-zero and the integer m used to express it (one of the two forms above) is an odd number, then the value has an odd number . Otherwise, it has an even meaning.

In this specification, when x represents an exact non-zero real mathematical quantity (or even an irrational number such as π), “the Number value for x ” means that a Number value is selected in the following manner. Consider the Number type except-0 And two values ​​that are added to the numeric type but are not renderable, 2 1024 (+1 × 2 53 × 2 971) as well as -2 1024(-1 × 2 53 × 2 971) a collection of all finite values. Select a member of this set whose value is closest to x .

If the two values ​​in the set are approximately equal, then choose the one with an even meaning; for this, 2 1024 and-2 1024 These two excess values ​​are considered to have an even meaning. Finally, if you choose 2 1024 , use+∞ Replace it; if you choose -2 1024, use -∞ Replace it; if you choose +0, if and only if x is less than zero, use-0 Replace it; any other selected values ​​do not need to be changed. The result is the Number value of x . (This process is the behavior of the IEEE 754-2008 “round to nearest, ties to even” mode.)

Some ECMAScript operators only handle closed intervals -2 31 To 2 31 -1, or 0 to 2 16 -1The integer. These operators accept values ​​of any Number type and first convert them to the values ​​in the ranges mentioned above.

ECMAScript Object type

An object is logically a collection of attributes. Each attribute is a data attribute or an accessor attribute:

  • The data attribute is associated with a key value and an ECMAScript language value and a set of properties of the Boolean type.
  • The accessor property associates a key value with one or two accessor functions and a set of properties of type Boolean. The accessor function is used to store or retrieve the ECMAScript language value associated with this property.

Attributes are identified by a key value. The key value of an attribute is an ECMAScript String value or a Symbol value. All String values ​​(including empty strings) and Symbol values ​​are valid as the key of the property. The attribute name refers to the key of the attribute and its value is a string.

A value +0or a ≤ 2 53 is an integer of 1 in a string as the attribute value key numeric index is a typical digital String. An array index is in the range +0 ≤ i < 2 32 -1 The integer.

The key of the attribute is used to access the attribute and its value. Attributes have two access methods: get and set , which respectively retrieve and assign values. Properties that are accessible through get and set include both the own property that belongs directly to it , and the inherited property that is provided by other related objects through the inheritance relationship . An inherited property may also be its own property or an inherited property of another object. Each of the object’s own properties must have a different key value than the object’s other own property key values.

All objects are logical collections of attributes, but there are multiple forms of objects in the semantics of the attributes used to access and manipulate them. Ordinary objects are the most common form of objects and have default object semantics. A singular object is an object whose attribute semantics differ from all aspects of the default semantics.

Related JavaScript Tutorials For Beginners

JavaScript Introduction Tutorials
Introduction to JavaScript
Javascript Code editors
Javascript Reference and Specifications
Javascript Developer Console
Javascript Basics
JavaScript Hello World.!
External JavaScript Files
JavaScript Code Structure
JavaScript Variables
Use Strict in JavaScript


Node.js Tutorial

Node.js Tutorial from Coding compiler. This is a very comprehensive Node tutorial for beginners covering topics like Node introduction, installation, nvm version management tool, repl environment, global objects, modular structure and exception handling. Let’s start learning Node.js.

Table of Contents

  • Introduction
  • Installation and update
  • Version management tool nvm
  • Basic usage
  • REPL environment
  • Asynchronous operation
  • Global objects and global variables
  • Modular structure
  • Overview
  • Core module
  • Custom module
  • Exception handling
  • Try…catch structure
  • Callback
  • Error event of the EventEmitter interface
  • UncaughtException event
  • unhandledRejection event
  • Command line script

Node.js Introduction

Node is the server runtime environment for the JavaScript language.

The so-called “runtime environment” has two meanings: First, the JavaScript language runs on the server through Node. In this sense, Node is a bit like a JavaScript virtual machine.

Second, Node provides a large number of tool libraries to make the JavaScript language interact with the operating system (such as reading Write files, create new subprocesses, and in this sense, Node is a tool library for JavaScript.

Node internally uses Google’s V8 engine as a JavaScript language interpreter; calls operating system resources through a self-developed libuv library.

Node.js Installation and update

Visit the official website nodejs.org or github.com/nodesource/distributions to see the latest version of Node and how to install it.

The official website provides compiled binary packages, which can be extracted under the /usr/local directory.

$ tar -xf node-someversion.tgz

Then, create symbolic links and add them to the path inside the $PATH variable.

$ ln -s /usr/local/node/bin/node /usr/local/bin/node
$ ln -s /usr/local/node/bin/npm /usr/local/bin/npm

Below is the installation method for installing the Deb package under Ubuntu and Debian.

$ curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -
$ sudo apt-get install -y nodejs
$ apt-get install nodejs

After the installation is complete, run the following command to see if it works.

$ node --version
# or
$ node -v

Updating the node.js version can be done through the n module of node.js.

$ sudo npm install n -g
$ sudo n stable

The above code n updates the node.js to the latest released stable version through the module.

N Modules can also specify to install a specific version of node.

 $ sudo n 0.10.21

Version management tool nvm

If you want to install multiple versions of node.js on the same machine at the same time, you need to use the version management tool nvm.

$ git clone https://github.com/creationix/nvm.git ~/.nvm
$ source ~/.nvm/nvm.sh

After installation, the nvm execution script should be activated before each use. It is recommended to add it to the ~/.bashrc file (assuming Bash is used). Once activated, you can install the specified version of Node.

# Install the latest version
$ nvm install node

# Install the specified version
$ nvm install 0.12.1

# Use the latest version installed
$ nvm use node

# Use the specified version of node
$ nvm use 0.12

Nvm also allows access to the specified version of the REPL environment.

$ nvm run 0.12

If you create a new .nvmrc file in the project root directory and write the version number, just enter the nvm use command and no longer need to add the version number.

Below are other commands that are often used.

# View all versions of the local installation
$ nvm ls

# View all available versions of the server.
$ nvm ls-remote

# Exit the activated nvm and use the deactivate command.
$ nvm deactivate

Basic usage

After the installation is complete, run the node.js program, which is to use the node command to read the JavaScript script.

The demo.js script file of the current directory can be executed like this.

$ node demo
# or
$ node demo.js

-eCode parameters can be executed using parameters.

$ node -e 'console.log("Hello World")'
Hello World

REPL Environment

Type the node command on the command line, followed by no file name, enter a Node.js REPL environment (Read-eval–print loop, “read-evaluate-output” loop), you can run a variety of JavaScript commands directly.

$ node
> 1+1
2
>

If the parameter –use_strict is used, the REPL will run in strict mode.

$ node --use_strict

REPL is a shell that Node.js interacts with the user. Various basic shell functions can be used inside, such as using the up and down arrow keys to traverse commands that have been used.

The special variable underscore (_) indicates the result of the previous command.

> 1 + 1
2
> _ + 1
3

In the REPL, if you run an expression, the result is returned directly on the command line. If you run a statement, there will be no output because the statement has no return value.

> x = 1
1
> var x = 1

The second command of the above code does not show any results. Because this is a statement, not an expression, there is no return value.

Asynchronous operation

Node uses the V8 engine to process JavaScript scripts. The biggest feature is that it runs in a single thread and can only run one task at a time. This causes Node to use a large number of asynchronous operations, that is, the task is not executed immediately, but inserted at the end of the task queue, and then executed after the previous task is run.

Due to this feature, subsequent operations of a task are often defined in the form of a callback.

 
var isTrue = function(value, callback) {
 if (value === true) {
   callback(null, "Value was true.");
 }
 else {
   callback(new Error("Value is not true!"));
 }
}

The above code passes the further processing to the callback function callback.

The Node convention, if a function requires a callback function as a parameter, the callback function is the last parameter. In addition, the first parameter of the callback function itself is the error object passed in the previous step.

 var callback = function (error, value) {
 if (error) {
   return console.log(error);
 }
 console.log(value);
}

In the above code, the first parameter of the callback is the Error object, and the second parameter is the real data parameter. This is because the callback function is mainly used for asynchronous operations.

When the callback function runs, the previous operation ends early, and the wrong execution stack does not exist anymore. The traditional error trapping mechanism try…catch does not work for asynchronous operations, so only Can give the error to the callback function processing.

try {
 db.User.get(userId, function(err, user) {
   if(err) {
     throw err
   }
   // ...
 })
} catch(e) {
 console.log(‘Oh no!’);
}

In the above code, the db.User.get method is an asynchronous operation. When the error is thrown, the try…catch block in which it is located may have finished running, which will cause the error to be caught. Therefore, Node uniformly stipulates that once an asynchronous operation has an error, the error object is passed to the callback function.

If no error occurs, the first argument to the callback function passes in null. This kind of writing has a great advantage, that is, as long as you judge the first parameter of the callback function, you know if there is any error. If it is not null, it will definitely be wrong. In addition, this can also pass errors in layers.

if(err) {
 // In addition to letting go of the No Permission error, other errors are passed to the next callback function.
 if(!err.noPermission) {
   return next(err);
 }
}

Global objects and global variables

Node provides the following global objects, which are called by all modules.

  • Global : indicates the global environment where Node is located, similar to the window object of the browser. It should be noted that if you declare a global variable in the browser, it actually declares the properties of a global object, such as the var x = 1 same as the setting window.x = 1, but Node is not like this, at least not in the module (the behavior of the REPL environment and the browser consistent).
  • In the module file, declare var x = 1 that the variable is not an global object’s property and global.xis equal to undefined. This is because the global variables of the module are private to the module and cannot be retrieved by other modules.
  • Process : This object represents the current process in which the Node is located, allowing developers to interact with the process.
  • Console : Point to the built-in Console module of Node to provide standard input and standard output functions in the command line environment.

Node also provides some global functions.

  • setTimeout() : Used to run the callback function after the specified number of milliseconds. The actual call interval also depends on system factors. The number of milliseconds between the intervals is between 1 millisecond and 2,147,483,647 milliseconds (about 24.8 days). If it exceeds this range, it will be automatically changed to 1 millisecond. This method returns an integer representing the number of this new timer.
  • clearTimeout() : Used to terminate a timer created by a setTimeout method.
  • setInterval() : Used to call the callback function every certain millisecond. Due to system factors, it may not be possible to guarantee exactly the number of milliseconds between each call, but only more than this interval, not less than it. The specified number of milliseconds must be an integer between 1 and 2,147,483,647 (approximately 24.8 days), and if it exceeds this range, it will be automatically changed to 1 millisecond. This method returns an integer representing the number of this new timer.
  • clearInterval() : Terminates a timer created with the setInterval method.
  • Require() : Used to load the module.
  • Buffer() : Used to manipulate binary data.

Node provides two global variables, all starting with two underscores.

  • __filename: Point to the name of the currently running script file.
  • __dirname: Point to the directory where the currently running script is located.

In addition, there are some objects that are actually local variables inside the module. The objects pointed to are different according to the module, but all modules are applicable. They can be regarded as pseudo-global variables, mainly module, module.exports, exports. Wait.

Modular Structure Overview

Node.js uses a modular structure that defines and uses modules in accordance with the CommonJS specification . The module and the file have a one-to-one correspondence, that is, loading a module, in fact, is loading a corresponding module file.

The require command is used to specify the load module. The suffix name of the script file can be omitted when loading.

var circle = require('./circle.js');
// or
var circle = require('./circle');

The argument to the require method is the name of the module file. It is divided into two cases. The first case is that the parameter contains the file path (such as the above example).

In this case, the path is relative to the directory where the current script is located. In the second case, the file path is not included in the parameter. The installation directory of the module, to find the installed modules (such as the following example).

 var bar = require('bar'); 

Sometimes a module is itself a directory with multiple files. At this time, Node looks for the module entry file specified by the main attribute in the package.json file.

{
 "name" : "bar",
 "main" : "./lib/bar.js"
}

In the above code, the module’s startup file is bar.js in the lib subdirectory. When require(‘bar’)the module is loaded with a command, the ./node_modules/bar/lib/bar.js file is actually loaded . The following method will have the same effect.

var bar = require('bar/lib/bar.js')

If there is no package.json file in the module directory, node.js will try to find the index.js or index.node file in the module directory for loading.

Once the module is loaded, it is cached by the system. If the module is loaded the second time, the version in the cache is returned, which means that the module will only be executed once.

If you want the module to execute multiple times, you can have the module return a function and then call the function multiple times.

Core Module

If you just run JavaScript code on the server, it’s not very useful, because there are many different server scripting languages. The usefulness of Node.js is that it also provides a set of functional modules that interact with the operating system. These core functional modules can be used without installation. Below is a list of them.

  • Http : Provides HTTP server functionality.
  • Url : Parse the URL.
  • Fs : Interact with the file system.
  • Querystring : A query string that parses the URL.
  • Child_process : New child process.
  • Util : Provides a set of useful gadgets.
  • Path : Process the file path.
  • Crypto : provide encryption and decryption functions, in essentially OpenSSL packaging.

The above core modules, the source code is in the lib subdirectory of Node. In order to improve the speed, they will be compiled into binary files when they are installed.

The core module is always loaded with the highest priority. If you write an HTTP module yourself, require(‘http’)the kernel module is loaded.

Custom Module

The Node module uses the CommonJS specification. As long as this specification is met, the module can be customized.

Here is the simplest module, assuming you create a new foo.js file and write the following.

// foo.js

module.exports = function(x) {
   console.log(x);
};

The above code is a module that outputs a method externally via the module.exports variable.

The use of this module is as follows.

// index.js

var m = require('./foo');

m("This is a custom module");

The above code loads the module file foo.js (the suffix is ​​omitted) by the require command, outputs the module’s external interface to the variable m, and then calls m. At this point, run index.js on the command line and the screen will output “This is a custom module.”

$ node index
This is a custom module

The module variable is the top-level variable of the entire module file, and its exports attribute is the interface that the module outputs to the outside. If you directly output a function (like foo.js above), then calling the module is calling a function. However, the module can also output an object. The following is a rewrite of foo.js.

// foo.js

var out = new Object();

function p(string) {
 console.log(string);
}

out.print = p;

module.exports = out;

The above code indicates that the module outputs an out object that has a print attribute that points to a function. Below is how to use this module.

// index.js

var m = require('./foo');

m.print("This is a custom module");

The above code indicates that since the specific method is defined on the print property of the module, the print property must be explicitly called.

Exception Handling

Node is a single-threaded runtime environment. Once the thrown exception is not caught, it will cause the entire process to crash. Therefore, Node’s exception handling is very important to ensure the stable operation of the system.

In general, Node has three methods to propagate an error.

  • Throw an error object using the throw statement, which throws an exception.
  • The error object is passed to the callback function, which is responsible for issuing the error.
  • Issue an error event via the EventEmitter interface.

Try…catch structure

The most common way to catch exceptions is to use the try…catch structure. However, this structure cannot catch exceptions thrown by code that is running asynchronously.

try {
 process.nextTick(function () {
   throw new Error("error");
 });
} catch (err) {
 //can not catch it
 console.log(err);
}

try {
 setTimeout(function(){
   throw new Error("error");
 },1)
} catch (err) {
 //can not catch it
 console.log(err);
}

The above code uses the process.next Tick and setTimeout methods to throw two exceptions in the next round of event loops, representing the errors thrown by the asynchronous operation. None of them can be caught by the catch block, because the part of the catch block is already running.

One workaround is to put the error capture code into asynchronous execution.

function async(cb, err) {
 setTimeout(function() {
   try {
     if (true)
       throw new Error("woops!");
     else
       cb("done");
   } catch(e) {
     err(e);
   }
 }, 2000)
}

async(function(res) {
 console.log("received:", res);
}, function(err) {
 console.log("Error: async threw an exception:", err);
});
// Error: async threw an exception: Error: woops!

In the above code, the async function throws an error asynchronously, which can be deployed in the asynchronous catch block capture.

Both of these treatment methods are less than ideal. In general, Node only uses try/catch statements in a few cases, such as using JSON.parse parsed JSON text.

Callback

The method used by Node is to pass the error object as the first parameter and pass it into the callback function. This avoids the problem of capturing code that is not in the same time period as the code that caused the error.

fs.readFile('/foo.txt', function(err, data) {
 if (err !== null) throw err;
 console.log(data);
});

The above code indicates that reading a file foo.txt is an asynchronous operation. Its callback function has two parameters, the first one is the error object, and the second is the file data read. If the first argument is not null, it means that an error has occurred and the code is no longer executed.

Below is a complete example.

 function async2(continuation) {
 setTimeout(function() {
   try {
     var res = 42;
     if (true)
       throw new Error("woops!");
     else
       continuation(null, res); // pass 'null' for error
   } catch(e) {
     continuation(e, null);
   }
 }, 2000);
}

async2(function(err, res) {
 if (err)
   console.log("Error: (cps) failed:", err);
 else
   console.log("(cps) received:", res);
});
// Error: (cps) failed: woops!

In the above code, the first argument to the callback function of the async2 function is an error object, which is to handle the error thrown by the asynchronous operation.

Error Event of the EventEmitter Interface

When an error occurs, you can also use the EventEmitter interface to throw an error event.

var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();

emitter.emit('error', new Error('something bad happened'));

Care must be taken to use the above code, because deploying a listener function for an error event can cause the entire application to crash. Therefore, it is always necessary to deploy the following code at the same time.

emitter.on('error', function(err) {
 console.error('Error:' + err.message);
});

UncaughtException event

When an exception is not caught, an uncaughtException event is fired, and the event can be registered with the callback function to catch the exception.

var logger = require('tracer').console();
process.on('uncaughtException', function(err) {
 console.error('Error caught in uncaughtException event:', err);
});

try {
 setTimeout(function(){
   throw new Error("error");
 },1);
} catch (err) {
 //can not catch it
 console.log(err);
}

As long as the callback is configured for uncaughtException, the Node process will not exit abnormally, but the context of the exception has been lost, and the details of the exception cannot be given.

Moreover, an exception may cause Node to fail to perform memory reclamation and memory leaks. So, when an uncaughtException is fired, it’s a good idea to log the error log and then end the Node process.

 process.on('uncaughtException', function(err) {
 logger.log(err);
 process.exit(1);
});

unhandledRejection Event

Io.js has an unhandledRejection event that listens for the rejected state of a non-captured Promise object.

var promise = new Promise(function(resolve, reject) {
 reject(new Error("Broken."));
});

promise.then(function(result) {
 console.log(result);
})

In the above code, the status of the promise becomes rejected and an error is thrown. However, there will be no reaction because no handler is set.

As long as you listen to the unhandledRejection event, you can solve this problem.

process.on('unhandledRejection', function (err, p) {
 console.error(err.stack);
})

It should be noted that the listen function of the unhandledRejection event has two parameters, the first one is the error object, and the second one is the error object that generated the error. This can provide a lot of useful information.

var http = require('http');

http.createServer(function (req, res) {
 var promise = new Promise(function(resolve, reject) {
   reject(new Error("Broken."))
 })

 promise.info = {url: req.url}
}).listen(8080)

process.on('unhandledRejection', function (err, p) {
 if (p.info && p.info.url) {
   console.log('Error in URL', p.info.url)
 }
 console.error(err.stack)
})

The above code will output the URL requested by the user when an error occurs.

Error in URL /testurl
Error: Broken.
 at /Users/mikeal/tmp/test.js:9:14
 at Server.<anonymous> (/Users/mikeal/tmp/test.js:4:17)
 at emitTwo (events.js:87:13)
 at Server.emit (events.js:169:7)
 at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:471:12)
 at HTTPParser.parserOnHeadersComplete (_http_common.js:88:23)
 at Socket.socketOnData (_http_server.js:322:22)
 at emitOne (events.js:77:13)
 at Socket.emit (events.js:166:7)
 at readableAddChunk (_stream_readable.js:145:16)

Command Line Script

The node script can be used as a command line script.

$ node foo.js

The above code executes the foo.js script file.

The first line of the foo.js file, if you add the location of the interpreter, you can call it directly as a command-line tool.

#!/usr/bin/env node

Before the call, you need to change the execution permission of the file.

$ chmod u+x foo.js
$ ./foo.js arg1 arg2 ...

Console.log Used as a command-line script for outputting content to standard output process.stdin for reading standard input child_process.exec()for executing a shell command.

Related JavaScript Tutorials For Beginners

JavaScript Introduction Tutorials
Introduction to JavaScript
Javascript Code editors
Javascript Reference and Specifications
Javascript Developer Console
Javascript Basics
JavaScript Hello World.!
External JavaScript Files
JavaScript Code Structure
JavaScript Variables
Use Strict in JavaScript

Babel Core Tutorial

Babel Core

Babel core is the API. For v5 the babel package is the CLI and depends on babel-core. For v6, the babel-cli package is the CLI (the CLI bin command is still babel though) and the babel package doesn’t do anything. Babel-runtime I guess is just the runtime (polyfill and helpers) to support code that’s already been transformed.

var babel = require("@babel/core");
import { transform } from "@babel/core";
import * as babel from "@babel/core";

All transformations will use your local configuration files.

Transform

babel.transform(code: string, options?: Object, callback: Function)

Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST.

babel.transform(code, options, function(err, result) {
 result; // => { code, map, ast }
});

Example

babel.transform("code();", options, function(err, result) {
 result.code;
 result.map;
 result.ast;
});

Compat Note:

In Babel 6, this method was synchronous and transformSync did not exist. For backward-compatibility, this function will behave synchronously if no callback is given. If you’re starting with Babel 7 and need synchronous behavior, please use transformSync since this backward-compat may be dropped in future major versions of Babel.

transformSync

babel.transformSync(code: string, options?: Object)

Transforms the passed in code. Returning an object with the generated code, source map, and AST.

babel.transformSync(code, options) // => { code, map, ast }

Example

var result = babel.transformSync("code();", options);
result.code;
result.map;
result.ast;

transformAsync

babel.transformAsync(code: string, options?: Object)

Transforms the passed in code. Returning an promise for an object with the generated code, source map, and AST.

babel.transformAsync(code, options) // => Promise<{ code, map, ast }>

Example

babel.transformAsync("code();", options).then(result => {
 result.code;
 result.map;
 result.ast;
});

transformFile

babel.transformFile(filename: string, options?: Object, callback: Function)

Asynchronously transforms the entire contents of a file.

babel.transformFile(filename, options, callback)

Example

babel.transformFile("filename.js", options, function (err, result) {
 result; // => { code, map, ast }
});

transformFileSync

babel.transformFileSync(filename: string, options?: Object)

Synchronous version of babel.transformFile. Returns the transformed contents of the filename.

babel.transformFileSync(filename, options) // => { code, map, ast }

Example

babel.transformFileSync("filename.js", options).code;

transformFileAsync

babel.transformFileAsync(filename: string, options?: Object)

Promise version of babel.transformFile. Returns a promise for the transformed contents of the filename.

babel.transformFileAsync(filename, options) // => Promise<{ code, map, ast }>
Copy

Example

babel.transformFileAsync("filename.js", options).then(result => {
 result.code;
});
Copy

transformFromAst

babel.transformFromAst(ast: Object, code?: string, options?: Object, callback: Function): FileNode | null

Given an AST, transform it.

const sourceCode = "if (true) return;";
const parsedAst = babel.parse(sourceCode, { allowReturnOutsideFunction: true });
babel.transformFromAst(parsedAst, sourceCode, options, function(err, result) {
 const { code, map, ast } = result;
});

Compat Note:

In Babel 6, this method was synchronous and transformFromAstSync did not exist. For backward-compatibility, this function will behave synchronously if no callback is given. If you’re starting with Babel 7 and need synchronous behavior, please use transformFromAstSync since this backward-compat may be dropped in future major versions of Babel.

transformFromAstSync

babel.transformFromAstSync(ast: Object, code?: string, options?: Object)

Given an AST, transform it.

const sourceCode = "if (true) return;";
const parsedAst = babel.parse(sourceCode, { allowReturnOutsideFunction: true });
const { code, map, ast } = babel.transformFromAstSync(parsedAst, sourceCode, options);

transformFromAstAsync

babel.transformFromAstAsync(ast: Object, code?: string, options?: Object)

Given an AST, transform it.

const sourceCode = "if (true) return;";
babel.parseAsync(sourceCode, { allowReturnOutsideFunction: true })
 .then(parsedAst => {
   return babel.transformFromAstSync(parsedAst, sourceCode, options);
 })
 .then(({ code, map, ast }) => {
   // ...
 });

parse

babel.parse(code: string, options?: Object, callback: Function)

Given some code, parse it using Babel’s standard behavior. Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.

Compat Note:

In Babel 7’s early betas, this method was synchronous and parseSync did not exist. For backward-compatibility, this function will behave synchronously if no callback is given. If you’re starting with Babel 7 stable and need synchronous behavior, please use parseSync since this backward-compat may be dropped in future major versions of Babel.

parseSync

babel.parseSync(code: string, options?: Object)

Returns an AST.

Given some code, parse it using Babel’s standard behavior. Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.

parseAsync

babel.parseAsync(code: string, options?: Object)

Returns a promise for an AST.

Given some code, parse it using Babel’s standard behavior. Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.

Advanced APIs

Many systems that wrap Babel like to automatically inject plugins and presets, or override options. To accomplish this goal, Babel exposes several functions that aid in loading the configuration part-way without transforming.

loadOptions

babel.loadOptions(options?: Object)

Resolve Babel’s options fully, resulting in an options object where:

  • opts.plugins is a full list of Plugin instances.
  • opts.presets is empty and all presets are flattened into opts.
  • It can be safely passed back to Babel. Fields like “babelrc” have been set to false so that later calls to Babel will not make a second attempt to load config files.

Plugin instances aren’t meant to be manipulated directly, but often callers will serialize this opts to JSON to use it as a cache key representing the options Babel has received. Caching on this isn’t 100% guaranteed to invalidate properly, but it is the best we have at the moment.

loadPartialConfig

babel.loadPartialConfig(options?: Object): PartialConfig

To allow systems to easily manipulate and validate a user’s config, this function resolves the plugins and presets and proceeds no further. The expectation is that callers will take the config’s .options, manipulate it as then see fit and pass it back to Babel again.

  • babelrc: string | void – The path of the file-relative configuration file, if there was one.
  • babelignore: string | void – The path of the .babelignore file, if there was one.
  • config: string | void – The path of the project-wide config file file, if there was one.
  • options: ValidatedOptions – The partially resolved options, which can be manipulated and passed back to Babel again.
    • plugins: Array<ConfigItem> – See below.
    • presets: Array<ConfigItem> – See below.
    • It can be safely passed back to Babel. Options like “babelrc” have been set to false so that later calls to Babel will not make a second attempt to load config files.
  • hasFilesystemConfig(): boolean – Check if the resolved config loaded any settings from the filesystem.

ConfigItem instances expose properties to introspect the values, but each item should be treated as immutable. If changes are desired, the item should be removed from the list and replaced with either a normal Babel config value, or with a replacement item created by babel.createConfigItem. See that function for information about ConfigItem fields.

createConfigItem

babel.createConfigItem(value: string | {} | Function | [string | {} | Function, {} | void], { dirname?: string, type?: "preset" | "plugin" }): ConfigItem

Allows build tooling to create and cache config items up front. If this function is called multiple times for a given plugin, Babel will call the plugin’s function itself multiple times. If you have a clear set of expected plugins and presets to inject, pre-constructing the config items would be recommended.

ConfigItem type

Each ConfigItem exposes all of the information Babel knows. The fields are:

  • value: {} | Function – The resolved value of the plugin.
  • options: {} | void – The options object passed to the plugin.
  • dirname: string – The path that the options are relative to.
  • name: string | void – The name that the user gave the plugin instance, e.g. plugins: [ [‘env’, {}, ‘my-env’] ]
  • file: Object | void – Information about the plugin’s file, if Babel knows it.
    • request: string – The file that the user requested, e.g. “@babel/env”
    • resolved: string – The full path of the resolved file, e.g. “/tmp/node_modules/@babel/preset-env/lib/index.js”

Options

  • Primary options
  • Config Loading options
  • Plugin and Preset configuration
  • Config Merging options
  • Source Map options
  • Misc options
  • Code Generator options
  • AMD / UMD / SystemJS options
  • Option concepts

Options can be passed to Babel in a variety of ways. When passed directly to Babel, you can just pass the objects object. When Babel is used via a wrapper, it may also be necessary, or at least more useful, to pass the options via configuration files.

If passing options via @babel/cli you’ll need to kebab-case the names. i.e.

npx babel --root-mode upward file.js # equivalent of passing the rootMode config option

Related JavaScript Tutorials For Beginners

JavaScript Introduction Tutorials
Introduction to JavaScript
Javascript Code editors
Javascript Reference and Specifications
Javascript Developer Console
Javascript Basics
JavaScript Hello World.!
External JavaScript Files
JavaScript Code Structure
JavaScript Variables
Use Strict in JavaScript

Babel Presets

BDon’t want to set up the plugin yourself? Then no problem! You can work with Presents. Presets can operate even shareable options configurations like a set of Babel plugins .

Official Presets

We have assembled some presets for common environments:

  • @babel/preset-env
  • @babel/preset-flow
  • @babel/preset-react
  • @babel/preset-typescript

There are many other community-maintained presets available on npm !

Stage-X (Experimental Presets)

Any conversion in stage-x presets is a change to a section that is not approved for publishing as Javascript (such as ES6 / ES2015).

Adjustable change

These proposals are subject to change, so please use them with caution , especially for proposals prior to Phase 3. We plan to update the changes to stage-x presets as soon as possible after each TC39 meeting.

TC39 divides the proposal into the following phases:

  • Stage 0 – Scarecrow: Just an idea might have a related Babel plugin.
  • Stage 1 – Proposal: Worth deep.
  • Stage 2 – Draft: Initial specification.
  • Stage 3 – Candidate: Complete specification and initial browser implementation.
  • Stage 4 – End: will be added to the next annual version.

For more information, be sure to check out the latest TC39 proposal and its process documentation .

Babel Preset – ENV

@babel/preset-env is a smart preset that allows you to use the latest JavaScript without needing to micromanage which syntax transforms (and optionally, browser polyfills) are needed by your target environment(s). This both makes your life easier and JavaScript bundles smaller!

Install

With npm:

npm install --save-dev @babel/preset-env
copy

Or yarn:

yarn add @babel/preset-env --dev
copy

How Does it Work?

@babel/preset-env would not be possible if not for a number of awesome open-source projects, like browserslist, compat-table, and electron-to-chromium.

We leverage these data sources to maintain mappings of which version of our supported target environments gained support of a JavaScript syntax or browser feature, as well as a mapping of those syntaxes and features to Babel transform plugins and core-js polyfills.

It is important to note that @babel/preset-env does not support stage-x plugins.

@babel/preset-env takes any target environments you’ve specified and checks them against its mappings to compile a list of plugins and passes it to Babel.

Browserslist Integration

For browser- or Electron-based projects, we recommend using a .browserslistrc file to specify targets. You may already have this configuration file as it is used by many tools in the ecosystem, like autoprefixer, stylelint, eslint-plugin-compat and many others.

By default @babel/preset-env will use browserslist config sources unless either the targets or ignoreBrowserslistConfig options are set.

For example, to only include polyfills and code transforms needed for users whose browsers have >0.25% market share (ignoring browsers without security updates like IE 10 and BlackBerry):

Options

 {
 "presets": [
   [
     "@babel/preset-env",
     {
       "useBuiltIns": "entry"
     }
   ]
 ]
}

browserslist

 > 0.25%
not dead

or

package.json
"browserslist": "> 0.25%, not dead"

Options

For more information on setting options for a preset, refer to the preset options documentation.

targets

string | Array<string> | { [string]: string }, defaults to {}.

Describes the environments you support/target for your project.

This can either be a browserslist-compatible query:

{
 "targets": "> 0.25%, not dead"
}

Or an object of minimum environment versions to support:

{
 "targets": {
   "chrome": "58",
   "ie": "11"
 }
}

Example environments: chrome, opera, edge, firefox, safari, ie, ios, android, node, electron.

Sidenote, if no targets are specified, @babel/preset-env will transform all ECMAScript 2015+ code by default.

We don’t recommend using preset-env this way because it doesn’t take advantage of its ability to target specific browsers.

{
 "presets": ["@babel/preset-env"]
}

targets.esmodules

boolean.

You may also target browsers supporting ES Modules (https://www.ecma-international.org/ecma-262/6.0/#sec-modules). When specifying this option, the browsers field will be ignored. You can use this approach in combination with <script type=”module”></script> to conditionally serve smaller scripts to users (https://jakearchibald.com/2017/es-modules-in-browsers/#nomodule-for-backwards-compatibility).

Please note: when specifying the es modules target, browsers targets will be ignored.

{
 "presets": [
   [
     "@babel/preset-env",
     {
       "targets": {
         "esmodules": true
       }
     }
   ]
 ]
}

targets.node

string | “current” | true.

If you want to compile against the current node version, you can specify “node”: true or “node”: “current”, which would be the same as “node”: process.versions.node.

targets.safari

string | “tp”.

If you want to compile against the technology preview version of Safari, you can specify “safari”: “tp”.

targets.browsers

string | Array<string>.

A query to select browsers (ex: last 2 versions, > 5%, safari tp) using browserslist.

Note, browsers’ results are overridden by explicit items from targets.

Note: this will be removed in later version in favor of just setting “targets” to a query directly.

spec

boolean, defaults to false.

Enable more spec compliant, but potentially slower, transformations for any plugins in this preset that support them.

loose

boolean, defaults to false.

Enable “loose” transformations for any plugins in this preset that allow them.

modules

"amd" | "umd" | "systemjs" | "commonjs" | "cjs" | "auto" | false, defaults to "auto".

Enable transformation of ES6 module syntax to another module type.

Setting this to false will not transform modules.

Also note that cjs is just an alias for commonjs.

debug

boolean, defaults to false.

Outputs the targets/plugins used and the version specified in plugin data version to console.log.

include

Array<string|RegExp>, defaults to [].

An array of plugins to always include.

Valid options include any:

  • Babel plugins – both with (@babel/plugin-transform-spread) and without prefix (plugin-transform-spread) are supported.
  • Built-ins, such as es6.map, es6.set, or es6.object.assign.

Plugin names can be fully or partially specified (or using RegExp).

Acceptable inputs:

  • Full name (string): “es6.math.sign”
  • Partial name (string): “es6.math.*” (resolves to all plugins with es6.math prefix)
  • RegExp Object: /^transform-.*$/ or new RegExp(“^transform-modules-.*”)

Note that the above . is the RegExp equivalent to match any character, and not the actual ‘.’character. Also note that to match any character .* is used in RegExp as opposed to * in globformat.

This option is useful if there is a bug in a native implementation, or a combination of a non-supported feature + a supported one doesn’t work.

For example, Node 4 supports native classes but not spread. If super is used with a spread argument, then the @babel/plugin-transform-classes transform needs to be included, as it is not possible to transpile a spread with super otherwise.

NOTE: The include and exclude options only work with the plugins included with this preset; so, for example, including @babel/plugin-proposal-do-expressions or excluding @babel/plugin-proposal-function-bind will throw errors. To use a plugin not included with this preset, add them to your “plugins” directly.

exclude

Array<string|RegExp>, defaults to [].

An array of plugins to always exclude/remove.

The possible options are the same as the include option.

This option is useful for “blacklisting” a transform like @babel/plugin-transform-regenerator if you don’t use generators and don’t want to include regeneratorRuntime (when using useBuiltIns) or for using another plugin like fast-async instead of Babel’s async-to-gen.

useBuiltIns

"usage" | "entry" | false, defaults to false.

This option adds direct references to the core-js module as bare imports. Thus core-js will be resolved relative to the file itself and needs to be accessible. You may need to specify [email protected] as a top level dependency in your application if there isn’t a core-js dependency or there are multiple versions.

This option configures how @babel/preset-env handles polyfills.

useBuiltIns: ‘entry’

NOTE: Only use require(“@babel/polyfill”); once in your whole app. Multiple imports or requires of @babel/polyfill will throw an error since it can cause global collisions and other issues that are hard to trace. We recommend creating a single entry file that only contains the require statement.

This option enables a new plugin that replaces the statement import “@babel/polyfill” or require(“@babel/polyfill”) with individual requires for @babel/polyfill based on environment.npm install @babel/polyfill –save

In

import "@babel/polyfill";

Out (different based on environment)

import "core-js/modules/es7.string.pad-start";
import "core-js/modules/es7.string.pad-end";

his will also work for core-js directly (import “core-js”; or require(‘core-js’);)

useBuiltIns: ‘usage’ (experimental)

Adds specific imports for polyfills when they are used in each file. We take advantage of the fact that a bundler will load the same polyfill only once.

In 
a.js
var a = new Promise();
b.js
var b = new Map();

Out (if environment doesn’t support it)

import "core-js/modules/es6.promise";
var a = new Promise();
import "core-js/modules/es6.map";
var b = new Map();

Out (if environment doesn’t support it)

import "core-js/modules/es6.promise";
var a = new Promise();
import "core-js/modules/es6.map";
var b = new Map();

Out (if environment supports it)

var a = new Promise();
var b = new Map();

useBuiltIns: false

Don’t add polyfills automatically per file, or transform import “@babel/polyfill” to individual polyfills.

forceAllTransforms

boolean, defaults to false.

Example

NOTE: targets.uglify is deprecated and will be removed in the next major in favor of this.

By default, this preset will run all the transforms needed for the targeted environment(s). Enable this option if you want to force running all transforms, which is useful if the output will be run through UglifyJS or an environment that only supports ES5.

NOTE: Uglify has a work-in-progress “Harmony” branch to address the lack of ES6 support, but it is not yet stable. You can follow its progress in UglifyJS2 issue #448. If you require an alternative minifier which does support ES6 syntax, we recommend using babel-minify.

configPath

string, defaults to process.cwd()

The starting point where the config search for browserslist will start, and ascend to the system root until found.

ignoreBrowserslistConfig

boolean, defaults to false

Toggles whether or not browserslist config sources are used, which includes searching for any browserslist files or referencing the browserslist key inside package.json. This is useful for projects that use a browserslist config for files that won’t be compiled with Babel.

shippedProposals

boolean, defaults to false

Toggles enabling support for built-in/feature proposals that have shipped in browsers. If your target environments have native support for a feature proposal, its matching parser syntax plugin is enabled instead of performing any transform. Note that this does not enable the same transformations as @babel/preset-stage-3, since proposals can continue to change before landing in browsers.

The following are currently supported:

Builtins

Features

  • None

Babel Preset – Stage-0

As of Babel v7, all the stage presets have been deprecated. Check the blog post for more information.For upgrade instructions, see the README.

Install

npm install --save-dev @babel/preset-stage-0

Usage

Via .babelrc (Recommended)

.babelrc
{
 "presets": ["@babel/preset-stage-0"]
}

Via CLI

babel script.js --presets @babel/preset-stage-0

Via Node API

require("@babel/core").transform("code", {
 presets: ["@babel/preset-stage-0"]
});

Options

loose

boolean, defaults to false.

Enable “loose” transformations for any plugins in this preset that allow them.

useBuiltIns

boolean, defaults to false.

Will use the native built-in instead of trying to polyfill behavior for any plugins that require one.

decoratorsLegacy

boolean, defaults to false.

Use the legacy (stage 1) decorators syntax and behavior.

Babel Preset – Stage-1

As of Babel v7, all the stage presets have been deprecated.

For upgrade instructions, see the README.

The gist of Stage 1 is:

Stage 1: proposal

What is it?

A formal proposal for the feature.

What’s required?

A so-called champion must be identified who is responsible for the proposal. Either the champion or a co-champion must be a member of TC39 (source). The problem solved by the proposal must be described in prose.

The solution must be described via examples, an API and a discussion of semantics and algorithms. Lastly, potential obstacles for the proposal must be identified, such as interactions with other features and implementation challenges. Implementation-wise, polyfills and demos are needed.

What’s next?

By accepting a proposal for stage 1, TC39 declares its willingness to examine, discuss and contribute to the proposal. Going forward, major changes to the proposal are expected

Install

npm install --save-dev @babel/preset-stage-1

Usage

Via .babelrc (Recommended)

.babelrc
{
 "presets": ["@babel/preset-stage-1"]
}

Via CLI

babel script.js --presets @babel/preset-stage-1

Via Node API

require("@babel/core").transform("code", {
 presets: ["@babel/preset-stage-1"]
});

Options

loose

boolean, defaults to false.

Enable “loose” transformations for any plugins in this preset that allow them.

useBuiltIns

boolean, defaults to false.

Will use the native built-in instead of trying to polyfill behavior for any plugins that require one.

decoratorsLegacy

boolean, defaults to false.

Use the legacy (stage 1) decorators syntax and behavior.

Babel Preset – Stage-2

As of Babel v7, all the stage presets have been deprecated.

For upgrade instructions, see the README.

The gist of Stage 2 is:

Stage 2: draft

What is it?

A first version of what will be in the specification. At this point, an eventual inclusion of the feature in the standard is likely.

What’s required?

The proposal must now additionally have a formal description of the syntax and semantics of the feature (using the formal language of the ECMAScript specification).

The description should be as complete as possible, but can contain todos and placeholders. Two experimental implementations of the feature are needed, but one of them can be in a transpiler such as Babel.

What’s next?

Only incremental changes are expected from now on.

Install

npm install --save-dev @babel/preset-stage-2

Usage

Via .babelrc (Recommended)

.babelrc

{
 "presets": ["@babel/preset-stage-2"]
}

Via CLI

babel script.js --presets @babel/preset-stage-2

Via Node API

require("@babel/core").transform("code", {
 presets: ["@babel/preset-stage-2"]
});

Options

loose

boolean, defaults to false.

Enable “loose” transformations for any plugins in this preset that allow them.

useBuiltIns

boolean, defaults to false.

Will use the native built-in instead of trying to polyfill behavior for any plugins that require one.

decoratorsLegacy

boolean, defaults to false.

Use the legacy (stage 1) decorators syntax and behavior.

Babel Preset – Stage-3

As of Babel v7, all the stage presets have been deprecated.

For upgrade instructions, see the README.

The gist of Stage 3 is:

Stage 3: candidate

What is it?

The proposal is mostly finished and now needs feedback from implementations and users to progress further.

What’s required?

The spec text must be complete. Designated reviewers (appointed by TC39, not by the champion) and the ECMAScript spec editor must sign off on the spec text. There must be at least two spec-compliant implementations (which don’t have to be enabled by default).

What’s next?

Henceforth, changes should only be made in response to critical issues raised by the implementations and their use.

Install

npm install --save-dev @babel/preset-stage-3

Usage

Via .babelrc (Recommended)

.babelrc

{
 "presets": ["@babel/preset-stage-3"]
}

Via CLI

babel script.js --presets @babel/preset-stage-3

Via Node API

require("@babel/core").transform("code", {
 presets: ["@babel/preset-stage-3"]
});

Options

loose

boolean, defaults to false.

Enable “loose” transformations for any plugins in this preset that allow them.

useBuiltIns

boolean, defaults to false.

Will use the native built-in instead of trying to polyfill behavior for any plugins that require one.

Babel Preset – Flow

This preset includes the following plugins:

  • @babel/plugin-transform-flow-strip-types

Example

In

function foo(one: any, two: number, three?): string {}
Copy

Out

function foo(one, two, three) {}

Installation

npm install --save-dev @babel/preset-flow

Usage

Via .babelrc (Recommended)

.babelrc

{
 "presets": ["@babel/preset-flow"]
}

Via CLI

babel --presets @babel/preset-flow script.js

Via Node API

require("@babel/core").transform("code", {
 presets: ["@babel/preset-flow"],
});

Babel Preset – React

This preset always includes the following plugins:

  • @babel/plugin-syntax-jsx
  • @babel/plugin-transform-react-jsx
  • @babel/plugin-transform-react-display-name

And with the development option:

  • @babel/plugin-transform-react-jsx-self
  • @babel/plugin-transform-react-jsx-source

Note: Flow syntax support is no longer enabled in v7. For that, you will need to add the Flow preset.

Installation

You can also check out the React Getting Started page

npm install --save-dev @babel/preset-react

Usage

Via .babelrc (Recommended)

.babelrc

Without options:

{
 "presets": ["@babel/preset-react"]
}

With options:

{
 "presets": [
   [
     "@babel/preset-react",
     {
       "pragma": "dom", // default pragma is React.createElement
       "pragmaFrag": "DomFrag", // default is React.Fragment
       "throwIfNamespace": false // defaults to true
     }
   ]
 ]
}

Via CLI

babel --presets @babel/preset-react script.js

Via Node API

require("@babel/core").transform("code", {
 presets: ["@babel/preset-react"],
});

Options

pragma

string, defaults to React.createElement.

Replace the function used when compiling JSX expressions.

pragmaFrag

string, defaults to React.Fragment.

Replace the component used when compiling JSX fragments.

useBuiltIns

boolean, defaults to false.

Will use the native built-in instead of trying to polyfill behavior for any plugins that require one.

development

boolean, defaults to false.

Toggles plugins that aid in development, such as @babel/plugin-transform-react-jsx-self and @babel/plugin-transform-react-jsx-source.

This is useful when combined with the env option configuration or js config files.

throwIfNamespace

boolean, defaults to true.

Toggles whether or not to throw an error if a XML namespaced tag name is used. For example:

<f:image />

Though the JSX spec allows this, it is disabled by default since React’s JSX does not currently have support for it.

.babelrc.js

module.exports = {
 presets: [
   [
     "@babel/preset-react",
     {
       development: process.env.BABEL_ENV === "development",
     },
   ],
 ],
};

.babelrc

Note: the env option will likely get deprecated soon

{
 "presets": ["@babel/preset-react"],
 "env": {
   "development": {
     "presets": [["@babel/preset-react", { "development": true }]]
   }
 }
}

Babel Preset – Minify

  • Install
  • Usage
  • Options

Install

npm install babel-preset-minify --save-dev

Usage

Via .babelrc (Recommended)

.babelrc

{
 "presets": ["minify"]
}

or pass in options –

{
 "presets": [["minify", {
   "mangle": {
     "exclude": ["MyCustomError"]
   },
   "unsafe": {
     "typeConstructors": false
   },
   "keepFnName": true
 }]]
}

Via CLI

babel script.js --presets minify

Via Node API

require("@babel/core").transform("code", {
 presets: ["minify"]
});

Options

Two types of options:

  1. 1-1 mapping with plugin
  2. The same option passed to multiple plugins

1-1 mapping with plugin

  • false – disable plugin
  • true – enable plugin
  • { …pluginOpts } – enable plugin and pass pluginOpts to plugin

Examples

{
 "presets": [["minify", {
   "evaluate": false,
   "mangle": true
 }]]
}
{
 "presets": [["minify", {
   "mangle": {
     "exclude": ["ParserError", "NetworkError"]
   }
 }]]
}
{
 "presets": [["minify", {
   "keepFnName": true
 }]]
}
// is the same as
{
 "presets": [["minify", {
   "mangle": {
     "keepFnName": true
   },
   "deadcode": {
     "keepFnName": true
   }
 }]]
}

Babel Preset – Typescript

This preset includes the following plugins:

  • @babel/plugin-transform-typescript

You will need to specify –extensions “.ts” for @babel/cli & @babel/node cli’s to handle .ts files.

Example

In

const x: number = 0

Out

const x = 0;

Installation

npm install --save-dev @babel/preset-typescript

Usage

Via .babelrc (Recommended)

.babelrc

{
 "presets": ["@babel/preset-typescript"]
}

Via CLI

babel --presets @babel/preset-typescript script.ts

Via Node API

require("@babel/core").transform("code", {
 presets: ["@babel/preset-typescript"],
});

Options

isTSX

boolean, defaults to false.

Forcibly enables jsx parsing. Otherwise angle brackets will be treated as typescript’s legacy type assertion var foo = <string>bar;. Also, isTSX: true requires allExtensions: true

jsxPragma

string, defaults to React.

Replace the function used when compiling JSX expressions.

This is so that we know that the import is not a type import, and should not be removed

allExtensions

boolean, defaults to false.

Indicates that every file should be parsed as TS or TSX (depending on the isTSX option)

Related JavaScript Tutorials For Beginners

JavaScript Introduction Tutorials
Introduction to JavaScript
Javascript Code editors
Javascript Reference and Specifications
Javascript Developer Console
Javascript Basics
JavaScript Hello World.!
External JavaScript Files
JavaScript Code Structure
Use Strict in JavaScript
JavaScript Variables


Babel CLI & Babel Polyfill Tutorial

Babel CLI

Babel comes with a built-in CLI which can be used to compile files from the command line.

In addition, various entry point scripts live in the top-level package at @babel/cli/bin. There is a shell-executable utility script, babel-external-helpers.js, and the main Babel cli script, babel.js.

Install

While you can install Babel CLI globally on your machine, it’s much better to install it locally project by project.

There are two primary reasons for this.

  1. Different projects on the same machine can depend on different versions of Babel allowing you to update them individually.
  2. Not having an implicit dependency on the environment you are working in makes your project far more portable and easier to setup.

We can install Babel CLI locally by running:

npm install --save-dev @babel/core @babel/cli
Copy

Note: If you do not have a package.json, create one before installing. This will ensure proper interaction with the npx command.

After that finishes installing, your package.json file should include:

 {
 "devDependencies": {
+   "@babel/cli": "^7.0.0",
+   "@babel/core": "^7.0.0"
 }
}

Usage

babel script.js

Note: These instructions use the excellent npx command to run the locally installed executables. You can drop it inside of an npm run script or you may instead execute with the relative path instead. ./node_modules/.bin/babel

Compile Files

Compile the file script.js and output to stdout.

npx babel script.js
# output...

If you would like to output to a file you may use –out-file or -o.

npx babel script.js --out-file script-compiled.js

To compile a file every time that you change it, use the –watch or -w option:npx babel script.js –watch –out-file script-compiled.js

Compile with Source Maps

If you would then like to add a source map file you can use –source-maps or -s. Learn more about source maps.

npx babel script.js --out-file script-compiled.js --source-maps

Or, if you’d rather have inline source maps, use –source-maps inline instead.npx babel script.js –out-file script-compiled.js –source-maps inline

Compile Directories

Compile the entire src directory and output it to the lib directory by using either –out-dir or -d. This doesn’t overwrite any other files or directories in lib.

npx babel src --out-dir lib

Compile the entire src directory and output it as a single concatenated file.npx babel src –out-file script-compiled.js

Ignore files

Ignore spec and test files

npx babel src --out-dir lib --ignore "src/**/*.spec.js","src/**/*.test.js"

Copy files

Copy files that will not be compilednpx babel src –out-dir lib –copy-files

npx babel src --out-dir lib --copy-files

Piping Files

Pipe a file in via stdin and output it to script-compiled.js

npx babel --out-file script-compiled.js < script.js

Using Plugins

Use the –plugins option to specify plugins to use in compilation

npx babel script.js --out-file script-compiled.js [email protected]/proposal-class-properties,@babel/transform-modules-amd

Using Presets

Use the –presets option to specify plugins to use in compilation

npx babel script.js --out-file script-compiled.js [email protected]/preset-env,@babel/flow

Ignoring .babelrc

Ignore the configuration from the project’s .babelrc file and use the cli options e.g. for a custom build

 npx babel --no-babelrc script.js --out-file script-compiled.js --presets=es2015,react

Advanced Usage

There are many more options available, babel –help and other sections for more information.

Babel Polyfill

Babel includes a polyfill that includes a custom regenerator runtime and core-js.

This will emulate a full ES2015+ environment (no < Stage 4 proposals) and is intended to be used in an application rather than a library/tool. (this polyfill is automatically loaded when using babel-node).

This means you can use new built-ins like Promise or WeakMap, static methods like Array.from or Object.assign, instance methods like Array.prototype.includes, and generator functions (provided you use the regenerator plugin). The polyfill adds to the global scope as well as native prototypes like String in order to do this.

Installation

npm install --save @babel/polyfill
copy

Because this is a polyfill (which will run before your source code), we need it to be a dependency, not a devDependency

Size

The polyfill is provided as a convenience but you should use it with @babel/preset-env and the useBuiltIns option so that it doesn’t include the whole polyfill which isn’t always needed. Otherwise, we would recommend you import the individual polyfills manually.

TC39 Proposals

If you need to use a proposal that is not Stage 4, @babel/polyfill will not automatically import those for you. You will have to import those from another polyfill like core-js individually. We may work towards including this as separate files in @babel/polyfill soon.

Usage in Node / Browserify / Webpack

To include the polyfill you need to require it at the top of the entry point to your application.

Make sure it is called before all other code/require statements!

 require("@babel/polyfill");

If you are using ES6’s import syntax in your application’s entry point, you should instead import the polyfill at the top of the entry point to ensure the polyfills are loaded first:

import "@babel/polyfill";

With webpack, there are multiple ways to include the polyfills:

  • When used alongside @babel/preset-env,
    • If useBuiltIns: ‘usage’ is specified in .babelrc then do not include @babel/polyfill in either webpack.config.js entry array nor source. Note, @babel/polyfill still needs to be installed.
    • If useBuiltIns: ‘entry’ is specified in .babelrc then include @babel/polyfill at the top of the entry point to your application via require or import as discussed above.
    • If useBuiltIns key is not specified or it is explicitly set with useBuiltIns: false in your .babelrc, add @babel/polyfill directly to the entry array in your webpack.config.js.
module.exports = {
 entry: ["@babel/polyfill", "./app/js"],
};
  • If @babel/preset-env is not used then add @babel/polyfill to webpack entry array as discussed above. It can still be added at the top of the entry point to application via import or require, but this is not recommended.

We do not recommend that you import the whole polyfill directly: either try the useBuiltInsoptions or import only the polyfills you need manually (either from this package or somewhere else).

Usage in Browser

Available from the dist/polyfill.js file within a @babel/polyfill npm release. This needs to be included before all your compiled Babel code. You can either prepend it to your compiled code or include it in a <script> before it.

NOTE: Do not require this via browserify etc, use @babel/polyfill.

Details

If you are looking for something that won’t modify globals to be used in a tool/library, checkout the transform-runtime plugin. This means you won’t be able to use the instance methods mentioned above like Array.prototype.includes.

Note: Depending on what ES2015 methods you actually use, you may not need to use @babel/polyfill or the runtime plugin. You may want to only load the specific polyfills you are using(like Object.assign) or just document that the environment the library is being loaded in should include certain polyfills.

Related JavaScript Tutorials For Beginners

JavaScript Introduction Tutorials
Introduction to JavaScript
Javascript Code editors
Javascript Reference and Specifications
Javascript Developer Console
Javascript Basics
JavaScript Hello World.!
External JavaScript Files
JavaScript Code Structure
JavaScript Variables
Use Strict in JavaScript