0% found this document useful (0 votes)
3K views

Notes JavaScript

Notes-JavaScript

Uploaded by

adrianblake1511
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3K views

Notes JavaScript

Notes-JavaScript

Uploaded by

adrianblake1511
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 34

-----------------------------------------------------------------------------------

--------------------------------------
///////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////
-----------------------------------------------------------------------------------
--------------------------------------
_ ____ _ _
| | __ ___ ____ _/ ___| ___ _ __(_)_ __ | |_
_ | |/ _` \ \ / / _` \___ \ / __| '__| | '_ \| __|
| |_| | (_| |\ V / (_| |___) | (__| | | | |_) | |_
\___/ \__,_| \_/ \__,_|____/ \___|_| |_| .__/ \__|
|_|

-----------------------------------------------------------------------------------
--------------------------------------
///////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////
-----------------------------------------------------------------------------------
--------------------------------------

===================================================================================
======================================

*************************
JavaScript - Introduction
*************************

> in HTML JS is inserted between the <script> and </script> tags

> 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

> JS accepts both single and double quotes

===================================================================================
======================================

*****************
JavaScript Output
*****************

> ways to get output from JS:


- innerHTML: write into an HTML element
- document.write(): write into the HTML output
- window.alert(): output into an alert box
- console.log(): output into the browser console
> the innerHTML property defines the HTML content of an element
eg.
---------------------------------
<script>
document.getElementById("test").innerHTML = <b>sample text</b>
</script>
---------------------------------

> 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

> window.alert(): outputs text into a popup window


- window keyword can be omitted, since the window object is a global scope object

> console.log(): outputs data into the browser console; used for debugging purposes

> can call window.print() to print the current window

===================================================================================
======================================

*********************
JavaScript Statements
*********************

> a JS program is a list of programming statements


- in HTML JS programs are executed by the browser
- JS statements are composed of values, operators, expressions, keywords,
comments
- a JS statement is terminated by a semicolon; multiple statements can be on the
same line. Terminating a statement
with semicolon is optional
- consecutive white spaces are ignored in JS

> line length and line breaks:


- programmers often avoid code lines longer than 80 characters
- when breaking a code statement into a new line, it's best to break after an
operator

> code blocks:


- JS statements can be grouped together inside curly brackets { }

===================================================================================
======================================

*****************
JavaScript Syntax
*****************

> values:
- fixed values are called literals
- variable values are called variables

> JS uses keywords var, let, const to declare variables


- equal sign(=) to assign values

> arithmetic operators: + - * /

> expressions: an expression is a combination of values, variables, operators,


which computes to a value

> comments: texts after // or between /* and */ are comments and not executed

> identifiers: identifiers are JS names, used to name variables, keywords,


functions
- a JS name must begin with a letter, or a dollar($) sign, or an underscore(_)
- JS identifiers are case sensitive

> JS uses the Unicode character set

===================================================================================
======================================

********************
JavaScript Variables
********************

> use var, let, const to declare variables


- var is used in JS since 1995; let and const were added in 2015. Must use var to
run JS in older browsers

> variables delared with const cannot be changed

> all variables must be identified with unique names (identifiers)


- a variable can be re-declared using var, but its value will not be changed

> data types:


- numbers in quotes are treated as strings

> 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
**************

> let was introduced in ES6 (2015)


- variables defined with let cannot be redeclared
- variables defined with let must be declared before use
- variables defined with let have block scope

> 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
****************

> const was introduced in ES6 (2015)


- variables defined with const cannot be redeclared
- variables defined with const cannot be reassigned
- variables defined with const have block scope

> const defines a constant reference to a value

> a const variable must be assigned a value when it is declared

> in general, use const when declaring new array, object, function, RegExp

> changing elements of a const array, or changing properties of a const object, is


allowed
eg.
---------------------------------
const fruits = ["apple", "orange", "peach"];
fruits[0] = "mango";

const car = {type:"BMW", year:"2015", color:"white"};


car.color = "black";
---------------------------------

> variables defined with const have block scope


- an existing variable can be redeclared in a separate block using const; the new
value is only effective within that
block
- redeclaring variables with const within the same block is not allowed

> a variable defined with const can only be used after it has been declared
(ReferenceError otherwise)

===================================================================================
======================================

********************
JavaScript Operators
********************

> types of operators:


- arithmetic
- assignment
- comparison
- logical
- conditional
- type
- bitwise

===================================================================================
======================================

*********************
JavaScript Arithmetic
*********************

> arithmetic operators: + - * / ** (ES2016) % ++ --

> x**y is the same as Math.pow(x,y)

===================================================================================
======================================

*********************
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

> adding numbers and strings will produce a string

> JS has dynamic types i.e. the same variable can be used to hold different data
types

> numbers in JS are stored as type double (64-bit floating point)

> 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 {}

> inside the function, parameters behave as local variables


> the function stops executing when it reaches a return statement

> invoking the function without the parentheses () will return the function object
instead of the function result

> variabled declared inside a function become local to the function

===================================================================================
======================================

******************
JavaScript Objects
******************

> an object contains name:value pairs, separated by commans, enclosed in curly


brackets
eg.
const car = {type:"Fiat", model:"500", color:"white"}

- it is common practice to declare objects using const

> each name:value pair is a property of the object

> accessing object properties: object.propertyName or object["propertyName"]

> 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;
}
};
---------------------------------

- accessing method: object.method()


- accessing method without the parentheses returns the method definition instead
of the method result

> 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

> JS counts position from 0

> slice(start, end)


- extracts part of a string, start and end params are start position and end
position (character at end position is
not included)
eg.
---------------------------------
let text = "apple, orange, pear";
let part = text.slice(7, 13); // returns "orange"
---------------------------------

- 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"
---------------------------------

> substring(start, end)


- similar to slice, but negative parameters are treated as 0
- if the second parameter is omitted, substring() extracts the rest of the string

> substr(start, length)


- extracts part of a string, start and length params are start position and
length of the substring
- if the second parameter is omitted, substr() extracts the rest of the string
- if a parameter is negative, the position is counted from the end of the string

> replace(string1, string2)


- replaces string1 in a given string with string2 (case sensitive); only replaces
the first match

> replaceAll(string1, string2)


- added in ES2021; same as replace, but will replace all matches found within
given string
> toUpperCase(string)
- converts given string to upper case

> toLowerCase(string)
- converts given string to lower case

> concat(string1, string2,...)


- joins given string with other strings; works like the plus(+) operator

> 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

> padStart(length, string)


- added in ES2017
- appends string param repeatedly to the start of a string until the result has
length equal to the length param
(excess characters will be truncated)
- does nothing if length of given string is equal to or greater than length param

> padEnd(length, string)


- added in ES2017
- appends string param repeatedly to the end of a string until the result has
length equal to the length param
(excess characters will be truncated)
- does nothing if length of given string is equal to or greater than length param

> 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

> ES2009 allows property access [] on strings


eg.
---------------------------------
let text = "Hello World";
let char = text[1]; // returns e
---------------------------------

- if no character is found, [] returns undefined (charAt returns empty string)


- [] is read-only i.e. cannot be used to replace part of 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
********************************

> indexOf(string1, [position])


- returns the index (position) of the first occurence of string1 param within a
given string
- if position param is specified, then the search will start from that position
eg.
---------------------------------
let text = "joins a string with another string";
let index1 = text.indexOf("string",5) // = 8
let index2 = text.indexOf("string",10) // = 28
---------------------------------

> lastIndexOf(string1, [position])


- returns the index (position) of the last occurence of string1 param within a
given string
- if position param is specified, then the search will end at that position
eg.
---------------------------------
let text = "joins a string with another string";
let index1 = text.lastIndexOf("string",10) // = 8
let index2 = text.lastIndexOf("string",30) // = 28
---------------------------------

> 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)

> includes(string1, [position])


- added in ES6; not supported in Internet Explorer
- returns true if a given string contains string1 param, returns false otherwise
- optional position param specifies where the search starts

> startsWith(string1, [position])


- not supported in Internet Explorer
- returns true if a given string (or part of a given string) starts with string1
param, returns false otherwise
- optional position param specifies where the search starts
> endsWith(string1, [position])
- not supported in Internet Explorer
- returns true if a given string (or part of a given string) ends with string1
param, returns false otherwise
- optional position param specifies where the search ends (end position not
included)

===================================================================================
======================================

*****************
JavaScript Number
*****************

> extra large/small numbers can be written with scientific notation


eg.
---------------------------------
let x = 12e5;
let y = 10e-5;
---------------------------------

> JS numbers are always 64-bit floating point


- the number part is stored in bits 0-51, exponent in bits 52-62, and sign in bit
63

> 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
---------------------------------

> maximum number of decimal points is 17

> floating point arithmetic is not always accurate


eg.
---------------------------------
let x = 0.2 + 0.1; // x will be 0.30000000000000004
---------------------------------

- can avoid this by multiply and divide by 10 (or 100, etc.)


eg.
---------------------------------
let x = (0.2 * 10 + 0.1 * 10) / 10;
---------------------------------

> numeric strings:


- a string can have numeric content: "10", "999", etc.
- in arithmetic operations (except addition(+)), JS will try to convert numeric
strings to numbers
eg.
---------------------------------
let x = "100" / "5"; // x will be 20
---------------------------------
> NaN - "not a string"
- NaN is a reserved word used to indicate that a value is not a number
- returns true if a value is not a number, returns false otherwise
- an operation with NaN as an operand will return NaN
- typeof NaN returns number

> division by 0 returns Infinity


- typeof Infinity returns number

> hexadecimal numbers:


- JS interprets numeric constants as hexadecimal if they are preceded by 0x
- some JS versions interprets numbers with a leading 0 as octal

> by default, numbers are base 10 decimals


- can use toString(b) to convert a number to base b (as string), eg.
number.toString(8), number.toString(16), etc.

===================================================================================
======================================

*****************
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(val) (global method)


- used to convert given value to number; if a number cannot be produced, NaN is
returned
- when used on Dates, converts the date to the number of milliseconds between Jan
01 1970 and the specified date

> parseInt(val) (global method)


- attempts to convert a value to an integer; if a string begins with a number,
that number will be used, returns
NaN otherwise
- can take an optional second argument that specifies the base (binary, decimal,
etc.) of the first argument

> parseFloat(val) (global method)


- attempts to convert a value to a float; if a string begins with a number, that
number will be used, returns NaN
otherwise

> 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

> MAX_SAFE_INTEGER / MIN_SAFE_INTEGER

> POSITIVE_INFINITY / NEGATIVE_INFINITY


- returned on overflow (division by 0)

> 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()

> it's common practice to declare arrays using const

> array elements are accessed by using index, starting from 0, eg. myArray[0],
myArray[1], etc.

> typeof returns "object" for arrays

> length property: returns the length of an array (= highest array index + 1)

> looping through an array's elements:


for:
eg.
---------------------------------
const fruits = ["apple", "orange", "mango"];
let text = "<ul>";
for (let i = 0; i < fruits.length; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
---------------------------------

forEach:
eg.
---------------------------------
const fruits = ["apple", "orange", "mango"];
let text = "<ul>";
fruits.forEach( function(val) { text += "<li>" + val + "</li>" } );
text += "</ul>";
---------------------------------

> adding elements to arrays:


- using push() method: myArray.push(newElement)
- using length: myArray[myArray.length] = newElement;
- adding an element with index higher than the array's length will create
undefined elements between the array's
last element and the newly added element

> to recognize an array:


- using Array.isArray(myArray): returns true if myArray is an array, returns
false otherwise
- using instanceof: myArray instance Array - returns true if myArray is an array,
returns false otherwise

===================================================================================
======================================

************************
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

> splice(pos, num, element1, element2,...)


- adds elements to an array and/or removes elements from an array
pos: position where new elements are added
num: number of elements to be removed
- removes elements without leaving undefined values in the array
- also returns the elements that were removed

> 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

> automatic toString()


- JS automatically converts an array to a string of comma-separated elements when
a primitive value is expected
(eg. when outputing the array as raw value)

===================================================================================
======================================

*********************
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

> the compare function


- to sort an array based on numeric values, use a compare function instead of
sort():
myArray.sort( function(a,b) { return a - b } )

- 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

> Math.max() / Math.min()


- can be used to find largest / smallest number in a numeric array
eg.
Math.max.apply(null, myArray);
Math.min.apply(null, myArray);

> sorting array of objects


- can use sort() to sort the objects based on values of a specified key
eg. sort objects based on values of key1
myArray.sort( function(a,b) { return a.key1 - b.key1 } )

===================================================================================
======================================

**************************
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

> indexOf(val, pos)


- searches an array for a specified value and returns its index (position)
- optional second parameter pos specifies starting position for the search; if
negative the starting position is
counted from the end of the array
- returns -1 if the value is not found
- if the value appears more than once, this returns the position of the first
occurrence

> lastIndexOf(val, pos)


- similar to indexOf, but returns the position of the last occurrence
- if pos is negative the starting position is counted from the end of the array
and the search continues to the
beginning of the 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

> new Date([year, month, day, hours, minutes, seconds, milliseconds])


- can take up to 7 arguments
- month is between 0 and 11 (inclusive)
- a month higher than 11 will add the overflow to the next year
- a day higher than the max day value for that month will add the overflow to the
next month
- month cannot be omitted; if only one argument is specified, it is treated as
millisecond
- year with one or two digits is interpreted as 19xx

> new Date()


- creates a date object with the current date and time

> new Date(date_string)


- creates a date object from the given date string
eg.
---------------------------------
const dt = new Date("October 10, 2014 16:20:00");
const dt = new Date("2020-05-31");
---------------------------------

> JS stores dates as milliseconds counting from January 01, 1970 00:00:00 UTC (zero
time)
- 1 day = 86400000ms

> when a date object is displayed in HTML, it is automatically converted to string


using toString()

> 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

> ISO dates can be written without month and/or day


- ISO dates can be written with added hours, minutes, and seconds: yyyy-mm-
ddThh:mm:ssZ
- date and time are separated with a capital T
- UTC time is defined with a capital Z at the end; is the same as GMT time
- to modify the time relative to UTC, remove the Z and add +hh-mm / -hh:mm at the
end
- omitting T or Z in a date-time string can give different results depending on
browsers

> time zones


- when specifying a date without a time zone, JS will use the browser's time zone
- when getting a date without a time zone specified, the result is converted to
the browser's time zone

> long dates


- month and day can be in any order
- month can be written in full or abbreviated, and is case insensitive
- commas are ignored

> parse()
- converts a valid date string to milliseconds, counting from Jan 01 1970

===================================================================================
======================================

*****************************
JavaScript Date - Get Methods
*****************************

> methods to get information from a date object


getFullYear - gets year (yyyy)
getMonth - gets month (0-11) (0 = Jan)
getDate - gets day (1-31)
getDay - gets week day (0-6) (0 = Sunday)
getHours - gets hour (0-23)
getMinutes - gets minute (0-59)
getSeconds - gets second (0-59)
getMilliseconds - gets millisecond (0-999)
getTime - gets number of milliseconds since 01/01/1970 (= Date.now())

- for UTC values, add UTC after get


- difference between local time and UTC time can be up to 24 hours

> 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
*****************************

> methods to set part of a date object


setFullYear - sets year (optionally month and day)
setMonth - sets month
setDate - sets day
setHours - sets hour
setMinutes - sets minute
setSeconds - sets second
setMilliseconds - sets milliseconds
setTime - sets number of milliseconds since 01/01/1970

- using a value outside of the proper range will shift the calculated time

> dates are stored as milliseconds so can be easily compared

===================================================================================
======================================

***************
JavaScript Math
***************

> the Math object is static and all of its methods and properties can be used
without creating a Math object first

> JS has 8 constants that can be accessed as Math properties


Math.E - returns Euler's number
Math.PI - returns pi
Math.sqrt2 - returns square root of 2
Math.sqrt1_2 - returns square root of 1/2
Math.LN2 - returns the natural logarithm of 2
Math.LN10 - returns the natural logarithm of 10
Math.LOG2E - returns base 2 logarithm of e
Math.LOG10E - returns base 10 logarithm of e

> 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.min() / Math.max()


- returns the min / max value in a list of arguments

> 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 with a value is true

> everything without a value is false: 0, null, undefined, NaN, false, empty
strings

> comparing two JS objects always returns false

===================================================================================
======================================
********************************************
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

> the nullish coalescing operator x ?? y


- returns the first argument if it is not nullish (neither null nor undefined);
returns the second argument otherwise

> the optional chaining operator ?.


- returns undefined if an object is null or undefined instead of throwing an
error
eg. car?.name

===================================================================================
======================================

******************
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

> "default" specifies the code to be executed if there is no case match

> 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
*****************

> for of loops through the values of an iterable object


- added in ES6; not supported in Internet Explorer
eg.
---------------------------------
const fruits = ['apple', 'orange', 'mango'];
let txt = '';
for (x of fruits) {
txt += x;
}
---------------------------------

===================================================================================
======================================

****************
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

> can be used with labels:


break labelName; - exit the block of code to which labelName was assigned
continue labelName; - skip current iteration and start the next iteration of the
loop to which labelName was assigned

===================================================================================
======================================

***************
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

> creating a new set:


- by passing an array to new Set(), or creating an empty set and adding elements
to it with add()

> 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

> creating a new map:


- by passing an array to new Map(), or creating an empty map and adding key/value
pairs to it with set()

===================================================================================
======================================

*****************
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
---------------------------------

> typeof NaN is a number


- typeof null is an object
- typeof undefined variables or variables without a value is undefined

> 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 + operator can be used to convert a variable to a number


eg. y = '5'; x = + y;

> the global method String(), and the Number method toString(), can be used to
convert numbers to strings

> other Number methods that return a string: toExponential(), toFixed(),


toPrecision()

> dates can be converted to numbers (number of milliseconds since 01/01/1970) by


the global method Number() or the date
method getTime()

> Number() can convert boolean values to numbers: Number(true) = 1, Number(false) =


0

> when performing operations on different data types, JS automatically attempts to


convert the operands to the same type;
may yield unexpected results

===================================================================================
======================================

****************************
JavaScript Bitwise Operators
****************************

> bitwise operators


AND & - returns 1 if both bits are 1
OR | - returns 1 if one of two bits is 1
XOR ^ - returns 1 if only one of two bits is 1
NOT ~ - inverts every bit
Zero fill left shift << - shifts left by pushing zeroes in from the right and let
leftmost bits fall off
Zero fill right shift >>> - shifts right by pushing zeroes in from the left and
let rightmost bits fall off
Signed right shift >> - shifts right by pushing in copies of the leftmost bit
from the left and let rightmost bits
fall off

eg. using 4 bits unsigned binary numbers


---------------------------------
5 & 1 - 0101 & 0001 -> 0001
5 | 1 - 0101 | 0001 -> 0101
5 ^ 1 - 0101 ^ 0001 -> 0100
~5 - ~0101 -> 1010
5 << 1 - 0101 << 1 -> 1010
8 >>> 1 - 1000 >>> 1 -> 0100
8 >> 1 - 1000 >> 1 -> 1100
---------------------------------

> JS uses 32 bit signed integers (left-most bit stores the sign)

===================================================================================
======================================

******************************
JavaScript Regular Expressions
******************************

> a regular expression is a sequence of characters that specify a search pattern,


used to describe what the user is
searching for in some text

> syntax: /pattern/modifiers


eg. /spring/i -> search for "spring", the "i" specifies case-insensitive
> modifiers:
i - indicates case-insensitive
g - finds all matches instead of stopping at first match
m - indicates multiline matching

> often used with two String methods: search() and replace()

> brackets are used to indicate a range of characters


eg.
---------------------------------
[agm] - find any of the characters (including numbers) between the brackets
[0-6] - find any number from 0 to 6
(foo|bar) - find any of the groups of characters separated by |
---------------------------------

> metacharacters: characters with special meaning


\d - find a digit
\s - find a whitespace character
\b - find a match at the beginning or at the end of a word eg. /\bfoo/g or /foo\
b/g
\uxxxx - find the Unicode character specified by the hex number xxxx

> quantifiers: define quantities


n+ - returns a match if a string contains at least one n
n* - returns a match if a string contains none or more occurrences of n
n? - returns a match if a string contains none or one occurence of n

> 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
**********************

> "use strict" is a directive added in ES5


- a literal expression, ignored by earlier versions of JS
- indicates that the code that follows is to be executed in "strict" mode
- is only recognized if used at the beginning of a script or function

> strict mode:


- makes it easier to write secure / clean JS
- strict mode changes previously accepted "bad syntax" into real errors

> not allowed in strict mode:


- using undeclared variables/objects
- deleting variables/objects/functions
- deleting undeletable properties
- octal numeric literals / octal escape characters
- writing to a read-only property or get-only property
- keywords "eval", "arguments" cannot be used as variable name
- "with" statements
- "eval" cannot be used to create variables in the same scope from which it was
called
- "eval" cannot declare variables using let, var

> 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
***************

> stands for JavaScript Object Notation


- is a lightweight data interchange format
- is plain text written in JS object notation
- is used to send data between computers
- is language independent; code for reading/generating JSON exists in most
programming languages

> JSON format is syntactically similar to code for generating JS object, so a JS


program can easily convert JSON data to
JS object
- JSON is text only, so can be sent easily between computers, and used by any
programming language
- JS has a built-in function for converting JSON strings into JS objects:
JSON.parse(), and a built-in function for
converting a JS object into a JSON string: JSON.stringify()

-----------
JSON Syntax
-----------

> is a subset of JS syntax


- data is in name-value (key-value) pairs
- data is separated by commas
- curly braces hold objects
- square brackets hold arrays

> 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, keys must be strings, enclosed in double quotes


- in JS, keys can be strings, numbers, or identifier names

> 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
************

> a callback is a function passed as an argument to another function


eg.
---------------------------------
function myFunction(param1, param2, myCallback) {
myCallback(param3);
}
---------------------------------

===================================================================================
======================================

***************
JS Asynchronous
***************

> asynchronous functions are functions running in parallel

> setTimeout(myFunction, duration)


- executes myFunction after duration in milliseconds

> setInterval(myFunction, duration)


- executes myFunction every [duration] milliseconds

> 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();
});

// consuming code (must wait for a fulfilled promise)


myPromise.then (
function(value) { /* code on success */ }
function(error) { /* code on error */ }
);
---------------------------------

> when the producing code has finished, it should call one of the two callbacks:
success - myResolve(result value)
error - myReject(error object)

> promise object properties: 'state' and 'result'


promise.state -- promise.result
pending -- undefined
fulfilled -- result value
rejected -- 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

>

You might also like