JavaScript

01 Jan 2020

A simple summary of JavaScript

Data Types
Svar s = "string";String
Nvar n = 4.0;Number
Bvar b = True;Boolean
N[] var a = [1,2,3,4];Array of numbers
Svar a = ["a","b","c"];Array of strings
*var g = /()/;Regular Expression syntax
Nconst n = 4.0;Constant Number, runtime immutable
Nlet n = 4.0;Block scope number definition, ie. inside functions
Using data types
Assignment
var s = "string";Stores the value into the variable
Comparison
a == bEquals
a === bStrictly Equals
a != bNot equal
!(a == b)Logical not of a == b
a !== bStrictly not equal
a < bLess than
a <= bLess than, or equal
a > bGreater than
a >= bGreater than
Arithmetic
a += bAdds a and b, then assigns value to a
a -= bSubtracts b from a, then assigns value to a
a /= bDivides a by b, then assigns value to a
a *= bMultiplies a and b, then assigns value to a
Logic
a && bLogical a AND b
a || bLogical a or b
Bitwise Operators
a & bAND
a | bOR
a ^ bXOR
~ bNOT (complement)
a << bShift a left b bits (Increase)
a >> bShift a right b bits (Decrease)
a >>> bShift a right b bits (Decrease), filling with zeroes
Other
typeof aReturns the type of variable 'a' (number, string, object, function)
var a;undefined, meaning has not been assigned a value
var a = null;null, has been assigned a non value
N Number()
ReturnProperties
N.POSITIVE_INFINITY+inf equivalent
N.NEGATIVE_INFINITY-inf equivalent
N.MAX_VALUElargest positive value
N.MIN_VALUEsmallest positive value
N.EPSILONdifference between 1 and smallest > 1
.NaNnot a number value
ReturnMethods
S.toExponential(dec)exponential notation
S.toFixed(dec)fixed-point notation
S.toPrecision(dec)change precision
B.isFinite(n)checks if number is finite
B.isInteger(n)checks if number is an integer
N.parseInt(n)string to integer conversion
N.parseFloat(n)string to float conversion
S Strings
ReturnProperties
N.lengthlength of string
ReturnAccessor
S[2]Array accessor, returns character at index offset 2 (Unsafe if length of string < 2)
ReturnMethods
S.charAt(2)Returns character at index offset 2
s.charCodeAt(2)Returns the ascii code of the character at position 2
S.concat("1","2","3")Returns string with values "123" appended to the end of the string
S.indexOf("value")find first occurrence of string, or -1
S.lastIndexOf("value")find last occurrence of string, or -1
S.replace("abc","123")Returns the string with all instances of string "abc" replaced with "123"
S.slice(3,6)Returns string with characters inside range removed. Negative numbers are from end of string.
S[] .split(",")Returns an array of strings, split using the provided separator
S.toLowerCase()Returns string in "lower case"
S.toUpperCase()Returns string in "UPPER CASE"
Svalue.toString()Returns value as string
Svalue.toString(16)Returns number value as hex string
Promises

A Promise is in inbuilt JavaScript object which supports asynchronous handling of events via either a successful function or error function

// Success callback function success_callback(data) { ... } // Error callback function error_callback(message) { ... } // Define the promise var myPromise = new Promise(function(on_success,on_error)) { ... do something ... if (...positive case...) { on_success(...some data...); } else { on_error(...error message...); } ... perform cleanup ... }; // Invoke the promise myPromise.then( function(value) {success_callback(value);}, function(error) {error_callback(error);} );

A JavaScript Promise object has a State (Pending, Fulfilled, or Rejected) and a Result. Neither the State or the Result can be directly accessed from the Promise object, but the implementation of the Promise can assign the Result

RESTful Architecture

Stateless : client state data is typically not stored on the server

Client <--> Server : Separation between client and server, supports isolation, independence, atomicity

Cache : Data can be cached on the client

URL Composition : data type and record identity is conveyed through the URL

HTTP verbs : GET, POST, PUT, DELETE used to perform CRUD

  • GET - Read a record or get many records of a type
    • HTTP Response Code 200 (OK) on success
    • HTTP Response Code 404 (NOT FOUND) or 400 (Bad Request) on error
  • POST - Add a record, or subordinate (child) records of another parent object
    • HTTP Response Code 201 on success, returning a location header with a link to the newly created resource.
  • PUT - Update a record
    • On edit, HTTP Response Code 200 on success, or 204 if not returning content in body.
    • On create, HTTP Response Code 201 on success.
  • DELETE - Remove a record
    • HTTP Response Code 200 (OK) on success, with response body
  • PATCH - Modify a record, by sending only the changes in the request body (with instructions)
    • Use JSON patch or XML patch to describe in the body how a new resource will be created.

Fetch supports asynchronous data transmission over HTTP

fetch('http://example.com/movies.json') .then((response) => { return response.json(); }) .then((myJson) => { console.log(myJson); });

The fetch specification differs from jQuery.ajax() in three main ways:

  1. The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
  2. fetch() won't receive cross-site cookies; you can’t establish a cross site session using fetch. Set-Cookie headers from other sites are silently ignored.
  3. fetch won’t send cookies, unless you set the credentials init option. (Since Aug 25, 2017. The spec changed the default credentials policy to same-origin. Firefox changed since 61.0b13.)

// Example POST method implementation: async function postData(url = '', data = {}) { // Default options are marked with * const response = await fetch(url, { method: 'POST', // *GET, POST, PUT, DELETE, etc. mode: 'cors', // no-cors, *cors, same-origin cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: 'same-origin', // include, *same-origin, omit headers: { 'Content-Type': 'application/json' // 'Content-Type': 'application/x-www-form-urlencoded', }, redirect: 'follow', // manual, *follow, error referrerPolicy: 'no-referrer', // no-referrer, *client body: JSON.stringify(data) // body data type must match "Content-Type" header }); return await response.json(); // parses JSON response into native JavaScript objects } postData('https://example.com/answer', { answer: 42 }) .then((data) => { console.log(data); // JSON data parsed by `response.json()` call });