Tiny ES6 Notebook Curated JavaScript Examples
Tiny ES6 Notebook Curated JavaScript Examples
Introduction
Strict Mode
Variables
Types
Numbers
Built-in Types
Built-in Functions
Unicode
Functions
Classes
Operators
Conditionals
Looping
Exceptions
Generators
Modules
Promises
Regular Expressions
About the Author
Also Available
One more thing
Introduction
THIS IS NOT SO MUCH AN INSTRUCTIONAL MANUAL, BUT RATHER NOTES, TABLES, AND
examples for ECMAScript2015 or ES6 syntax (aka modern JavaScript). It was
created by the author as an additional resource during training, meant to be
distributed as a physical notebook. Participants (who favor the physical
characteristics of dead tree material) could add their own notes, thoughts, and have a
valuable reference of curated examples.
Strict Mode
ES6 MODULES ARE ALWAYS STRICT ACCORDING TO THE SPEC. THERE SHOULD BE NO NEED TO
place this code at the top of your code to enable strict mode:
'use strict';
THERE ARE VARIOUS WAYS TO DECLARE A VARIABLE IN ES6. FUNCTION LOCAL VARIABLES ARE
declared with var, block variables are declared with let, and constant variables are
declared with const:
const PI = 3.14
function add(x, y) {
result = x + y // Implicit global
return result
}
add(3, 4)
console.log(result) // prints 7!
function sub(x, y) {
let val = x + y
return val
}
sub(42, 2)
//console.log(val) // ReferenceError
NOTE
Constant variables are not necessarily immutable (their value can change), but
they can't be rebound to another object or primitive.
TIP
A good rule of thumb is to use const as the default declaration. Use let only if
needed and try to stay away from var.
Scoping
The following function illustrates scoping with the let declaration:
function scopetest() {
//console.log(1, x) //ReferenceError
let x
console.log(2, x)
x = 42
console.log(3, x)
if (true) {
//console.log(4, x) // ReferenceError
let x
console.log(5, x)
x = 17
console.log(6, x)
}
console.log(7, x)
}
// inst is undefined
THERE ARE TWO TYPES OF DATA IN ES6, PRIMITIVES AND OBJECTS. ES6 HAS SIX PRIMITIVE,
immutable data types: string, number, boolean, null, undefined, and symbol (new in
ECMAScript 2015). When we use the literals we get a primitive. ES6 does
autoboxing when we invoke a method on them. There are also object wrappers for
string, number, boolean, and symbol. They are String, Number, Boolean, and Symbol
respectively. If you call the constructor with new, you will get back on object, to get
the primitive value call .valueOf().
null
NOTE
Even though null is a primitive, the result of typeof is an object. This is
according to the spec 1 (though it is considered a wart).
undefined
A property of the global object whose value is the primitive value undefined. A
variable that has been declared but not assigned has the value of undefined:
let x // x is undefined
1 0 or -0
"string" "" (empty string)
[] (empty list) undefined
{} (empty object)
Boolean(new Boolean(false))
Boolean Properties
PROPERTY DESCRIPTION
Boolean.length 1
Boolean.prototype The Boolean prototype
NOTE
Array spread is an ES6 feature. Object spread is not, though many JS engines
support it.
If we want to include properties in another object, we can do a shallow
spread:
const p2 = { ...person, copy: true }
Object can be called as a constructor (with new) and as a function. Both behave
the same and wrap what they were called with with an object.
Using the methods Object.defineProperties and Object.defineProperty, we
can set properties using data descriptors or accessor descriptors.
An accessor descriptor allows us to create functions (get and set) to define
member access. It looks like this:
{
configurable: false, // default
enumerable: false, // default
get: getFunc, // function to get prop, default undefined
set: setFunc, // function to set prop, default undefined
}
A data descriptor allows us to create a value for a property and to set whether it is
writeable. It looks like this:
{
configurable: false, // default
enumerable: false, // default
value: val // default undefined
writeable: false, // default
}
If configurable has the value of false, then no value besides writeable can be
changed with Object.defineProperty. Also, the property cannot be deleted.
The enumerable property determines if the property shows up in Object.keys()
or a for ... in loop.
An example of a accessor descriptor:
function Person(fname) {
let name = fname;
Object.defineProperty(this, 'name', {
get: function() {
// if you say this.name here
// you will blow the stack
if (name === 'Richard') {
return 'Ringo';
}
return name;
},
set: function(n) {
name = n
}
});
}
Object Properties
PROPERTY DESCRIPTION
Object.prototype The objects prototype
Object.prototype.__proto__ value: null
Object Methods
METHOD DESCRIPTION
Object.assign(target, Copy properties from sources into target
...sources)
Object.create(obj, [prop]) Create a new object with prototype of obj and properties from
prop
Object.getOwnProperty Return array of string of string properties found on obj that aren't
Names(obj) in prototype chain
Object.getOwnProperty Return array of symbols of symbol properties found on obj that
Symbols(obj) aren't in prototype chain
Object.getPrototypeOf( Return the prototype of obj
obj)
Object.is(a, b) Boolean whether the values are the same. Doesn't coerce like ==.
Also, unlike ===, doesn't treat -0 equal to +0, or NaN not equal to
NaN.
1 - http://www.ecma-international.org/ecma-262/6.0/#sec-typeof-operator-
runtime-semantics-evaluation
Numbers
NaN
NaN is a global property to represent not a number. This is the result of certain math
failures, such as the square root of a negative number. The function isNaN will test
whether a value is NaN.
Infinity
Number types
TYPE EXAMPLE
Integer 14
Float 14.0
Float 1.4e1
Number Properties
PROPERTY DESCRIPTION
Number.EPSILON Smallest value between numbers 2.220446049250313e-16
Number.MAX_SAFE_INTEGER Largest integer 9007199254740991 (2^53 - 1)
Number Methods
Number Methods
METHOD DESCRIPTION
n.isFinite(val) Test if val is finite
n.isInteger(val) Test if val is integer
n.isNaN(val) Test if val is NaN
n.isSafeInteger(val) Test if val is integer between safe values
n.parseFloat(s) Convert string, s to number (or NaN)
n.parseInt(s, [radix]) Convert string, s to integer (or NaN) for given base (radix)
Math Properties
PROPERTY DESCRIPTION
Math.E value: 2.718281828459045
Math.LN10 value: 2.302585092994046
Math.LN2 value: 0.6931471805599453
Math.LOG10E value: 0.4342944819032518
Math.LOG2E value: 1.4426950408889634
Math.PI value: 3.141592653589793
Math.SQRT1_2 value: 0.7071067811865476
Math.SQRT2 value: 1.4142135623730951
Math Methods
METHOD DESCRIPTION
Math.abs(n) Compute absolute value
Math.acos(n) Compute arccosine
Math.acosh(n) Compute hyperbolic arccosine
Math.asin(n) Compute arcsine
Math.asinh(n) Compute hyperbolic arcsine
Math.atan(n) Compute arctangent
Math.atan2(y, x) Compute arctangent of quotient
Math.atanh(n) Compute hyperbolic arctangent
Math.cbrt(n) Compute cube root
Math.ceil(n) Compute the smallest integer larger than n
Math.clz32(n) Compute count of leading zeros
Math.cos(n) Compute cosine
Math.cosh(n) Compute hyperbolic cosine
Math.exp(x) Compute e to the x
Math.expm1(x) Compute e to the x minux 1
Math.floor(n) Compute largest integer smaller than n
Math.fround(n) Compute nearest float
Math.hypot(x, [y], [...) Compute hypotenuse (square root of sums)
Math.imul(x, y) Compute integer product
Math.log(n) Compute natural log
Math.log10(n) Compute log base 10
Math.log1p(n) Compute natural log of 1 + n
Math.log2(n) Compute log base 2
Math.max(...) Compute maximum
Math.min(...) Compute minimum
Math.pow(x, y) Compute x to the y power
Math.random() Random number between 0 and 1
Math.round(n) Compute nearest integer
Math.sign(n) Return -1, 0, or 1 for negative, zero, or positive value of n
Math.sin(n) Compute sine
Math.sinh(n) Compute hyperbolic sine
Math.sqrt(n) Compute square root
Math.tan(n) Compute tangent
Math.tanh(n) Compute hyperbolic tangent
Math.trunc(b) Compute integer value without decimal
Built-in Types
Strings
ES6 strings are series of UTF-16 code units. A string literal can be created with
single or double quotes:
let n1 = 'Paul'
let n2 = "John"
To make long strings you can use to backslash to signify that the string continues
on the following line:
let longLine = "Lorum ipsum \
fooish bar \
the end"
String Properties
PROPERTY DESCRIPTION
String.length value: 1
String.name value: String
String.prototype Prototype for String constructor
String.raw Create a raw template literal (follow this by your string surrounded
by back ticks)
s.p.match(reg) Return an array with the whole match in index 0, remaining entries
correspond to parentheses
s.p.normalize([unf]) Return the Unicode Normalization Form of a string. unf can be "NFC",
"NFD", "NFKC", or "NFKD"
NOTE
Many of the HTML generating methods create markup that is not compatible
with HTML5.
Arrays
ES6 arrays can be created with the literal syntax or by calling the Array constructor:
let people = ['Paul', 'John', 'George']
people.push('Ringo')
console.log(people)
//["Paul", "John", "George", "Ringo", 6: "Billy"]
If we need the index number during iteration, the entries method gives us a list
of index, item pairs:
for (let [i, name] of people.entries()) {
console.log(`${i} - ${name}`);
}
// Output
// 0 - Paul
// 1 - John
// 2 - George
// 3 - Ringo
// 4 - undefined
// 5 - undefined
// 6 - Billy
Array Properties
PROPERTY DESCRIPTION
Array.length value: 1
Array.name value: Array
Array.prototype Prototype for Array constructor
Array Methods
METHOD DESCRIPTION
Array.from(iter, Return a new Array from an iterable. func will be called on every item.
[func, [this]]) this is a value to use for this when executing func.
a.p.find(func, [this]) Return first item (or undefined) from a where predicate func(item,
[idx, [a]]) is true. this is the value of this for the function
a.p.findIndex(func, Return first index (or -1) from a where predicate func(item, [idx,
[this]) [a]]) is true. this is the value of this for the function
a.p.indexOf(val, Return first index (or -1) of val in a, starting from start index
[start])
a.p.join([sep]) Return string with sep (default ',') inserted between items
a.p.keys() Return iterator of index values (doesn't skip sparse values)
a.p.lastIndexOf(val, Return last index (or -1) of val in a, searching backwards from start
[start]) index
a.p.map(func, [this]) Return new array with func(item, [idx, [a]]) called on every item of
a. this is the value of this for the function
a.p.splice(start, Return array with deleted objects. Mutate a at index start, remove
[deleteCount, [item1, deleteCount items, and insert items.
..., itemN]])
ArrayBuffer Properties
PROPERTY DESCRIPTION
ArrayBuffer.length 1
To put a typed array into a normal array, we can use the spread operator:
let normal = [...primes]
Typed Arrays
TYPE SIZE (BYTES) DESCTRIPTION C TYPE
Int8Array 1 signed integer int8_t
The following Array methods are missing: push, pop, shift, splice, and
unshift.
t.p.subarray(start, Return TypeArray with view of data in t starting at position start up to but
[end]) not including end. Note that the t and the new object share the data.
Data Views
A DataView is another interface for interacting with an ArrayBuffer. If you need
control over endianness, you should use this rather than a typed array.
let buf = new ArrayBuffer(2)
let dv = new DataView(buf)
let littleEndian = true;
let offset = 0
dv.setInt16(offset, 512, littleEndian)
DataView Properties
PROPERTY DESCRIPTION
DataView.name DataView
If an integer is provided, you will get the seconds from the Unix epoch:
let msPast1970 = 1
let groovyTime = new Date(msPast1970)
The ES6 spec only supports a variant of ISO8601, but in practice a string in RFC
2822/1123 is also supported:
let modern = new Date("Tue, 14 Mar 2017 14:59:59 GMT")
Finally, the Date constructor allows us to specify the year, month, date, hours,
minutes, seconds, and milliseconds:
let piDay = new Date(2017, 3, 14)
Dates created with the constructor are in the local time. To create a Date in UTC,
use the Date.UTC method.
NOTE
An RFC 2822/RFC 1123 string is a human readable string that looks like:
"Tue, 14 Mar 2017 14:59:59 GMT"
NOTE
ISO 8601 in ES6 is specified like this:
YYYY-MM-DDTHH:mm:ss.sssZ
Date Properties
Date Properties
PROPERTY DESCRIPTION
Date.name Date
Date Methods
METHOD DESCRIPTION
d.UTC(year, month, [day, [hour, [minute, Return milliseconds since Unix epoch from
[second, [millisecond]]]]]) UTC time specified
d.now() Return milliseconds since Unix epoch
d.parse(str) Return milliseconds since Unix epoch for
ISO 8601 string
instruments.has("Ringo"); // false
for (let [name, inst] of instruments) {
console.log(`${name} - ${inst}`);
}
Map Properties
PROPERTY DESCRIPTION
Map.name Map
WeakMaps allow you to track objects until they are garbage collected. The keys don't
create references, so data may disappear from weakmap if the key happens to be
garbage collected (or if its containing object is collected).
The constructor has the same interface as Map, you can create an empty WeakMap
by provided no arguments, or you can pass in an iterable of key value pairs.
WeakMap Properties
PROPERTY DESCRIPTION
WeakMap.name WeakMap
digits.has(9); // true
Set Properties
PROPERTY DESCRIPTION
Set.name Set
WeakSet Properties
PROPERTY DESCRIPTION
WeakSet.name WeakSet
cal.month = 12
console.log(cal.month) // 12
cal.month = 0 // RangeError
Proxy Methods
PROPERTY DESCRIPTION
Proxy.revocable(target, Create a revocable proxy. When revoke is called, proxy throws
handler) TypeError
Reflection
The Reflect object allows you to inspect objects. Reflect is not a constructor, all
the methods are static.
Math Methods
METHOD DESCRIPTION
Reflect.apply(obj, this, args) Return result of obj(...args) with this value
Reflect.construct(obj, args) Return result of new obj(...args)
NOTE
Symbol is not a constructor, and a TypeError will be raised if you try to use it as
one.
Symbol Properties
PROPERTY DESCRIPTION
Symbol.hasInstance Used to define class behavior for instanceof. Define method as static
[Symbol.hasInstance](instance) ...
Symbol. Used to define class behavior for Array.concat. Set to true if items are
isConcatSpreadable spread (or flattened).
Symbol.iterator Used to define class behavior for for...of. Should follow iteration protocol.
Can be a generator
Symbol.match Used to define class behavior for responding as a regular expression in
String methods: startsWith, endsWith, includes
Symbol Methods
METHOD DESCRIPTION
Symbol.for(key) Return symbol in global registry for key, other create symbol and return
it.
Symbol.keyFor(symbol) Return string value for symbol in global registry, undefined if symbol
not in registry
Built-in Functions
METHOD DESCRIPTION
eval(str) Evaluate code found in str
isFinite(val) Return false if val is Infinity, -Infinity, or NaN, else true
isNaN(val) Return true if val is NaN, else False
parseFloat(str) Return float if str can be converted to a number, else NaN
parseInt(val, radix) Return integer if str can be converted to an integer, else NaN. It
ignores characters that are not numbers in radix
decodeURI(uri) Return the unencoded version of the string. Should be used on full
URI
decodeURIComponent(str) Return the unencoded version of the string. Should be used on parts of
URI
encodeURI(uri) Return the encoded version of the URI. Should be used on full URI
encodeURIComponent(uri) Return the encoded version of the URI. Should be used on parts of
URI
Unicode
Alternatively, we can use the Unicode code point to specify a Unicode character:
let xSq2 = 'x\u{b2}';
To convert a code point back to a string using the fromCodePoint static method:
String.fromCodePoint(178) // "²"
FUNCTIONS ARE EASY TO DEFINE, WE SIMPLY GIVE THEM A NAME, THE PARAMETERS THEY
Again, because ES6 provides the arguments object, we can also create a function
that accepts variable parameters like this:
function add_many() {
let result = 0;
for (const val of arguments) {
result += val;
}
return result;
}
Calling Functions
You can use ... to spread an array into arguments:
add_many(...[1, 42., 7])
The bind Method
Functions have a method, bind, that allows you to set this and any other
parameters. This essentially allows you to partial the function:
function mul(a, b) { return a * b }
console.log(triple(2)) // 6
The first parameter to bind is the value passed for this. The rest are the arguments
for the function. If you want a callback to use the parent's this, you can call bind on
the function passing in the parent's this. Alternatively, you can use an arrow
function.
Arrow functions
ES6 introduced anonymous arrow functions. There are a few differences with arrow
functions:
Implicit return
this is not rebound
Cannot be generators
The second feature makes them nice for callbacks and handlers, but not a good
choice for methods. We can write:
function add2(val) {
return val + 2
}
As:
let add2 = (val) => (val + 2)
The => is called a fat arrow. Since, this is a one line function, we can remove the
curly braces and take advantage of the implicit return.
Note that the parentheses can be removed if you only have a single parameter and
are inlining the function:
let vals = [1, 2, 3]
console.log(vals.map(v=>v*2))
If we want a multiline arrow function, then remove the function, and add =>:
function add(x, y) {
let res = x + y
return res
}
becomes:
let add = (x,y) => {
let res = x + y
return res
}
Tail Call
If you perform a recursive call in the last position of a function, that is called tail
call. ES6 will allow you to do this without growing the stack:
function fib(n){
if (n == 0) {
return 0;
}
return n + fib(n-1);
}
NOTE
Some implementations might not support this. This fails with Node 7.7 and
Chrome 56 with fib(100000).
Classes
ES6 INTRODUCED CLASS WHICH IS SYNTACTIC SUGAR AROUND CREATING OBJECTS WITH
functions. ES6 classes support prototype inheritance, calls to parent classes via
super, instance methods, and static methods:
class Bike {
constructor(wheelSize, gearRatio) {
this._size = wheelSize;
this.ratio = gearRatio;
}
gearInches() {
return this.ratio * this.size;
}
}
Note that when you create a new instance of a class, you need to use new:
let bike = new Bike(26, 34/13)
bike.gearInches()
NOTE
Classes in ES6 are not hoisted. This means that you can't use a class until after
you defined it. Functions, are hoisted, and you can use them anywhere in the
scope of the code that defines them.
Bike2.prototype.gearInches = function() {
return this.ratio * this.size
}
let b = new Bike2(27, 33/11);
console.log(b.gearInches());
NOTE
The method is added after the fact to the prototype, so the instances can share
the method. We could define the method in the function, but then every instance
would get its own copy.
shift(ringIdx, cogIdx) {
this.ratio = this.rings[ringIdx] /
this.cogs[cogIdx];
}
}
let tan = new Tandem(26, [42, 36], [24, 20, 15, 11])
tan.shift(1, 2)
console.log(tan.gearInches())
Static Methods
A static method is a method called directly on the class, not on the instance.
class Recumbent extends Bike {
static isFast() {
return true;
}
}
Recumbent.isFast(); // true
let bike = {
__proto__: protoObj,
['__proto__']: otherObj,
size, // same as `size: size`
ratio: gearRatio,
gearInches() {
return this.size * this.ratio;
}
// dynamic properties
[ 'prop_' + (() => "foo")() ]: "foo"
}
Operators
ASSIGNMENT
Built-in Operators
OPERATOR DESCRIPTION
= Assignment
+ Addition, , unary plus (coerce to number), concatenation (string)
++ Increment
- Subtraction, unary negation (coerce to number)
-- Decrement
* Multiplication
/ Division
% Remainder (modulus)
** Power
<< Left shift
>> Right shift
<<< Unsigned left shift
>>> Unsigned right shift
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
~ Bitwise NOT
&& Logical AND
|| Logical OR
! Logical NOT
, Comma operator, evaluates all operands and returns last
delete X Delete an object, property, index
typeof Return string indicating type of operand
void Create an expression without a return value
in Return boolean if property in object
instanceof Return boolean if object instance of type
new Create a new instance of a type
... Spread sequence into array or parameters
Conditionals
ES6 HAS AN IF STATEMENT WITH ZERO OR MORE ELSE IF STATEMENTS, AND AN OPTIONAL ELSE
function letter_grade(grade) {
if (grade > 90) {
return 'A';
}
else if (grade > 80) {
return 'B';
}
else if (grade > 70) {
return 'C';
}
else {
return 'D';
}
}
letter_grade(grade); // 'C'
ES6 supports the following tests: >, >=, <, <=, ==, !=, ===, and !==. For boolean
operators use &&, ||, and ! for and, or, and not respectively.
For == and !=, ES6 tries to compare numeric values of the operands if they have
differing types, hence:
'3' == 3 // true
If this bothers you (and it should), use the strict equality operators (=== and !==):
'3' === 3 // false
Short Circuiting
The and statement will short circuit if it evaluates to false:
0 && 1/0 // 0
Likewise, the or statement will short circuit when something evaluates to true:
1 || 1/0 // 1
Ternary Operator
ES6 has a ternary operator. Instead of writing:
let last
if (band == 'Beatles') {
last = 'Lennon'
}
else {
last = 'Jones'
}
We can write:
let last = (band == 'Beatles) ? 'Lennon' : 'Jones';
Switch
ES6 supports the switch statement:
function strings(inst) {
switch(inst) {
case 'guitar':
return 6;
case 'violin':
return 4;
default:
return 1;
}
}
strings('violin'); // 4
Looping
for ... in - Iterates over the properties of an object. This only walks through
properties that have [[Enumerable]] set to true.
for ... of - Iterates over the items of a collection. Any object which has the
[Symbol.iterator] property can be iterated with this method.
forEach is a method on the Array object. It takes a callback that is invoked for
every item of the array.
[Symbol.iterator]() {
return this; // something with next
}
next() {
[this.val1, this.val2] = [this.val2, this.val1 + this.val2];
return {done: false, value: this.val1};
}
}
The result of next should be an object that indicates whether looping is finished in
the done property, and returns the item of iteration in the value property.
And here we use it in a for .. of loop:
for (var val of new Fib()) {
console.log(val);
if (val > 5) {
break;
}
}
generators. They generate values on the fly as they are iterated over. Following a
yield statement, the state of the function is frozen.
let fibGen = {
[Symbol.iterator]: function*() {
let val1 = 1;
let val2 = 2;
while (true) {
yield val1;
[val1, val2] = [val2, val1 + val2];
}
}
}
Using a generator:
for (var val of fibGen) {
console.log(val);
if (val > 5) {
break;
}
}
Modules
A MODULE IS A JAVASCRIPT FILE. TO USE OBJECT IN OTHER FILES, WE NEED TO EXPORT THE
console.log(sum(takeN(fibGen(), 5)));
NOTE
As of now, support for this feature is limited (available behind flag in Chrome
60, Edge 38, Firefox 54 and up). To use imports in non-modern browsers or in
node, we need to use Babel to get support:
$ npm install --save-dev babel-cli babel-preset-env
Promises
PROMISES ARE OBJECTS THAT ALLOW FOR ASYNCHRONOUS PROGRAMMING. THEY ARE AN
alternative for callbacks. If you know that a value might be available in the future, a
promise can represent that.
There are three states for a promise:
On the promise object a then method will be called to move the state to either
fulfilled or rejected.
An async function that implements a promise allows us to chain a then and a
catch method:
asyncFunction()
.then(function (result) {
// handle result
// Fulfilled
})
.catch(function (error) {
// handle error
// Rejected
})
Promise Properties
PROPERTY DESCRIPTION
Promise.length Return 1, number of constructor arguments
Promise.name value: Promise
Promise.prototype Prototype for Promise
Promise Methods
METHOD DESCRIPTION
Promise.all(promises) Return Promise that returns when promises are fulfilled, or rejects if
any of them reject.
Promise.race(promises) Return Promise that returns when any of the promises reject or fulfill
Promise.reject(reason) Return Promise that rejects with reason
Promise.resolve(value) Return a Promise that fulfills with value. If value has a then method, it
will return it's final state
A REGULAR EXPRESSION ALLOWS YOU TO MATCH CHARACTERS IN STRINGS. YOU CAN CREATE
then using the literal syntax. Between the slashes place the regular expression. Flags
can be specified at the end:
let names = 'Paul, George, Ringo, and John'
let re = /(Ringo|Richard)/g;
If there is a match it returns an array. The 0 position is the matched portion, the
remaining items correspond to the captured groups. These are specified with
parentheses. You can just count the left parentheses (unless they are escaped) in
order. Index 1 will be the group of the first parenthesis, index 2 will be the second
left parenthesis group, etc.
You can also call the constructor:
let re2 = RegExp('Ringo|Richard', 'g')
RegExp Flags
FLAG DESCRIPTION
g Match globally, returning all matches, not just first
i Ignore case when matching
m Treat newlines as breaks for ^ and $, allowing multi line matching
y Sticky match, start looking from r.lastIndex property
u Unicode match
Character Classes
CHARACTER DESCRIPTION
\d Match one digit ([0-9])
\D Match one non-digit ([^0-9])
\w Match one word character ([0-9a-zA-z])
\W Match one non-word character ([^0-9a-zA-z])
\s Match one space character
\S Match one non-space character
\b Match word boundary
\B Match non-word boundary
\t, \r, \v, \f Match one tab, carriage return, vertical tab, or line feed respectively
\0 Match one null character
\cCHAR Match one control character. Where CHAR is character
\xHH Match one character with hex code HH
\uHHHH Match one UTF-16 character with hex code HHHH
\u{HHHH} Match one unicode character with hex code HHHH (use u flag)
Syntax Characters
CHARACTER DESCRIPTION
^ Match beginning of line (note different in character class)
$ Match end of line
a|b Match a or b
[abet] Character class match one of a, b, e, or t
[^abe] ^ negates matches in character class. One of not a, b, or e
\[ Escape. Capture literal [. The following need to be escaped ^ $ \ . * + ? ( ) [
] { } |
RegExp Properties
PROPERTY DESCRIPTION
RegExp.length value: 2
RegExp.name value: RegExp
RegExp.prototype value: /(?:)/
r.p.flags Return flags for regular expression
r.p.global Return boolean if global (g) flag is used
r.p.ignoreCase Return boolean if ignore case (i) flag is used
r.p.multiline Return boolean if multi line (m) flag is used
r.p.source Return string value for regular expression
r.p.sticky Return boolean if sticky (y) flag is used
r.p.unicode Return boolean if unicode (u) flag is used
r.sticky Return integer specifying where to start looking for next match
MATT HARRISON HAS BEEN USING PYTHON SINCE 2000. HE RUNS METASNAKE, A PYTHON
and Data Science consultancy and corporate training shop. In the past, he has worked
across the domains of search, build management and testing, business intelligence
and storage.
He has presented and taught tutorials at conferences such as Strata, SciPy,
SCALE, PyCON and OSCON as well as local user conferences. The structure and
content of this book is based off of first hand experience teaching Python to many
individuals.
He blogs at hairysun.com and occasionally tweets useful Python related
information at @__mharrison__.
Also Available
Interpreter Usage
Types
Sequences
Dictionaries
Functions
Indexing and Slicing
File Input and Output
Classes
Exceptions
Importing
Libraries
Testing
And more …
Reviews
Matt Harrison gets it, admits there are undeniable flaws and schisms in Python,
and guides you through it in short and to the point examples. I bought both
Kindle and paperback editions to always have at the ready for continuing to
learn to code in Python.
—S. Oakland
This book was a great intro to Python fundamentals, and was very easy to read.
I especially liked all the tips and suggestions scattered throughout to help the
reader program Pythonically :)
—W. Dennis
Functional Programming
Lambda Expressions
List Comprehensions
Generator Comprehensions
Iterators
Generators
Closures
Decorators
And more …
Reviews
Complete! All you must know about Python Decorators: theory, practice,
standard decorators.
All written in a clear and direct way and very affordable price.
Nice to read in Kindle.
—F. De Arruda (Brazil)
This is a very well written piece that delivers. No fluff and right to the point,
Matt describes how functions and methods are constructed, then describes the
value that decorators offer.
…
Highly recommended, even if you already know decorators, as this is a very
good example of how to explain this syntax illusion to others in a way they can
grasp.
—J Babbington
This book will clear up your confusions about functions even before you start to
read about decoration at all. In addition to getting straight about scope, you'll
finally get clarity about the difference between arguments and parameters,
positional parameters, named parameters, etc. The author concedes that this
introductory material is something that some readers will find “pedantic,” but
reports that many people find it helpful. He’s being too modest. The distinctions
he draws are essential to moving your programming skills beyond doing a
pretty good imitation to real fluency.
—R. Careago
Learning the Pandas Library
Learning the Pandas Library by Matt Harrison is designed to bring developers and
aspiring data scientists who are anxious to learn Pandas up to speed quickly. It starts
with the fundamentals of the data structures. Then, it covers the essential
functionality. It includes many examples, graphics, code samples, and plots from real
world examples.
Installation
Data Structures
Series CRUD
Series Indexing
Series Methods
Series Plotting
Series Examples
DataFrame Methods
DataFrame Statistics
Grouping, Pivoting, and Reshaping
Dealing with Missing Data
Joining DataFrames
DataFrame Examples
Reviews
I have finished reading Learning the Pandas Library and I liked it... very useful
and helpful tips even for people who use pandas regularly.
—Tom. Z
Ebook Formatting: KF8, Mobi & EPUB
Ebook Formatting: KF8, Mobi & EPUB by Matt Harrison is the complete book on
formatting for all Kindle and EPUB devices. A good deal of the eBooks found in
online stores today have problematic formatting. Ebook Formatting: KF8, Mobi &
EPUB is meant to be an aid in resolving those issues. Customers hate poorly
formatted books. Read through the reviews on Amazon and you'll find many
examples. This doesn't just happen to self-published books. Books coming out of big
Publishing Houses often suffer similar issues. In the rush to put out a book, one of
the most important aspects affecting readability is ignored.
This books covers all aspects of ebook formatting on the most popular devices
(Kindle, iPad, Android Tablets, Nook and Kobo):
Covers
Title Pages
Images
Centering stuff
Box model support
Text Styles
Headings
Page breaks
Tables
Blockquotes
First sentence styling
Non-ASCII characters
Footnotes
Sidebars
Media Queries
Embedded Fonts
Javascript
and more …
2 - http://hairysun.com/books/tread/
3 - http://hairysun.com/books/treadvol2/
One more thing