pppp

Must Watch!



MustWatch



Getting started

JavaScript files alone can't be run directly by the browser; it's necessary to embed them in an HTML document. If you have some JavaScript code you'd like to try, you can embed it in some placeholder content like this, and save the result as example.html: <!doctype html> <html> <head> <meta charset="utf-8"> <title>Test page</title> </head> <body> Inline script (option 1): <script> // YOUR CODE HERE </script> External script (option 2): <script src="your-code-file.js"></script> </body> </html>

Single line comment //

Everything after the // until the end of the line is excluded from execution. function elementAt( event ) { // Gets the element from Event coordinates return document.elementFromPoint(event.clientX, event.clientY); } // TODO: write more cool stuff!

Multi-line comment /**/

Everything between the opening /* and the closing */ is excluded from execution, even if the opening and closing are on different lines. /* Gets the element from Event coordinates. Use like: var clickedEl = someEl.addEventListener("click", elementAt, false); */ function elementAt( event ) { return document.elementFromPoint(event.clientX, event.clientY); } /* TODO: write more useful comments! */

Bad practices

Using HTML comments in JavaScript Bad practice HTML comments (optionally preceded by whitespace) will cause code (on the same line) to be ignored by the browser also, though this is considered bad practice. One-line comments with the HTML comment opening sequence (<!--):
Note: the JavaScript interpreter ignores the closing characters of HTML comments (-->) here.
<!-- A single-line comment. <!-- --> Identical to using `//` since <!-- --> the closing `-->` is ignored. This technique can be observed in legacy code to hide JavaScript from browsers that didn't support it: <script type="text/javascript" language="JavaScript"> <!-- /* Arbitrary JavaScript code. Old browsers would treat it as HTML code. */ // --> </script> An HTML closing comment can also be used in JavaScript (independent of an opening comment) at the beginning of a line (optionally preceded by whitespace) in which case it too causes the rest of the line to be ignored: --> Unreachable JS code These facts have also been exploited to allow a page to call itself first as HTML and secondly as JavaScript. For example: <!-- self.postMessage('reached JS "file"'); /* --> <!DOCTYPE html> <script> var w1 = new Worker('#1'); w1.onmessage = function (e) { console.log(e.data); // 'reached JS "file" }; </script> <!-- */ --> When run a HTML, all the multiline text between the <!-- and --> comments are ignored, so the JavaScript contained therein is ignored when run as HTML. As JavaScript, however, while the lines beginning with <!-- and --> are ignored, their effect is not to escape over multiple lines, so the lines following them (e.g., self.postMessage(...) will not be ignored when run as JavaScript, at least until they reach a JavaScript comment, marked by /* and */. Such JavaScript comments are used in the above example to ignore the remaining HTML text (until the --> which is also ignored as JavaScript).

Basic data types

Numbers

Numbers are 8 byte, floating-point. const i = 16; const j = 38.53; const z = i + j; console.log(z); // -> 54.53 try online 54.53

Strings

Strings are Unicode. let s = "my"; s = s + " message"; console.log(s); // -> my message try online my message

Arrays

Arrays can grow and shrink and elements can be of any type. const cars = ["Model 3", "Leaf", "Bolt"]; console.log("first car:", cars[0]); const mixedTypes = ["string"]; mixedTypes.push(5); console.log("array with mixed types:", mixedTypes); try online first car: Model 3 array with mixed types: [ 'string', 5 ]

Objects (dictionaries, hash tables)

Objects map keys to values. In other languages they are known as dictionaries or hash tables. Values can be of any type, including functions. const person = { firstName: "John", lastName: "Doe", log: () => console.log("hello from log()") }; console.log("firstName:", person.firstName); console.log("lastName:", person["lastName"]); person.log(); try online firstName: John lastName: Doe hello from log()

Functions

Functions are first-class meaning they can be assigned to variables and passed around. const logMe = function(s) { console.log(s); } const logMe2 = logMe; logMe2("hello"); try online hello

Dynamic typing

The same variable can be assigned values of different types. let v; console.log(v); v = 5; console.log(v); v = "str"; console.log(v); try online undefined 5 str

Built-in constants

Variables

Variables are what make up most of JavaScript. These variables make up things from numbers to objects, which are all over JavaScript to make one's life much easier.

Syntax

var {variable_name} [= {value}];

Remarks

'use strict'; Strict Mode makes JavaScript stricter to assure you the best habits. For example, assigning a variable: "use strict"; // or 'use strict'; var syntax101 = "var is used when assigning a variable."; uhOh = "This is an error!"; uhOh is supposed to be defined using var. Strict Mode, being on, shows an error (in the Console, it doesn't care). Use this to generate good habits on defining variables. You may use Nested Arrays and Objects some time. They are sometimes useful, and they're also fun to work with. Here is how they work:

Nested Arrays

var myArray = [ "The following is an array", ["I'm an array"] ]; console.log(myArray[1]); // (1) ["I'm an array"] console.log(myArray[1][0]); // "I'm an array" var myGraph = [ [0, 0], [5, 10], [3, 12] ]; // useful nested array console.log(myGraph[0]); // [0, 0] console.log(myGraph[1][1]); // 10

Nested Objects

var myObject = { firstObject: { myVariable: "This is the first object" } secondObject: { myVariable: "This is the second object" } } console.log(myObject.firstObject.myVariable); // This is the first object. console.log(myObject.secondObject); // myVariable: "This is the second object" var people = { john: { name: { first: "John", last: "Doe", full: "John Doe" }, knownFor: "placeholder names" }, bill: { name: { first: "Bill", last: "Gates", full: "Bill Gates" }, knownFor: "wealth" } } console.log(people.john.name.first); // John console.log(people.john.name.full); // John Doe console.log(people.bill.knownFor); // wealth console.log(people.bill.name.last); // Gates console.log(people.bill.name.full); // Bill Gates

Declarations and assignments

Syntax

var foo [= value [, foo2 [, foo3 … [, fooN]]]]; let bar [= value [, bar2 [, foo3 … [, barN]]]]; const baz = value [, baz2 = value2 [, … [, bazN = valueN]]];

Remarks

See also: Reserved Keywords Scope

Reserved keywords

Introduction

Certain words - so-called keywords - are treated specially in JavaScript. There's a plethora of different kinds of keywords, and they have changed in different versions of the language.

Data types in JavaScript

Strings

Syntax

string literal string literal' string literal with mismatching quotes' // no errors; quotes are different. string literal withescaped quotes" // no errors; quotes are escaped. template string ${expression} String(a b c) // returns string when called in non-constructor context new String(a b c) // the String object, not the string primitive

Escape sequences

Not everything that starts with a backslash is an escape sequence. Many characters are just not useful to escape sequences, and will simply cause a preceding backslash to be ignored. "\H\e\l\l\o" === "Hello" // true On the other hand, some characters like u and x will cause a syntax error when used improperly after a backslash. The following is not a valid string literal because it contains the Unicode escape sequence prefix \u followed by a character that is not a valid hexadecimal digit nor a curly brace: "C:\Windows\System32\updatehandlers.dll" // SyntaxError A backslash at the end of a line inside a string does not introduce an escape sequence, but indicates line continuation, i.e. "contin\ uation" === "continuation" // true

Similarity to other formats

While escape sequences in JavaScript bear resemblance to other languages and formats, like C++, Java, JSON, etc. there will often be critical differences in the details. When in doubt, be sure to test that your code behaves as expected, and consider checking the language specification.

Entering special characters in strings and regular expressions

Most printable characters can be included in string or regular expression literals just as they are, e.g. var str = "ポケモン"; // a valid string var regExp = /[Α-Ωα-ω]/; // matches any Greek letter without diacritics In order to add arbitrary characters to a string or regular expression, including non-printable ones, one has to use escape sequences. Escape sequences consist of a backslash (\) followed by one or more other characters. To write an escape sequence for a particular character, one typically (but not always) needs to know its hexadecimal character code. JavaScript provides a number of different ways to specify escape sequences, as documented in the examples in this topic. For instance, the following escape sequences all denote the same character: the line feed (Unix newline character), with character code U+000A. \n \x0a \u000a \u{a} new in ES6, only in strings \012 forbidden in string literals in strict mode and in template strings \cj only in regular expressions

Escape sequence types

Single character escape sequences

Some escape sequences consist of a backslash followed by a single character. For example, in alert("Hello\nWorld");, the escape sequence \n is used to introduce a newline in the string parameter, so that the words Hello and World are displayed in consecutive lines.
Escape sequence Character Unicode
\b(only in strings, not in regular expressions)backspaceU+0008
\thorizontal tabU+0009
\nline feedU+000A
\vvertical tabU+000B
\fform feedU+000C
\rcarriage returnU+000D
Additionally, the sequence \0, when not followed by a digit between 0 and 7, can be used to escape the null character (U+0000). The sequences \\, \' and \" are used to escape the character that follows the backslash. While similar to non-escape sequences, where the leading backslash is simply ignored (i.e.\? for ?), they are explicitly treated as single character escape sequences inside strings as per the specification.

Hexadecimal escape sequences

Characters with codes between 0 and 255 can be represented with an escape sequence where \x is followed by the 2-digit hexadecimal character code. For example, the non-breaking space character has code 160 or A0 in base 16, and so it can be written as \xa0. var str = "ONE\xa0LINE"; // ONE and LINE with a non-breaking space between them For hex digits above 9, the letters a to f are used, in lowercase or uppercase without distinction. var regExp1 = /[\x00-xff]/; // matches any character between U+0000 and U+00FF var regExp2 = /[\x00-xFF]/; // same as above

4-digit Unicode escape sequences

Characters with codes between 0 and 65535 (216 - 1) can be represented with an escape sequence where \u is followed by the 4-digit hexadecimal character code. For example, the Unicode standard defines the right arrow character (→) with the number 8594, or 2192 in hexadecimal format. So an escape sequence for it would be \u2192. This produces the string A → B: var str = "A \u2192 B"; For hex digits above 9, the letters a to f are used, in lowercase or uppercase without distinction. Hexadecimal codes shorter than 4 digits must be left-padded with zeros: \u007A for the small letter z.

Curly bracket Unicode escape sequences

ES6 extends Unicode support to the full code range from 0 to 0x10FFFF. In order to escape characters with code greater than 216 - 1, a new syntax for escape sequences was introduced: \u{???} Where the code in curly braces is hexadecimal representation of the code point value, e.g. alert("Look! \u{1f440}"); // Look! In the example above, the code 1f440 is the hexadecimal representation of the character code of the Unicode Character Eyes. Note that the code in curly braces may contain any number of hex digits, as long the value does not exceed 0x10FFFF. For hex digits above 9, the letters a to f are used, in lowercase or uppercase without distinction. Unicode escape sequences with curly braces only work inside strings, not inside regular expressions!

Octal escape sequences

Octal escape sequences are deprecated as of ES5, but they are still supported inside regular expressions and in non-strict mode also inside non-template strings. An octal escape sequence consists of one, two or three octal digits, with value between 0 and 3778 = 255. For example, the capital letter E has character code 69, or 105 in base 8. So it can be represented with the escape sequence \105: /\105scape/.test("Fun with Escape Sequences"); // true In strict mode, octal escape sequences are not allowed inside strings and will produce a syntax error. It is worth to note that \0, unlike \00 or \000, is not considered an octal escape sequence, and is thus still allowed inside strings (even template strings) in strict mode.

Control escape sequences

Some escape sequences are only recognized inside regular expression literals (not in strings). These can be used to escape characters with codes between 1 and 26 (U+0001–U+001A). They consist of a single letter A–Z (case makes no difference) preceded by \c. The alphabetic position of the letter after \c determines the character code. For example, in the regular expression `/\cG/` The letter G (the 7th letter in the alphabet) refers to the character U+0007, and thus `/\cG`/.test(String.fromCharCode(7)); // true

Template Literals

Template literals are a type of string literal that allows values to be interpolated, and optionally the interpolation and construction behaviour to be controlled using a tag function.

Syntax

message = Welcome, ${user.name}! pattern = new RegExp(String.rawWelcome, (\\w+)!); query = SQLINSERT INTO User (name) VALUES (${name}) Template Literals were first specified by ECMAScript 6 §12.2.9.

Arrays

Syntax

array = [value, value, ] array = new Array(value, value, ) array = Array.of(value, value, ) array = Array.from(arrayLike)

Remarks

Summary: Arrays in JavaScript are, quite simply, modified Object instances with an advanced prototype, capable of performing a variety of list-related tasks. They were added in ECMAScript 1st Edition, and other prototype methods arrived in ECMAScript 5.1 Edition. Warning: If a numeric parameter called n is specified in the new Array() constructor, then it will declare an array with n amount of elements, not declare an array with 1 element with the value of n! console.log(new Array(53)); // This array has 53 'undefined' elements! That being said, you should always use [] when declaring an array: console.log([53]); // Much better!

Objects

Syntax

object = { } object = new Object() object = Object.create(prototype[, propertiesObject]) object.key = value object[key] = value object[Symbol()] = value object = { key1: value1, key2: value2, key3': value3 } object = { conciseMethod() { … } } object = { [computed() + key]: value } Object.defineProperty(obj, propertyName, propertyDescriptor) property_desc = Object.getOwnPropertyDescriptor(obj, propertyName) Object.freeze(obj) Object.seal(obj)

Parameters

Property Description
valueThe value to assign to the property.
writableWhether the value of the property can be changed or not.
enumerableWhether the property will be enumerated infor inloops or not.
configurableWhether it will be possible to redefine the property descriptor or not.
getA function to be called that will return the value of the property.
setA function to be called when the property is assigned a value.
Objects are collections of key-value pairs, or properties. The keys can be Strings or Symbols, and values are either primitives (numbers, strings, symbols) or references to other objects. In JavaScript, a significant amount of values are objects (e.g.functions, arrays) or primitives that behave as immutable objects (numbers, strings, booleans). Their properties or their prototype's properties can be accessed using dot (obj.prop) or bracket (obj['prop']) notation. Notable exceptions are the special values undefined and null. Objects are held by reference in JavaScript, not by value. This means that when copied or passed as arguments to functions, the copy and the original are references to the same object, and a change to one's properties will change the same property of the other. This does not apply to primitives, which are immutable and passed by value.

Prototypes objects

Classes

Syntax

class Foo {} class Foo extends Bar {} class Foo { constructor() {} } class Foo { myMethod() {} } class Foo { get myProperty() {} } class Foo { set myProperty(newValue) {} } class Foo { static myStaticMethod() {} } class Foo { static get myStaticProperty() {} } const Foo = class Foo {}; const Foo = class {};

Remarks

class support was only added to JavaScript as part of the 2015 [tag:es6] standard. Javascript classes are syntactical sugar over JavaScript's already existing prototype-based inheritance. This new syntax does not introduce a new object-oriented inheritance model to JavaScript, just a simpler way to deal with objects and inheritance. A class declaration is essentially a shorthand for manually defining a constructor function and adding properties to the prototype of the constructor. An important difference is that functions can be called directly (without the new keyword), whereas a class called directly will throw an exception. class someClass { constructor () {} someMethod () {} } console.log(typeof someClass); console.log(someClass); console.log(someClass === someClass.prototype.constructor); console.log(someClass.prototype.someMethod); // Output: // function // function someClass() { "use strict"; } // true // function () { "use strict"; } If you are using an earlier version of JavaScript you will need a transpiler like [tag:babel] or [tag:google-closure-compiler] in order to compile the code into a version that the target platform will be able to understand.

Variable coercion / conversion

Remarks

Some languages require you to define ahead of time what kind of variable you're declaring. JavaScript doesn't do that; it will try to figure that out on its own. Sometimes this can create unexpected behavior. If we use the following HTML <span>0</span> And retrieve its content through JS, it will not convert it to a number, even though one might expect it to. If we use the following snippet, one might expect boilingPoint to be 100. However, JavaScript will convert moreHeat to a string and concatenate the two string; the result will be 0100. var el = document.getElementById('freezing-point'); var freezingPoint = el.textContent || el.innerText; var moreHeat = 100; var boilingPoint = freezingPoint + moreHeat; We can fix this by explicitly converting freezingPoint to a number. var el = document.getElementById('freezing-point'); var freezingPoint = Number(el.textContent || el.innerText); var boilingPoint = freezingPoint + moreHeat; In the first line, we convert "0" (the string) to 0 (the number) before storing it. After doing the addition, you get the expected result (100).

Map

Syntax

new Map([iterable]) map.set(key, value) map.get(key) map.size map.clear() map.delete(key) map.entries() map.keys() map.values() map.forEach(callback[, thisArg])

Parameters

Parameter Details
iterableAny iterable object (for example an array) containing[key, value]pairs.
keyThe key of an element.
valueThe value assigned to the key.
callbackCallback function called with three parameters: value, key, and the map.
thisArgValue which will be used asthiswhen executingcallback.

Remarks

In Maps NaN is considered to be the same as NaN, even though NaN !== NaN. For example: const map = new Map([[NaN, true]]); console.log(map.get(NaN)); // true

Set

Arithmetic Math

Remarks

The clz32 method is not supported in Internet Explorer or Safari

Bitwise operators

Bitwise operators

Unary Operators

Syntax

void expression; // Evaluates expression and discards return value +expression; // Attempt to convert expression to a number delete object.property; // Delete object's property delete object[property]; // Delete object's property typeof operand; // Returns type of operand ~expression; // Perform NOT operation on each bit of expression !expression; // Perform logical negation on expression -expression; // Negate expression after attempting conversion to number

Comparison operations

When using boolean coercion, the following values are considered falsy: false 0 "" (empty string) null undefined NaN (not a number, e.g.0/0) document.all1 (browser context) Everything else is considered truthy.

Conditions

Conditional expressions, involving keywords such as if and else, provide JavaScript programs with the ability to perform different actions depending on a Boolean condition: true or false. This section covers the use of JavaScript conditionals, Boolean logic, and ternary statements.

Remarks

Conditions can break normal program flow by executing code based on the value of an expression. In JavaScript, this means using if, else if and else statements and ternary operators.

Loops

Syntax

for (initialization; condition; final_expression) { } for (key in object) { } for (variable of iterable) { } while (condition) { } do { } while (condition) for each (variable in object) { } // ECMAScript for XML

Remarks

Loops in JavaScript typically help solve problems which involve repeating specific code x amount of times. Say you need to log a message 5 times. You could do this: console.log("a message"); console.log("a message"); console.log("a message"); console.log("a message"); console.log("a message"); But that's just time-consuming and kind of ridiculous. Plus, what if you needed to log over 300 messages? You should replace the code with a traditional for loop: for (var i = 0; i < 5; i++){ console.log("a message"); }

Functions

Functions in JavaScript provide organized, reusable code to perform a set of actions. Functions simplify the coding process, prevent redundant logic, and make code easier to follow. This topic describes the declaration and utilization of functions, arguments, parameters, return statements and scope in JavaScript.

Syntax

function example(x) { return x } var example = function (x) { return x } (function() { … })(); // Immediately Invoked Function Expression (IIFE) var instance = new Example(x); Methods fn.apply(valueForThis[, arrayOfArgs]) fn.bind(valueForThis[, arg1[, arg2, …]]) fn.call(valueForThis[, arg1[, arg2, …]]) ES2015+ (ES6+): const example = x => { return x }; // Arrow function explicit return const example = x => x; // Arrow function implicit return const example = (x, y, z) => { … } // Arrow function multiple arguments (() => { … })(); // IIFE using an arrow function

Remarks

For information on arrow functions, please view the Arrow Functions documentation.

Arrow functions

Date

Syntax

new Date(); new Date(value); new Date(dateAsString); new Date(year, month[, day[, hour[, minute[, second[, millisecond]]]]]);

Parameters

Parameter Details
valueThe number of milliseconds since 1 January 1970 00:00:00.000 UTC (Unix epoch)
dateAsStringA date formatted as a string (see examples for more information)
yearThe year value of the date. Note thatmonthmust also be provided, or the value will be interpreted as a number of milliseconds. Also note that values between0and99have special meaning. See the examples.
monthThe month, in the range0-11. Note that using values outside the specified range for this and the following parameters will not result in an error, but rather cause the resulting date to roll over to the next value. See the examples.
dayOptional: The date, in the range1-31.
hourOptional: The hour, in the range0-23.
minuteOptional: The minute, in the range0-59.
secondOptional: The second, in the range0-59.
millisecondOptional: The millisecond, in the range0-999.

Date comparison

Scope

Remarks

Scope is the context in which variables live and can be accessed by other code in the same scope. Because JavaScript can largely be used as a functional programming language, knowing the scope of variables and functions is important as it helps to prevent bugs and unexpected behavior at runtime.

AJAX

AJAX stands for Asynchronous JavaScript and XML. Although the name includes XML, JSON is more often used due to it's simpler formatting and lower redundancy. AJAX allows the user to communicate with external resources without reloading the web page. AJAX stands for Asynchronous JavaScript and XML. Nevertheless you can actually use other types of data and—in the case of [tag:XMLHttpRequest]—switch to the deprecated synchronous mode. AJAX allows web pages to send HTTP requests to the server and receive a response, without needing to reload the entire page.

Promises

Syntax

new Promise( /* executor function: */ function(resolve, reject) { }) promise.then(onFulfilled[, onRejected]) promise.catch(onRejected) Promise.resolve(resolution) Promise.reject(reason) Promise.all(iterable) Promise.race(iterable)

Remarks

Promises are part of the ECMAScript 2015 specification and browser support is limited, with 88% of browsers worldwide supporting it as of July 2017. In environments which do not support them, Promise can be polyfilled. Third-party libraries may also provide extended functionalities, such as automated promisification of callback functions or additional methods like progress—also known as notify. The Promises/A+ standard website provides a list of 1.0 and 1.1 compliant implementations. Promise callbacks based on the A+ standard are always executed asynchronously as microtasks in the event loop.

Regular Expression

Syntax

let regex = /pattern/[flags] let regex = new RegExp('pattern', [flags]) let ismatch = regex.test('text') let results = regex.exec('text')

Parameters

Flags Details
gglobal. All matches (don't return on the first match).
mmulti-line. Causes^&$to match the begin/end of each line (not only begin/end of string).
iinsensitive. Case insensitive match (ignores case of [a-zA-Z]).
uunicode : Pattern strings are treated asUTF-16. Also causes escape sequences to match Unicode characters.
ysticky: matches only from the index indicated by the lastIndex property of this regular expression in the target string (and does not attempt to match from any later indexes).
The RegExp object is only as useful as your knowledge of Regular Expressions is strong. See here for an introductory primer, or see MDN for a more in-depth explanation.

Error Handling

Syntax

try { … } catch (error) { … } try { … } finally { … } try { … } catch (error) { … } finally { … } throw new Error([message]); throw Error([message]);

Remarks

try allows you to define a block of code to be tested for errors while it is being executed. catch allows you to define a block of code to be executed, if an error occurs in the try block. finally lets you execute code regardless of the result. Beware though, the control flow statements of try and catch blocks will be suspended until the execution of the finally block finishes.

Geolocation

Syntax

navigator.geolocation.getCurrentPosition(successFunc, failureFunc) navigator.geolocation.watchPosition(updateFunc, failureFunc) navigator.geolocation.clearWatch(watchId)

Remarks

The Geolocation API does what you might expect: retrieve information about the client's whereabouts, represented in latitude and longitude. However, it is up to the user to agree to give away their location. This API is defined in the W3C Geolocation API Specification. Features for obtaining civic addresses and to enable geofencing / triggering of events have been explored, but are not widely implemented. To check if the browser supports the Geolocation API: if(navigator.geolocation){ // Horray! Support! } else { // No support... }

Cookies

Adding and Setting Cookies

The following variables set up the below example: var COOKIE_NAME = "Example Cookie"; /* The cookie's name. */ var COOKIE_VALUE = "Hello, world!"; /* The cookie's value. */ var COOKIE_PATH = "/foo/bar"; /* The cookie's path. */ var COOKIE_EXPIRES; /* The cookie's expiration date (config'd below). */ /* Set the cookie expiration to 1 minute in future (60000ms = 1 minute). */ COOKIE_EXPIRES = (new Date(Date.now() + 60000)).toUTCString(); document.cookie += COOKIE_NAME + "=" + COOKIE_VALUE + "; expires=" + COOKIE_EXPIRES + "; path=" + COOKIE_PATH;

Reading cookies

var name = name + "=", cookie_array = document.cookie.split(';'), cookie_value; for (var i=0;i<cookie_array.length;i++) { var cookie=cookie_array[i]; while(cookie.charAt(0)==' ') cookie = cookie.substring(1,cookie.length); if(cookie.indexOf(name)==0) cookie_value = cookie.substring(name.length,cookie.length); } This will set cookie_value to the value of the cookie, if it exists. If the cookie is not set, it will set cookie_value to null

Removing cookies

var expiry = new Date(); expiry.setTime(expiry.getTime() - 3600); document.cookie = name + "=; expires=" + expiry.toGMTString() + "; path=/" This will remove the cookie with a given name.

Test if cookies are enabled

If you want to make sure cookies are enabled before using them, you can use navigator.cookieEnabled: if (navigator.cookieEnabled === false) { alert("Error: cookies not enabled!"); } Note that on older browsers navigator.cookieEnabled may not exist and be undefined. In those cases you won't detect that cookies are not enabled.

Intervals and timeouts

Syntax

timeoutID = setTimeout(function() {}, milliseconds) intervalID = setInterval(function() {}, milliseconds) timeoutID = setTimeout(function() {}, milliseconds, parameter, parameter, …) intervalID = setInterval(function() {}, milliseconds, parameter, parameter, …) clearTimeout(timeoutID) clearInterval(intervalID)

Remarks

If the delay is not specified, it defaults to 0 milliseconds. However, the actual delay will be longer than that; for example, the HTML5 spec specifies a minimum delay of 4 milliseconds. Even when setTimeout is called with a delay of zero, the function that is called by setTimeout will be executed asynchronously. Note that many operations like DOM manipulation are not necessarily completed even if you've made the operation and moved on to the next code sentence, so you shouldn't assume they will run synchronously. Using setTimeout(someFunc, 0) enqueues the execution of the someFunc function at the end of the current JavaScript engine's call stack, so the function will be called after those operations completed. It is possible to pass a string containing JavaScript code (setTimeout("some..code", 1000)) in place of the function (setTimeout(function(){some..code}, 1000)). If the code is placed in a string, it will be later parsed using eval(). String-style timeouts are not recommended for performance, clarity and sometimes security reasons, but you may see older code which uses this style. Passing functions has been supported since Netscape Navigator 4.0 and Internet Explorer 5.0.

Generators

Introduction

Generator functions (defined by the function* keyword) run as coroutines, generating a series of values as they're requested through an iterator.

Syntax

function* name(parameters) { yield value; return value } generator = name(arguments) { value, done } = generator.next(value) { value, done } = generator.return(value) generator.throw(error)

Remarks

Generator functions are a feature introduced as part of the ES 2015 specification and are not available in all browsers. They are also fully supported in Node.js as of v6.0. For a detailed browser compatibility list, see the MDN Documentation, and for Node, see the node.green website.

History of visited urls

The browser remembers all visited urls in a browsing session. A user can use back / forward buttons to manually navigate to urls from the history. The history can be accessed programmatically via window.history. For security reasons we can't read what urls are in the history. We don't want a website to see what pages the user visited before.

history.back, history.forward, history.go, history.length

You can navigate the history with window.history.back() and window.history.forward(). Use history.length to get number of entries in history. To navigate to a given entry use history.go(n). history.go(-1) is an equivalent of history.back() and history.go(1) is the same as history.forward().

history.pushState, history.replaceState

You can add new entries to history with history.pushState(state_object, title, url), for example: window.history.pushState("arbitrary object", "a title", "/example/path.html"); history.replaceState(state_object, title, url) is like pushState except it replaces current state instead of adding a new one, e.g.: var stateObj = { foo: "bar" }; window.history.pushState(stateObj, "a page bar", "/foo/bar.html"); State object can be any serializable JavaScript value. Manually adding to history is useful when implementing custom UI interactions. For example an implementation of infinite scroll might add checkpoints to navigation history so that back button navigates to a meaningful place in the page.

window.onpopstate

Navigation (either manual with back / forward button or programmatically via back(), forward(), go() triggers onpopstate event: window.onpopstate = (event) => console.log("event:", event) Event is of PopStateEvent type with the following properties: state : the same as first argument passed to pushState and replaceState type : "popstate"

Strict mode

Syntax

use strict'; use strict; use strict;

Remarks

Strict mode is an option added in ECMAScript 5 to enable a few backwards-incompatible enhancements. Behaviour changes in strict mode code include: Assigning to undefined variables raises an error instead of defining new global variables; Assigning to or deleting non-writable properties (such as window.undefined) raises an error instead of executing silently; Legacy octal syntax (ex. 0777) is unsupported; The with statement is unsupported; eval cannot create variables in the surrounding scope; Functions' .caller and .arguments properties are unsupported; A function's parameter list cannot have duplicates; window is no longer automatically used as the value of this. NOTE:- strict' mode is NOT enabled by default as if a page uses JavaScript which depends on features of non - strict mode, then that code will break. Thus, it has to be turned on by the programmer himself / herself.

Custom Elements

Syntax

.prototype.createdCallback() .prototype.attachedCallback() .prototype.detachedCallback() .prototype.attributeChangedCallback(name, oldValue, newValue) document.registerElement(name, [options])

Parameters

Parameter Details
nameThe name of the new custom element.
options.extendsThe name of the native element being extended, if any.
options.prototypeThe custom prototype to use for the custom element, if any.

Remarks

Note that the Custom Elements specification has not yet been standardized, and is subject to change. The documentation describes the version that's been shipped in Chrome stable at this time.
Custom Elements is an HTML5 feature allowing developers to use JavaScript to define custom HTML tags that can be used in their pages, with associated styles and behaviours. They are often used with [tag:shadow-dom].

JSON

Introduction

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and easy for machines to parse and generate. It is important to realize that, in JavaScript, JSON is a string and not an object. A basic overview can be found on the json.org website which also contains links to implementations of the standard in many different programming languages.

Syntax

JSON.parse(input[, reviver]) JSON.stringify(value[, replacer[, space]])

Parameter

Parameter Details
JSON.parseParse a JSON string
input(string)JSON string to be parsed.
reviver(function)Prescribes a transformation for the input JSON string.
JSON.stringifySerialize a serializable value
value(string)Value to be serialized according to the JSON specification.
replacer(functionorString[]orNumber[])Selectively includes certain properties of thevalueobject.
space(StringorNumber)If anumberis provided, thenspacenumber of whitespaces will be inserted of readability. If astringis provided, the string (first 10 characters) will be used as whitespaces.

Remarks

The JSON utility methods were first standardized in ECMAScript 5.1 §15.12. The format was formally defined in The application/json Media Type for JSON (RFC 4627 July 2006) which was later updated in The JSON Data Interchange Format (RFC 7158 March 2013, ECMA-404 October 2013 and RFC 7159 March 2014). To make these methods available in old browsers such as Internet Explorer 8, use Douglas Crockford's json2.js.

Binary Data

Remarks

Typed Arrays were originally specified by a Khronos editor's draft, and later standardized in ECMAScript 6 §24 and §22.2. Blobs are specified by the W3C File API working draft.

Web Storage

Syntax

localStorage.setItem(name, value); localStorage.getItem(name); localStorage.name = value; localStorage.name; localStorage.clear() localStorage.removeItem(name);

Parameters

Parameter Description
nameThe key/name of the item
valueThe value of the item

Remarks

The Web Storage API is specified in the WHATWG HTML Living Standard.

Fetch

Syntax

promise = fetch(url).then(function(response) {}) promise = fetch(url, options) promise = fetch(request)

Parameters

Options Details
methodThe HTTP method to use for the request. ex:GET,POST,PUT,DELETE,HEAD. Defaults toGET.
headersAHeadersobject containing additional HTTP headers to include in the request.
bodyThe request payload, can be astringor aFormDataobject. Defaults toundefined
cacheThe caching mode.default,reload,no-cache
referrerThe referrer of the request.
modecors,no-cors,same-origin. Defaults tono-cors.
credentialsomit,same-origin,include. Defaults toomit.
redirectfollow,error,manual. Defaults tofollow.
integrityAssociated integrity metadata. Defaults to empty string.

Remarks

The Fetch standard defines requests, responses, and the process that binds them: fetching. Among other interfaces, the standard defines Request and Response Objects, designed to be used for all operations involving network requests. A useful application of these interfaces is GlobalFetch, which can be used to load remote resources. For browsers that do not yet support the Fetch standard, GitHub has a polyfill available. In addition, there is also a Node.js implementation that is useful for server/client consistency. In the absence of cancelable Promises you can't abort the fetch request (github issue). But there is a proposal by the T39 in stage 1 for cancelable promises.

Modules

Syntax

import defaultMember from module'; import { memberA, memberB, … } from module'; import * as module from module'; import { memberA as a, memberB, … } from module'; import defaultMember, * as module from module'; import defaultMember, { moduleA, … } from module'; import module';

Remarks

From MDN (emphasis added):
This feature is not implemented in any browsers natively at this time. It is implemented in many transpilers, such as the Traceur Compiler, Babel or Rollup.
Many transpilers are able to convert ES6 module syntax into CommonJS for use in the Node ecosystem, or RequireJS or System.js for use in the browser. It is also possible to use a module bundler like Browserify to combine a set of inter-dependent CommonJS modules into a single file which can be loaded in the browser.

Screen

Inheritance

Timestamps

Syntax

millisecondsAndMicrosecondsSincePageLoad = performance.now(); millisecondsSinceYear1970 = Date.now(); millisecondsSinceYear1970 = (new Date()).getTime();

Remarks

performance.now() is available in modern web browsers and provides reliable timestamps with sub-millisecond resolution. Since Date.now() and (new Date()).getTime() are based on the system time, they often get skewed by a few milliseconds when the system time is automatically synchronized.

Destructuring assignment

Introduction

Destructuring is a pattern matching technique that is added to Javascript recently in EcmaScript 6. It allows you to bind a group of variables to a corresponding set of values when their pattern matches to the right hand-side and the left hand-side of the expression.

Syntax

let [x, y] = [1, 2] let [first, …rest] = [1, 2, 3, 4] let [one, , three] = [1, 2, 3] let [val=default value'] = [] let {a, b} = {a: x, b: y} let {a: {c}} = {a: {c: nested'}, b: y} let {b=default value'} = {a: 0}

Remarks

Destructuring is new in the ECMAScript 6 (A.K.A ES2015) specification and browser support may be limited. The following table gives an overview of the earliest version of browsers that supported >75% of the specification.

Web Worker

Syntax

new Worker(file) postMessage(data, transfers) onmessage = function(message) { /* … */ } onerror = function(message) { /* … */ } terminate()

Remarks

Service workers are only enabled for websites served over HTTPS.

Debugging

Notifications API

Syntax

Notification.requestPermission(callback) Notification.requestPermission().then(callback, rejectFunc) new Notification(title, options) notification.close()

Remarks

The Notifications API was designed to allow browser access to notifying the client. Support by browsers might be limited. Also support by the operating system may be limited. The following table gives an overview of the earliest browser versions that provide support for notifications.

WebSockets

Introduction

WebSocket is protocol, which enables two-way communication between a client and server: The goal WebSocket is to provide a mechanism for browser-based applications that need two-way communication with servers that does not rely on opening multiple HTTP connections. (RFC 6455) WebSocket works over HTTP protocol.

Syntax

new WebSocket(url) ws.binaryType /* delivery type of received message: arraybuffer or blob */ ws.close() ws.send(data) ws.onmessage = function(message) { /* … */ } ws.onopen = function() { /* … */ } ws.onerror = function() { /* … */ } ws.onclose = function() { /* … */ }

Parameters

Parameter Details
urlThe server url supporting this web socket connection.
dataThe content to send to the host.
messageThe message received from the host.

Web Cryptography API

Remarks

The WebCrypto APIs are usually only available on secure origins, meaning that the document must have been loaded over HTTPS or from the local machine (from localhost, file:, or a browser extension). These APIs are specified by the W3C Web Cryptography API Candidate Recommendation.

Async functions, async / await

Introduction

async and await build on top of promises and generators to express asynchronous actions inline. This makes asynchronous or callback code much easier to maintain. Functions with the async keyword return a Promise, and can be called with that syntax. Inside an async function the await keyword can be applied to any Promise, and will cause all of the function body after the await to be executed after the promise resolves.

Remarks

Async functions are a syntactic sugar over promises and generators. They help you make your code more readable, maintainable, easier to catch errors in, and with fewer levels of indentation.

Constructor functions

Remarks

Constructor functions are actually just regular functions, there's nothing special about them. It's only the new keyword which causes the special behavior shown in the examples above. Constructor functions can still be called like a regular function if desired, in which case you would need to bind the this value explicitly.

execCommand and contenteditable

Syntax

bool supported = document.execCommand(commandName, showDefaultUI, valueArgument)

Parameters

commandId value
Inline formatting commands
backColorColor value String
bold
createLinkURL String
fontNameFont family name
fontSize1, 2, 3, 4, 5, 6, 7
foreColorColor value String
strikeThrough
superscript
unlink
Block formatting commands
delete
formatBlockaddress, dd, div, dt, h1, h2, h3, h4, h5, h6, p, pre
forwardDelete
insertHorizontalRule
insertHTMLHTML String
insertImageURL String
insertLineBreak
insertOrderedList
insertParagraph
insertTextText string
insertUnorderedList
justifyCenter
justifyFull
justifyLeft
justifyRight
outdent
Clipboard commands
copyCurrently Selected String
cutCurrently Selected String
paste
Miscellaneous commands
defaultParagraphSeparator
redo
selectAll
styleWithCSS
undo
useCSS

Performance Tips

Introduction

JavaScript, like any language, requires us to be judicious in the use of certain language features. Overuse of some features can decrease performance, while some techniques can be used to increase performance.

Remarks

Remember that premature optimization is the root of all evil. Write clear, correct code first, then if you have performance problems, use a profiler to look for specific areas to improve. Don't waste time optimizing code that's not affecting the overall performance in a meaningful way. Measure, measure, measure. Performance can often be counter intuitive, and changes over time. What's faster now might not be in the future, and can depend on your use case. Make sure any optimizations you make are actually improving, not hurting performance, and that the change is worthwhile.

Design patterns

requestAnimationFrame

Syntax

window.requestAnimationFrame(callback); window.webkitRequestAnimationFrame(callback); window.mozRequestAnimationFrame(callback);

Parameters

callback : A parameter specifying a function to call when it's time to update your animation for the next repaint. (https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)

Remarks

When it comes to animating DOM elements fluidly, we are limited to the following CSS transitions: POSITION - transform: translate (npx, npx); SCALE - transform: scale(n); ROTATION - transform: rotate(ndeg); OPACITY - opacity: 0; However, using these is no guarantee that your animations will be fluid, because it causes the browser to start new paint cycles, regardless of what else is going on. Basically, paint are made inefficiently and your animation looks janky because the frames per second (FPS) suffers. To guarantee smooth-as-possible DOM animations, requestAnimationFrame must be used in conjunction with the above CSS transitions. The reason this works, is because the requestAnimationFrame API lets the browser know that you want an animation to happen at the next paint cycle, as opposed to interrupting what's going on to force a new paint cycle in when a non-RAF animation is called.
References URL
What is jank?http://jankfree.org/
High Performance Animationshttp://www.html5rocks.com/en/tutorials/speed/high-performance-animations/.
R.A.I.L.https://developers.google.com/web/tools/chrome-devtools/profile/evaluate-performance/rail?hl=en
Analyzing Critical Rendering Pathhttps://developers.google.com/web/fundamentals/performance/critical-rendering-path/analyzing-crp?hl=en
Rendering Performancehttps://developers.google.com/web/fundamentals/performance/rendering/?hl=en
Analyzing Paint Timeshttps://developers.google.com/web/updates/2013/02/Profiling-Long-Paint-Times-with-DevTools-Continuous-Painting-Mode?hl=en
Identifying Paint Bottleneckshttps://developers.google.com/web/fundamentals/performance/rendering/simplify-paint-complexity-and-reduce-paint-areas?hl=en

Method chaining

Global error handling in browsers

File API, blobs and FileReaders

Syntax

reader = new FileReader();

Parameters

Property/Method Description
errorA error that occurred while reading the file.
readyStateContains the current state of the FileReader.
resultContains the file contents.
onabortTriggered when the operation is aborted.
onerrorTriggered when an error is encountered.
onloadTriggered when the file has loaded.
onloadstartTriggered when the file loading operation has started.
onloadendTriggered when the file loading operation has ended.
onprogressTriggered whilst reading a Blob.
abort()Aborts the current operation.
readAsArrayBuffer(blob)Starts reading the file as an ArrayBuffer.
readAsDataURL(blob)Starts reading the file as a data url/uri.
readAsText(blob[, encoding])Starts reading the file as a text file. Not able to read binary files. Use readAsArrayBuffer instead.

Remarks

https://www.w3.org/TR/FileAPI/

Console

Introduction

A browser's debugging console or web console is generally used by developers to identify errors, understand flow of execution, log data and for many other purpose at runtime. This information is accessed through the object.

Syntax

void console.log(obj1 [, obj2, …, objN]); void console.log(msg [, sub1, …, subN]);

Parameters

Parameter Description
obj1 … objNA list of JavaScript objects whose string representations are outputted in the console
msgA JavaScript string containing zero or more substitution strings.
sub1 … subNJavaScript objects with which to replace substitution strings within msg.

Remarks

The information displayed by a Javascript object that can be consulted through console.dir(console). Besides the console.memory property, the methods displayed are generally the following (taken from Chromium's output): assert clear count debug dir dirxml error group groupCollapsed groupEnd info log markTimeline profile profileEnd table time timeEnd timeStamp timeline timelineEnd trace warn

Opening the Console

In most current browsers, the JavaScript Console has been integrated as a tab within Developer Tools. The shortcut keys listed below will open Developer Tools, it might be necessary to switch to the right tab after that.

Chrome

Opening the Console panel of Chrome's DevTools: Windows / Linux: any of the following options: Ctrl + Shift + J Ctrl + Shift + I, then click on the Web Console tab or press ESC to toggle the console on and off F12, then click on the Console tab or press ESC to toggle the console on and off Mac OS: Cmd + Opt + J

Firefox

Opening the Console panel in Firefox's Developer Tools: Windows / Linux: any of the following options Ctrl + Shift + K Ctrl + Shift + I, then click on the Web Console tab or press ESC to toggle the console on and off F12, then click on the Web Console tab or press ESC to toggle the console on and off Mac OS: Cmd + Opt + K

Edge and Internet Explorer

Opening the Console panel in the F12 Developer Tools: F12, then click on the Console tab

Safari

Opening the Console panel in Safari's Web Inspector you must first enable the develop menu in Safari's Preferences Then you can either pick Develop->Show Error Console from the menus or press + Option + C

Opera

Opening the Console in opera: Ctrl + Shift + I,then click on the Console tab

Compatibility

When using or emulating Internet Explorer 8 or earlier versions (e.g.through Compatibility View / Enterprise Mode) the console will only be defined when the Developer Tools are active, so console.log() statements can cause an exception and prevent code from executing. To mitigate this, you can check to see if the console is available before you log: if (typeof window.console !== 'undefined') { console.log("Hello World"); } Or at the start of your script you can identify if the console is available and if not, define a null function to catch all of your references and prevent exceptions. if (!window.console) { console = {log: function() {}}; } Note this second example will stop all console logs even if the developer window has been opened. Using this second example will preclude use of other functions such as console.dir(obj) unless that is specifically added.

Tail call optimization

Syntax

only return call() either implicitly such as in arrow function or explicitly, can be a tail call statment function foo(){ return bar(); } // the call to bar is a tail call function foo(){ bar(); }// bar is not a tail call. The function returns undefined when no return is given const foo = () => bar(); // bar() is a tail call const foo = () => (poo(),bar()); // poo is not a tail call, bar is a tail call const foo = () => poo() && bar(); // poo is not a tail call, bar is a tail call const foo = () => bar() + 1; // bar is not a tail call as it requires context to return + 1

Remarks

TCO is also known as PTC (Proper Tail Call) as it is referred to in the ES2015 specifications.

Detecting browser

Introduction

Browsers, as they have evolved, offered more features to Javascript. But often these features are not available in all browsers. Sometimes they may be available in one browser, but yet to be released on other browsers. Other times, these features are implemented differently by different browsers. Browser detection becomes important to ensure that the application you develop runs smoothly across different browsers and devices.

Remarks

Use feature detection when possible. There are some reasons to use browser detection (e.g.Giving a user directions on how to install a browser plugin or clear their cache), but generally feature detection is considered best practice. If you are using browser detection be sure that it is absolutely nesesary. Modernizr is a popular, lightweight JavaScript library that makes feature detection easy.

Enumerations

Remarks

In computer programming, an enumerated type (also called enumeration or enum [..]) is a data type consisting of a set of named values called elements, members or enumerators of the type. The enumerator names are usually identifiers that behave as constants in the language. A variable that has been declared as having an enumerated type can be assigned any of the enumerators as a value.
Wikipedia: Enumerated type JavaScript is weakly typed, variables are not declared with a type beforehand and it does not have a native enum data type. Examples provided here may include different ways to simulate enumerators, alternatives and possible trade-offs.

Symbols

Syntax

Symbol() Symbol(description) Symbol.toString()

Remarks

ECMAScript 2015 Specification 19.4 Symbols

Localization

Syntax

new Intl.NumberFormat() new Intl.NumberFormat(en-US') new Intl.NumberFormat(en-GB',{timeZone: UTC'})

Parameters

Paramater Details
weekday narrow, short, long
era narrow, short, long
year numeric, 2-digit
month numeric, 2-digit, narrow, short, long
day numeric, 2-digit
hour numeric, 2-digit
minute numeric, 2-digit
second numeric, 2-digit
timeZoneName short, long

Selection API

Syntax

Selection sel = window.getSelection(); Selection sel = document.getSelection(); // equivalent to the above Range range = document.createRange(); range.setStart(startNode, startOffset); range.setEnd(endNode, endOffset);

Parameters

Parameter Details
startOffsetIf the node is a Text node, it is the number of characters from the beginning ofstartNodeto where the range begins. Otherwise, it is the number of child nodes between the beginning ofstartNodeto where the range begins.
endOffsetIf the node is a Text node, it is the number of characters from the beginning ofstartNodeto where the range ends. Otherwise, it is the number of child nodes between the beginning ofstartNodeto where the range ends.

Remarks

The Selection API allows you to view and change the elements and text that are selected (highlighted) in the document. It is implemented as a singleton Selection instance that applies to the document, and holds a collection of Range objects, each representing one contiguous selected area. Practically speaking, no browser except Mozilla Firefox supports multiple ranges in selections, and this is not encouraged by the spec either. Additionally, most users are not familiar with the concept of multiple ranges. As such, a developer can usually only concern themselves with one range.

Callbacks

Functional JavaScript

Remarks

What is Functional Programming ? Functional Programming or FP is a programming paradigm that is built upon two main concepts immutability, and statelessness.The goal behind FP is to make your code more readable, reusable, and portable. What is Functional JavaScript There has been a debate to call JavaScript a functional language or not.However we can absolutely use JavaScript as a functional due to its nature: Has Pure Functions Has Has It supports Has Closures , and List Transforation Methods(Arrays) like map,reduce,filter..etc The Examples should cover each concept in details, and the links provided here are just for reference, and should be removed once the concept is illustrated.

Modals

Syntax

alert( message ) confirm( message ) prompt( message [, optionalValue]) print()

Remarks

https://www.w3.org/TR/html5/webappapis.html#user-prompts https://dev.w3.org/html5/spec-preview/user-prompts.html

Data attributes

Syntax

var x = HTMLElement.dataset.*; HTMLElement.dataset.* = value;

Remarks

MDN Documentation: Using data attributes.

Event Loop

Events

Data manipulation

BOM Browser Object Model

Unit Testing

Linters for ensuring code quality

Automatic Semicolon Insertion

IndexedDB

Anti-patterns

Navigator Object

Modularization techniques

Proxy

Same origin policy, cross-origin communication

postMessage and MessageEvent

WeakMap

WeakSet

Behaviroal Design Patterns

Server-sent events

Async iterators

Namespacing

Evaluating JavaScript

Memory efficiency

How to make iterator usable inside async callback function

Context this

Setters and getters

Vibration API

Modern mobile devices can vibrate. The Vibration API allows Web apps the trigger vibration of the device (if its supported by the hardware). Support by browsers and operating systems might be limited.

Single vibration

Vibrate the device for 100 ms: const didVibrate = window.navigator.vibrate(100); or const didVibrate = window.navigator.vibrate([100]);

Check if vibration is supported

Check if browser supports vibrations if ('vibrate' in window.navigator) { // browser has support for vibrations } else { // no support }

Vibration patterns

An array of values describes periods of time in which the device is vibrating and not vibrating. window.navigator.vibrate([200, 100, 200]);