Notes JavaScript
Notes JavaScript
--------------------------------------
///////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////
-----------------------------------------------------------------------------------
--------------------------------------
_ ____ _ _
| | __ ___ ____ _/ ___| ___ _ __(_)_ __ | |_
_ | |/ _` \ \ / / _` \___ \ / __| '__| | '_ \| __|
| |_| | (_| |\ V / (_| |___) | (__| | | | |_) | |_
\___/ \__,_| \_/ \__,_|____/ \___|_| |_| .__/ \__|
|_|
-----------------------------------------------------------------------------------
--------------------------------------
///////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////
-----------------------------------------------------------------------------------
--------------------------------------
===================================================================================
======================================
*************************
JavaScript - Introduction
*************************
> scripts can be placed in the <head> section or in the <body> section
- placing scripts at the bottom of the <body> section improves display speed
> external scripts: it's a good idea to put scripts in an external file if the
scripts are used in many different pages
- to insert an external script, assign the file name to the src attribute of the
<script> tag
eg.
<script src="myscript.js"></script>
- advantages of using external scripts: HTML and scripts are separated, are
easier to maintain, and cached JS files can
speed up page load
- use multiple <script> tags to insert multiple external script files
===================================================================================
======================================
*****************
JavaScript Output
*****************
> document.write(): outputs text into the page; will delete existing HTML if called
after the page is loaded
- should only be used for testing purposes
> console.log(): outputs data into the browser console; used for debugging purposes
===================================================================================
======================================
*********************
JavaScript Statements
*********************
===================================================================================
======================================
*****************
JavaScript Syntax
*****************
> values:
- fixed values are called literals
- variable values are called variables
> comments: texts after // or between /* and */ are comments and not executed
===================================================================================
======================================
********************
JavaScript Variables
********************
> in a calculation, all numbers that come after a string will be treated as strings
and will be concatenated
eg.
"2" + 3 + 4 + "5" -> evaluates to "2345"
2 + 3 + "5" -> evaluates to "55"
===================================================================================
======================================
**************
JavaScript Let
**************
> redeclaring a variable with let inside a block does not affect the variable's
value outside the block
> a variable can be redeclared with let in a different block, but not within the
same block
> a variable defined with let can only be used after it has been declared
(ReferenceError otherwise)
===================================================================================
======================================
****************
JavaScript Const
****************
> in general, use const when declaring new array, object, function, RegExp
> a variable defined with const can only be used after it has been declared
(ReferenceError otherwise)
===================================================================================
======================================
********************
JavaScript Operators
********************
===================================================================================
======================================
*********************
JavaScript Arithmetic
*********************
===================================================================================
======================================
*********************
JavaScript Data Types
*********************
> JS has 8 data types: string, number, bigint, boolean, undefined, null, symbol,
object
> the object data type can contain: an object, an array, a date
> JS has dynamic types i.e. the same variable can be used to hold different data
types
> BigInt (added in 2020) is used to store integer values too big to be represented
by a normal JS number
===================================================================================
======================================
********************
JavaScript Functions
********************
> a function is defined with the keyword function, followed by a name for the
function, then parentheses which can
contain parameters (separated by commas)
> the code to be executed by the function are contained within curly brackets {}
> invoking the function without the parentheses () will return the function object
instead of the function result
===================================================================================
======================================
******************
JavaScript Objects
******************
> objects can have methods; methods are defined the same way as function
definitions
eg.
---------------------------------
const person = {
firstName: "John";
lastName: "Doe";
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
---------------------------------
> avoid declaring String, Number, Boolean as objects; they slow down execution
speed
===================================================================================
======================================
*****************
JavaScript Events
*****************
> an HTML event is something the browser does, or something the user does, and can
be detected by the browser
> HTML allows event handler attributes and JS code to be added to HTML elements
eg.
---------------------------------
<button onclick="JS code"> Click here </button> // direct JS code
or
<button onclick="myFunction()"> Click here </button> // calling a function
---------------------------------
===================================================================================
======================================
*************************
JavaScript String Methods
*************************
> length
- returns the length of a string
- if the second parameter is omitted, slice() extracts the rest of the string
- if a parameter is negative, the position is counted from the end of the string
eg.
---------------------------------
let text = "apple, orange, pear";
let part = text.slice(7, -6); // returns "orange"
---------------------------------
> toLowerCase(string)
- converts given string to lower case
> trim()
- removes whitespace from two sides of a string
> trimStart()
- added in ES2019
- removes whitespace from the beginning of a string
> trimEnd()
- added in ES2019
- removes whitespace from the end of a string
> charAt(position)
- returns the character at the specified index (position) within a given string
> charCodeAt(position)
- returns an UTF-16 code (an integer between 0 and 65535) of the character at the
specified index (position)
within a given string
> split(separator)
- converts given string into an array; given string is split at the specified
separator
- if separator param is omitted, the returned array contains the entire given
string at index 0
- if separator = "", the given string is split after every single character
===================================================================================
======================================
********************************
JavaScript String Search Methods
********************************
> search(string1)
- returns the index (position) of the first occurence of string1 param within a
given string
- unlike indexOf(), search() accepts a regular expression, and cannot take a
position as the second parameter
> match(string1)
- searches a given string and returns an array containing all the matches against
string1 (or a regular expression)
param
- without the regular expression modifier g (global search), search() returns
only the first match
> matchAll(string1)
- added in ES2020; not supported in Internet Explorer
- returns an iterator containing the results of matching a given string against
string1 param (or a regular expression)
===================================================================================
======================================
*****************
JavaScript Number
*****************
> integers (numbers without a decimal point or exponent notation) are accurate up
to 15 digits
eg.
---------------------------------
let x = 999999999999999; // will be 999999999999999
let y = 9999999999999999; // will become 10000000000000000
---------------------------------
===================================================================================
======================================
*****************
JavaScript BigInt
*****************
> JS stores numbers in 64-bit floating point format (IEEE 754 standard)
- JS can only safely represent integers up to (2^53 - 1) or 9007199254740991, and
down to -(2^53 - 1)
or -9007199254740991. Integer values outside this range lose precision
- to create a BigInt, append n to the end of the integer, or call BigInt()
eg.
---------------------------------
let x = 1234567890123456789012345n
let y = BigInt(1234567890123456789012345)
---------------------------------
- operators that can be used on Number can also be used on BigInt
- arithmetic between a BigInt and a Number is not allowed
- division between two BigInts cannot produce a decimal number (result is
truncated to a BigInt)
> ES6 added MAX_SAFE_INTEGER and MIN_SAFE_INTEGER to Number object, which return
the largest and smallest integer
values that can be safely represented by JS
Number.MAX_SAFE_INTEGER = 9007199254740991; Number.MIN_SAFE_INTEGER = -
9007199254740991;
- not supported in Internet Explorer
> isInteger(num)
- returns true if the argument is an integer, returns false otherwise
> isSafeInteger(num)
- returns true if the argument can be exactly represented as a double precision
number (safe integer), return false
otherwise
===================================================================================
======================================
*************************
JavaScript Number Methods
*************************
> toString()
- returns a number as a string
> toExponential()
- returns a string as a number written using exponenial notation
- optional parameter to specify the number of decimal places; if omitted, the
number is not rounded
eg.
---------------------------------
let x = 31415;
let y = x.toExponential();
let z = x.toExponential(3);
---------------------------------
> toFixed()
- returns a string, with the nubmer written with a specified number of decimal
places
- if no argument is provided, the number is rounded to the nearest integer
(number of decimal places = 0)
eg.
---------------------------------
let x = 15.325;
let y = toFixed(2);
let z = toFixed(4);
---------------------------------
> toPrecision()
- returns a string, with the number written with a specified length
- optional parameter to specify the length; if omitted, the number is unaltered
> valueOf()
- used internally by JS to convert Number objects or numeric strings to primitive
values
> Number.isInteger(val)
- returns true if the argument is an integer
> Number.isSafeInteger(val)
- returns true if the argument can be exactly represented as a double precision
number (safe integer), return false
otherwise
> Number.parseInt(val)
- attempts to convert a value to an integer; if a string begins with a number,
that number will be used, returns
NaN otherwise
> Number.parseFloat(val)
- attempts to convert a value to a float; if a string begins with a number, that
number will be used, returns NaN
otherwise
> ES6 added MAX_SAFE_INTEGER and MIN_SAFE_INTEGER to Number object, which return
the largest and smallest integer
values that can be safely represented by JS
- not supported in Internet Explorer
===================================================================================
======================================
****************************
JavaScript Number Properties
****************************
> EPSILON
- the difference between 1 and the smallest floating point number greater than 1
- added in ES6; not supported in Internet Explorer
> MAX_VALUE
- largest number possible in JS
> MIN_VALUE
- smallest number possible in JS
> NaN
- reserved word for a value that is not a number
===================================================================================
======================================
*****************
JavaScript Arrays
*****************
> JS arrays are a special kind of objects that use numbered indexes
> it's preferable to create arrays using array literals instead of new Array()
> array elements are accessed by using index, starting from 0, eg. myArray[0],
myArray[1], etc.
> length property: returns the length of an array (= highest array index + 1)
forEach:
eg.
---------------------------------
const fruits = ["apple", "orange", "mango"];
let text = "<ul>";
fruits.forEach( function(val) { text += "<li>" + val + "</li>" } );
text += "</ul>";
---------------------------------
===================================================================================
======================================
************************
JavaScript Array Methods
************************
> toString()
- converts the array to a string of array values (comma separated)
> join([separator])
- same as toString, but a separator can be specified
eg. myArray.join(" ; ");
> pop()
- removes the last element from an array; also returns the element that was
removed
> push(newElement)
- adds an element to the end of an array; also returns the length of the new
array
> shift()
- "shifts" all elements up 1 position and removes the first element; also returns
the element that was removed
> unshift(newElement)
- adds an element to the beginning of an array and pushes other elements down 1
position; also returns the length of
the new array
> delete
- deletes an element in an array; leaves undefined value in the array
eg. delete myArray[0]
> concat()
- merges (concatenates) arrays into a new array
eg. myArray.concat(array1, array2,...)
- can also take a string as argument, the string is added to the array as a new
element
- returns a new array and does not alter the original array
> slice(pos1,pos2)
- extracts elements from an array, starting from position pos1, optionally up to
position pos2
- if pos2 is omitted, slices from position pos1 to the end of the array
- returns a new array and does not alter the original array
===================================================================================
======================================
*********************
JavaScript Array Sort
*********************
> sort()
- sorts the elements of an array alphabetically
> reverse()
- reverses the order of elements in an array; combined with sort() to sort an
array in reversed alphabetical order
- two elements a and b are sorted based on the return value of the compare
function: if the result is negative then
a is sorted before b; if the result if positive then a is sorted after b; if the
result is 0 then no change is made
to the order of a and b
===================================================================================
======================================
**************************
JavaScript Array Iteration
**************************
> forEach()
- the array method forEach() calls a specified function once for each array
element
eg.
---------------------------------
myArray.forEach(myFunction);
function myFunction(value, index, array) { }
---------------------------------
- the function called by forEach() can accept 3 parameters: the value of the
element, the index of the element, and
the original array
> map()
- creates a new array by performing a function on each element of the original
array
- does not execute the function for elements without a value
- does not change the original array
eg.
---------------------------------
const myArray;
const myArray2 = myArray.map(myFunction);
function myFunction(value, index, array) { }
---------------------------------
- the function called by map() can accept 3 parameters: the value of the element,
the index of the element, and the
original array
> filter()
- creates a new array where elements from the original array meet specific
requirements
eg.
---------------------------------
const myArray = [4, -20, 0, 15, -100];
const positiveNum = myArray.filter(myFunction);
function myFunction(value, index, array) {
return value > 0;
}
---------------------------------
> reduce()
- calls a function on each element of the original array (from left to right) to
reduce the array to a single value
- does not reduce the original array
eg. reduces the array to sum of its elements
---------------------------------
const myArray = [1, 2, 3, 4, 5];
const sum = myArray.reduce(myFunction);
function myFunction(total, value, index, array) {
return total + value;
}
---------------------------------
- the total param is the initial value / previously returned total value
- can take a second parameter as the initial value for total
> reduceRight()
- same as reduce(), but iterates from right to left over the elements
> every()
- checks if all elements of an array meet a specific requirement
- returns false if any one element fails the check
eg. myArray.every( myFunction() { } );
- myFunction can take 3 arguments: value, index, array
> some()
- checks if any element of an array meets a specific requirement
- return true if at least one element passes the check
eg. myArray.some( myFunction() { } );
- myFunction can take 3 arguments: value, index, array
> find()
- returns the value of the first element in the array that meets a specified
requirement
eg.
---------------------------------
myArray.find(myFunction);
function myFunction(value, index, array) { }
---------------------------------
- myFunction can take 3 arguments: value, index, array
- added in ES6 (2015); not supported in Internet Explorer
> findIndex()
- returns the index of the first element in the array that meets a specified
requirement
eg.
---------------------------------
myArray.findIndex(myFunction);
function myFunction(value, index, array) { }
---------------------------------
- myFunction can take 3 arguments: value, index, array
- added in ES6 (2015); not supported in Internet Explorer
> from()
- returns an array object created from any object with a length property or any
iterable object
eg.
---------------------------------
Array.from("Hello World!");
---------------------------------
- added in ES6 (2015); not supported in Internet Explorer
> keys()
- returns an array iterator object containing the keys of an array
- added in ES6 (2015); not supported in Internet Explorer
> entries()
- returns an array iterator object containing the key/value pairs of an array
- added in ES6 (2015); not supported in Internet Explorer
> includes()
- returns true if a specified value is present in an array
- allows checking for NaN values, unlike indexOf()
- added in ES2016; not supported in Internet Explorer
> spread(...)
- expands an iterable into more elements; functions similarly to concat()
- added in ES6 (2015); not supported in Internet Explorer
===================================================================================
======================================
****************
JavaScript Dates
****************
> JS uses the browser's time zone to display date and time as a string
> JS stores dates as milliseconds counting from January 01, 1970 00:00:00 UTC (zero
time)
- 1 day = 86400000ms
> toDateString()
- converts a date object to a date string (without the time part)
> toUTCString()
- converts a date object to a date-time string using the UTC standard
> toISOString()
- converts a date object to a date-time string using the ISO standard
===================================================================================
======================================
***********************
JavaScript Date Formats
***********************
> 3 formats:
- ISO (International Standard): "2015-03-25"
- short: "03/25/2015"
- long: "Mar 25 2015" or "25 Mar 2015"
> regardless of input format, JS will by default output full date-time string
> ISO 8601 is the international standard for date-time representation: yyyy-mm-dd
- also the preferred JS date format
> the computed time is relative to the user's time zone
> parse()
- converts a valid date string to milliseconds, counting from Jan 01 1970
===================================================================================
======================================
*****************************
JavaScript Date - Get Methods
*****************************
> getTimezoneOffset()
- returns the difference between local time and UTC time in minutes
- negative if local time is ahead of UTC time; positive if local time is behind
===================================================================================
======================================
*****************************
JavaScript Date - Set Methods
*****************************
- using a value outside of the proper range will shift the calculated time
===================================================================================
======================================
***************
JavaScript Math
***************
> the Math object is static and all of its methods and properties can be used
without creating a Math object first
> Math.round(x)
- returns the nearest integer
> Math.ceil(x)
- returns the smallest integer that is equal to or greater than the given number
> Math.floor(x)
- returns the greatest integer that is equal to or less than the given number
> Math.trunc(x)
- returns the integer part of the given number
- added in ES6
> Math.sign(x)
- returns the sign (positive / null / negative) of the given number
- added in ES6
> Math.pow(x,y)
- returns the value of x to the power of y
> Math.sqrt(x)
- returns the square root of x
> Math.abs(x)
- returns the absolute value of x
> Math.sin(x)
- returns the sine of the angle x (given in radians)
> Math.cos(x)
- returns the cosine of the angle x (given in radians)
> Math.random()
- returns a random number between 0 (inclusive) and 1 (exclusive)
eg. returns a random integer between two integers min (inclusive) and max
(exclusive)
---------------------------------
function getRndNum(min,max) {
return Math.floor(Math.random() * (max-min)) + min
}
---------------------------------
> Math.log(x)
- returns the natural logarithm of x
> Math.log2(x)
- returns the base 2 logarithm of x
> Math.log10(x)
- returns the base 10 logarithm of x
===================================================================================
======================================
*******************
JavaScript Booleans
*******************
> the Boolean data type can only have value "true" or "false"
> Boolean(expression)
- returns if given expression is true; return false if no expression is given
- can also be used to create a boolean object: let x = new Boolean(expression);
> everything without a value is false: 0, null, undefined, NaN, false, empty
strings
===================================================================================
======================================
********************************************
JavaScript Comparisons and Logical Operators
********************************************
> when comparing a number and a string, JS will try to convert the string to a
number; an empty string converts to 0
===================================================================================
======================================
******************
JavaScript if else
******************
if (condition) {
} else if (condition) {
} else {
}
> the keywords if / else have to be lowercase, otherwise an error will be generated
===================================================================================
======================================
*****************
JavaScript switch
*****************
switch(expression) {
case x:
break;
case y:
break;
default:
}
> without a break to stop the execution of the switch block, the code execution
will "fall through" and the next case
will be executed even if the evaluation does not match that case
> if multiple cases match a case value, the first case is selected
> switch case uses strict comparison (===) to decide if the case matches the
expression
===================================================================================
======================================
*******************
JavaScript For loop
*******************
eg.
---------------------------------
let text = '';
for (let i = 0; i < myArray.length; i++) {
text += myArray[i] + '<br/>';
}
---------------------------------
> the first expression can be omitted if the starting condition has been set before
the for loop
> multiple variables can be initiated within the first expression, separated by
comma
> the second expression (condition to stop the loop) can be omitted, but a break
needs to be provided inside the loop,
otherwise the loop will be infinite and crash the browser
> the third expression can be omitted if the counter is incremented inside the loop
===================================================================================
======================================
*****************
JavaScript for in
*****************
> for in loops through the properties of an object (each iteration returns a key
name)
eg.
---------------------------------
const person = {firstName:'John', lastName:'Doe', age:25};
let text = '';
for (let x in person) {
text += person[x] + ' ';
}
---------------------------------
> for in also loops through the elements of an array (each iteration returns an
index value)
===================================================================================
======================================
*****************
JavaScript for of
*****************
===================================================================================
======================================
****************
JavaScript while
****************
> the while loop repeats a block of code for as long as the specified condition is
true
- if the variable used in the condition is never changed so that the condition
will become false at some point, the
loop will be infinite and crash the browser
- the condition is evaluated before the loop is executed
> the do-while loop is similar to the while loop, but the loop is executed once
before the condition is evaluated
===================================================================================
======================================
*****************************
JavaScript break and continue
*****************************
> the break statement jumps out of a loop or switch; the continue statement stops
the current iteration and moves on to
the next iteration in a loop
===================================================================================
======================================
***************
JavaScript Sets
***************
> methods:
new Set() - creates a new set
add() - adds a new element to the set
delete() - removes an element from the set
has() - returns true if a specified element exists in the set
forEach() - invokes a callback function for each element in the set
values() - returns an iterator with all the values in the set
> properties:
size - returns the number of elements in the set
> add()
- when adding the same elements, only the first one is saved
> values()
- returns a new iterator object containing all values in a set
===================================================================================
======================================
***************
JavaScript Maps
***************
> a map holds key-value pairs where the keys can be any data type
> methods
new Map() - creates a new map
set() - sets the value for a key in a map
get() - gets the value for a key in a map
delete() - removes a map element specified by the key
has() - returns true if a key exists in a map
forEach() - invokes a callback function for each key/value pair in a map
entries() - returns an iterator containing the key/value pairs in a map
> properties:
size - returns the number of key/value pairs in a map
===================================================================================
======================================
*****************
JavaScript typeof
*****************
> the typeof operator can return: string, number, boolean, object, function,
undefined
eg.
---------------------------------
typeof 5 // returns 'number'
typeof 'John Doe' // returns 'string'
typeof true // returns boolean
---------------------------------
> the constructor property returns the constructor function for all JS variables
- can be used to check if an object is an array (constructor function name
contains the word "Array")
ie. myArray.constructor.toString().indexOf('Array') > -1 or myArray.constructor
=== Array)
> instanceof
- returns true if the object is an instance of the specified data/object type
eg.
---------------------------------
5 instance of Number // true
'John Doe' instanceof String // true
---------------------------------
> void
- evaluates an expression and returns undefined
===================================================================================
======================================
**************************
JavaScript Type Conversion
**************************
> Number()
- converts a numeric string to a number
- converts empty string '' to 0
- converts non-numeric string to NaN
> parseFloat()
- parses a string and returns a floating point number
> parseInt()
- parses a string and returns an integer
> the global method String(), and the Number method toString(), can be used to
convert numbers to strings
===================================================================================
======================================
****************************
JavaScript Bitwise Operators
****************************
> JS uses 32 bit signed integers (left-most bit stores the sign)
===================================================================================
======================================
******************************
JavaScript Regular Expressions
******************************
> often used with two String methods: search() and replace()
> the RegEx object: a regular expression object with predefined properties and
methods
- test(str) - searches a pattern; returns true if a match is found
eg.
---------------------------------
const pattern = /e/;
pattern.test("Sample Text");
---------------------------------
- exec() - searches a pattern; returns the found text as an object; returns null
if no match is found
===================================================================================
======================================
*************************
JavaScript Error Handling
*************************
> try-catch(err)
- "try" defines a block of code for JS to (attempt) to run
- "catch" defines a block of code to be executed if an error occurs in the "try"
block
> throw
- the throw statement allows creating custom error
- the exception thrown can be a string, number, boolean, or object
- can be used with try-catch to control program flow and generate custom error
messages
> finally
- defines a block of code to be executed after a try-catch section is completed,
regardless of whether an error occurs
or not
- syntax:
try {
// block of code
} catch(err) {
// block of code
} finally {
// block of code
}
> when JS throws an exception, an Error object is created with two properties: name
and message
- name can return: EvalError, RangeError, ReferenceError, SyntaxError, TypeError,
URIError
EvalError - thrown when there is an error in the eval() function
(newer versions of JS don't throw EvalError; use SyntaxError instead)
RangeError - thrown when a number is outside of the legal range of values
ReferenceError - thrown when an undeclared variable is referenced
SyntaxError - thrown when the code has syntax errors
TypeError - thrown when a wrong data type is passed to a method
URIError - thrown when there are illegal characters in URI functions
===================================================================================
======================================
**********************
JavaScript Strict Mode
**********************
> in strict mode, "this" refers to the object that calls the function
- if the object is not specified, functions in strict mode will return undefined
and functions in normal mode will
return the global object (window)
> keywords reserved for future versions of JS cannot be used as variable names in
strict mode:
implements, interface, let, package, private, protected, public, static, yield
===================================================================================
======================================
***********************
JavaScript this keyword
***********************
> the "this" keyword refers to different objects depending on how it is called
- in an object method, "this" refers to the object
- by itself, "this" refers to the global object [object Window]
- in a function, by default, "this" refers to the global object
- in a function in strict mode, "this" is undefined
- in an event, "this" refers to the object that received the event
- methods call(), apply(), and bind() can refer "this" to any object
===================================================================================
======================================
***************
JavaScript JSON
***************
-----------
JSON Syntax
-----------
> a name/value pair consists of a field name in double quotes, followed by a colon,
followed by a value
eg. "name":"John"
> in JSON, values must be one of the types: string, number, object, array, boolean,
null
- in JS, values can be any of the above, plus any other valid JS expression,
including a function, a date, or
undefined
- in JSON, values must be enclosed in double quotes; in JS, values can be
enclosed in single quotes
> the file type for JSON files is .json; the MIME type for JSON text is
application/json
-----------
JSON vs XML
-----------
---------------
JSON Data Types
---------------
----------
JSON parse
----------
> when receiving data from a web server, the data is always a string
- parse the data with JSON.parse() to get a JS object
eg.
---------------------------------
const obj = JSON.parse('{"name":"John", "age":"30", "city":"London"}');
---------------------------------
> when using JSON.parse() on a JSON derived from an array, the method will return a
JS array instead of a JS object
> JSON.parse() can take a second parameter called a reviver - a function that
checks each property before returning
a value
eg.
---------------------------------
const text = '{"name":"John", "birthdate":"1986-12-14", "city":"London"}';
const obj = JSON.parse(text, function(key,value) {
if (key == "birthdate") {
return new Date(value);
} else {
return value;
}
});
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birthday;
---------------------------------
--------------
JSON stringify
--------------
> when sending data to a web server, the data has to be a string
- a JS object can be converted into a string with JSON.stringify
eg.
---------------------------------
const obj = {name:"John", age:30, city:"London"};
const jsonString = JSON.stringify(obj);
// jsonString = {"name":"John", "age":"30", "city":"London"}
---------------------------------
===================================================================================
======================================
************
JS Callbacks
************
===================================================================================
======================================
***************
JS Asynchronous
***************
> asynchronous programs are difficult to write and debug; modern asynchronous
programming is handled using Promises
instead
===================================================================================
======================================
***********
JS Promises
***********
> concepts
- producing code: code that can take some time to finish
- consuming code: code that must wait for the result
- promise: a JS object that links producing and consuming code
> a JS promise object contains both the producing code and calls to the consuming
code
> syntax
---------------------------------
let myPromise = new Promise(function(myResolve, myReject) {
// producing code
myResolve();
myReject();
});
> when the producing code has finished, it should call one of the two callbacks:
success - myResolve(result value)
error - myReject(error object)
- state and result cannot be accessed; a Promise method must be used to handle
promises
> promise.then
promise.then(
function(value) { /* code on success */ }
function(error) { /* code on error */ }
)
- promise.then() takes two arguments, a callback for success and another for
failure; both are optional
>