diff --git a/CHANGELOG.md b/CHANGELOG.md index de66904891..40336b6d94 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,12 @@ Git History on master by all authors -
- Original + + Original + + + Merge pull request #1564 from bgoonz/master 3e3b8baab (HEAD -> master, origin/master, origin/HEAD) by Bryan C Guner <66654881+bgoonz@users.noreply.github.com>, Sat Jan 22 2022 (2 days ago) @@ -104,7 +107,7 @@ ffb04efe8 by Bryan C Guner <66654881+bgoonz@users.noreply.github.com>, Sat Jan 2 Merge pull request #1560 from bgoonz/preview 68d7afa15 by Bryan C Guner <66654881+bgoonz@users.noreply.github.com>, Sat Jan 22 2022 (2 days ago) -site-metadata.json: Multiple updates: _ updated social_links in footer _ updated links in footer \* updated new_window in links +site-metadata.json: Multiple updates: _updated social_links in footer_ updated links in footer \* updated new_window in links cb64efe0c by Bryan Guner , Sat Jan 22 2022 (2 days ago) 1 file changed, 17 insertions(+), 1 deletion(-) @@ -202,7 +205,7 @@ Create github-profiles.md b8ff2ca1e by Bryan C Guner <66654881+bgoonz@users.noreply.github.com>, Fri Jan 21 2022 (3 days ago) 1 file changed, 112 insertions(+) -Merge branch 'master' of https://github.com/Web-Dev-Collaborative/BGOONZ_BLOG_2.0 +Merge branch 'master' of f7771c7cf by Bryan C Guner <66654881+bgoonz@users.noreply.github.com>, Fri Jan 21 2022 (3 days ago) Merge pull request #2 from bgoonz/master @@ -315,7 +318,7 @@ hi c3c681777 by Bryan Guner , Fri Jan 21 2022 (3 days ago) 364 files changed, 1209 insertions(+), 1209 deletions(-) -Merge branch 'master' of https://github.com/bgoonz/BGOONZ_BLOG_2.0 +Merge branch 'master' of a41090f64 by Bryan Guner , Fri Jan 21 2022 (3 days ago) main-projects.md: added @@ -326,7 +329,7 @@ bash-intro.md: added 5aae32300 by Stackbit Code Editor , Fri Jan 21 2022 (3 days ago) 1 file changed, 0 insertions(+), 0 deletions(-) -Merge branch 'preview' of https://github.com/bgoonz/BGOONZ_BLOG_2.0 into preview +Merge branch 'preview' of into preview db9888093 by Bryan Guner , Fri Jan 21 2022 (3 days ago) .env: removed @@ -625,7 +628,7 @@ jamstack.md: added 1fa357f64 by Bryan Guner , Fri Jan 21 2022 (4 days ago) 1 file changed, 20 insertions(+) -index.md: Multiple updates: _ updated actions in grid_items _ updated type in actions _ updated label in actions _ updated url in actions \* updated style in actions +index.md: Multiple updates: _updated actions in grid_items_ updated type in actions _updated label in actions_ updated url in actions \* updated style in actions 39539d581 by Bryan Guner , Fri Jan 21 2022 (4 days ago) 1 file changed, 6 deletions(-) @@ -888,13 +891,13 @@ hi 4172ce972 by bgoonz , Mon Jan 17 2022 (7 days ago) 2 files changed, 25074 insertions(+), 27 deletions(-) -Merge branch 'master' of https://github.com/bgoonz/BGOONZ_BLOG_2.0 +Merge branch 'master' of 937e49815 by Bryan Guner , Mon Jan 17 2022 (7 days ago) Merge remote-tracking branch 'origin/preview' 93d277a41 by Stackbit , Sun Jan 16 2022 (8 days ago) -Merge branch 'preview' of https://github.com/bgoonz/BGOONZ_BLOG_2.0 +Merge branch 'preview' of 13e53a3bc by Bryan Guner , Mon Jan 17 2022 (7 days ago) scrap.md: changed @@ -1107,277 +1110,269 @@ Merge pull request #1478 from bgoonz/preview ··· - - -
- - - -
--- + + April-4-2022-stable + - April-4-2022-stable - ## What's Changed -* Merge pull request #1432 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1433 -* Preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1434 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1436 -* async-js by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1437 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1438 -* Merge pull request by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1439 -* Merge pull request by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1441 -* Merge pull request by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1442 -* Merge pull request #1442 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1443 -* cs-basics-in-js.md: added by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1444 -* Merge pull request #1444 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1445 -* _docs.scss: changed by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1446 -* STABLE---FIXED-DOCS_FORMATTINGMerge pull request #1446 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1447 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1448 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1449 -* _reset.scss: changed by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1450 -* Merge pull request #1450 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1451 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1452 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1453 -* Merge pull request by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1454 -* Merge pull request #1454 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1455 -* Merge pull request #1455 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1456 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1457 -* hi by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1458 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1459 -* hi by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1460 -* Add files via upload by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1461 -* hi by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1462 -* Update _general.scss by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1463 -* index.md: changed by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1464 -* Merge pull request #1464 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1465 -* _general.scss: changed by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1466 -* Merge pull request #1466 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1467 -* portfolio-91689538.jpg: added by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1468 -* _general.scss: changed by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1469 -* Merge pull request by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1470 -* _posts.scss: changed by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1471 -* Merge pull request #1471 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1472 -* Create python-quiz.md by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1473 -* Merge pull request by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1474 -* Merge pull request #1474 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1475 -* Merge pull request by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1476 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1639 -* Merge pull request #1639 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1640 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1641 -* Merge pull request by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1643 -* Restyle -update by @restyled-io in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1642 -* Revert "Merge pull request #1574 from bgoonz/master" by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1653 -* Restyled by clang-format by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1654 -* Merge pull request #1654 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1655 -* Merge pull request #1655 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1656 -* Bump url-parse from 1.4.3 to 1.5.7 in /notes/future-implementations/gatsby-plugin-algolia/example by @dependabot in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1650 -* Bump url-parse by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1659 -* Update _general.scss by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1657 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1661 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1663 -* Merge pull request by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1664 -* Merge pull request #1664 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1665 -* Add .circleci/config.yml by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1660 -* Add .circleci/config.yml by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1666 -* Create BGOONZ_BLOG_2.0.git by @ladykraken in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1652 -* 1a7db48b5f17639cbacd645504b3afd5fd2e170f by @ladykraken in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1651 -* BGOONZ_BLOG_2.0/.github/workflows/makefile.yml by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1667 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1668 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1670 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1671 -* Merge pull request by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1672 -* Merge pull request #1672 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1673 -* Bump marked from 0.6.1 to 4.0.10 by @dependabot in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1674 -* Bump marked from 0.6.1 to 4.0.10 by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1681 -* Merge pull request#1673from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1682 -* Merge pull request#1682from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1683 -* Restyle Merge pull request#1682from bgoonz/preview by @restyled-io in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1684 -* Restyled by whitespace by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1686 -* Restyle Restyled by whitespace by @restyled-io in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1687 -* Configure Sider by @sider in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1685 -* Merge pull request#1683from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1690 -* pleaseeeee by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1692 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1693 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1694 -* Restyle Merge pull request#1683from bgoonz/master by @restyled-io in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1691 -* Restyled by autopep8 by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1695 -* Merge pull request #1695 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1696 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1697 -* Merge pull request#1697from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1698 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1700 -* Preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1701 -* 446 by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1702 -* Merge pull request #1702 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1703 -* Merge pull request #1703 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1704 -* img by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1705 -* Merge pull request #1705 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1706 -* Merge pull request#1705from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1707 -* overwriting with better lost history by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1711 -* Merge pull request #1711 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1712 -* Merge pull request #1712 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1713 -* Merge pull request #1713 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1714 -* Delete _docs.scss by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1715 -* y by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1716 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1719 -* Merge pull request #1716 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1717 -* Merge pull request #1717 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1720 -* Delete lint.yml by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1721 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1722 -* Merge pull request #1722 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1724 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1725 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1726 -* Merge pull request#1725from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1727 -* Merge pull request#1727from bgoonz/preview removed unused code like algolia search by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1728 -* Merge pull request #1728 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1729 -* Merge pull request #1729 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1730 -* Update README.md by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1731 -* jamstack.md: added by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1733 -* Restyle jamstack.md: added by @restyled-io in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1734 -* Merge pull request #1733 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1735 -* url.md: added by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1736 -* Merge pull request #1736 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1738 -* Restyle url.md: added by @restyled-io in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1737 -* Restyled by prettier-markdown by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1739 -* Merge pull request #1739 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1741 -* Merge pull request#1741from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1743 -* markdown correcctions by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1745 -* Restyle markdown correcctions by @restyled-io in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1746 -* Restyled by prettier-markdown by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1747 -* js files by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1748 -* logo-final-touchup.PNG: added by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1749 -* Merge pull request #1749 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1750 -* moved gists by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1752 -* build(deps): bump axios from 0.16.2 to 0.21.2 by @dependabot in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1751 -* build(deps): bump axios from 0.16.2 to 0.21.2 by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1753 -* Merge pull request#1750from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1754 -* Merge pull request #1754 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1756 -* styling by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1757 -* leetcode by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1759 -* Merge remote-tracking branch 'origin/preview' by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1760 -* update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1761 -* Merge pull request #1761 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1763 -* Merge pull request #1763 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1764 -* pull by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1765 -* pull by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1766 -* formatting by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1767 -* package-lock.json deleted by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1769 -* _general.scss: changed by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1770 -* scss by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1771 -* inital stable commit by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1772 -* Merge remote-tracking branch 'origin/preview' by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1773 -* iframe fixes by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1774 -* formatting and connect table by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1775 -* accessibility.md: added by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1777 -* Merge pull request #1777 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1779 -* Restyle accessibility.md: added by @restyled-io in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1778 -* hi by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1780 -* Restyled by prettier-markdown by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1781 -* Merge pull request #1781 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1782 -* sitemap by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1784 -* hi by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1786 -* Add files via upload by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1787 -* Merge pull request#1782from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1789 -* Merge pull request #1789 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1790 -* Merge pull request#1790from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1791 -* Merge pull request #1791 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1792 -* Merge pull request #1792 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1793 -* Merge pull request #1793 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1795 -* Restyle Merge pull request#1790from bgoonz/master by @restyled-io in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1794 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1796 -* Restyled by clang-format by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1797 -* Restyle -update by @restyled-io in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1798 -* Restyled by prettier-markdown by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1799 -* Delete package-lock.json by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1800 -* Create label.yml by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1801 -* Restyle Restyled by clang-format by @restyled-io in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1802 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1803 -* Merge pull request #1803 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1804 -* Merge pull request #1804 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1805 -* removed prototype from titles by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1806 -* removed prototype from titles by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1807 -* removed prototype from titles by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1808 -* mdn by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1809 -* Restyle mdn by @restyled-io in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1810 -* Restyled by prettier-markdown by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1811 -* Merge remote-tracking branch 'origin/preview' by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1812 -* hi by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1813 -* hi by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1815 -* hi by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1816 -* Merge pull request#1811from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1817 -* Restyle Merge pull request#1811from bgoonz/master by @restyled-io in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1818 -* Merge pull request #1817 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1819 -* formatting by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1820 -* Merge pull request #1820 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1821 -* Merge pull request #1821 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1822 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1823 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1826 -* Merge pull request #1826 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1827 -* Merge pull request #1827 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1828 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1829 -* -update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1832 -* update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1833 -* update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1834 -* Merge pull request#1828from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1836 -* Restyle update by @restyled-io in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1835 -* Restyled by jq by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1837 -* deleted script by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1838 -* Merge pull request#1837from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1839 -* Merge pull request #1839 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1840 -* Merge pull request #1840 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1841 -* docs by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1842 -* Update README.md by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1843 -* Merge pull request#1842from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1844 -* organized imports by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1845 -* update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1846 -* Merge pull request#1845from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1847 -* initial components by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1848 -* hi by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1850 -* Merge pull request #1848 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1849 -* de by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1852 -* update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1853 -* Merge pull request#1852from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1854 -* hi dad by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1855 -* ds-algo by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1856 -* hi by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1857 -* Merge pull request#1855from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1858 -* git-banner.png by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1860 -* Merge pull request #1860 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1861 -* Merge pull request#1861from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1862 -* Merge pull request #1862 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1863 -* hi by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1865 -* Merge pull request #1863 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1864 -* Merge pull request#1864from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1866 -* hi by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1867 -* formatting by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1869 -* Merge pull request#1866from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1868 -* Merge pull request #1868 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1871 -* update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1872 -* update by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1873 -* Merge pull request#1871from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1874 -* Merge pull request #1874 from bgoonz/preview by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1875 -* Merge pull request #1875 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1876 -* styling by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1877 -* hi by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1879 -* Merge pull request #1879 from bgoonz/master by @bgoonz in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1880 + +* Merge pull request #1432 from bgoonz/preview by @bgoonz in +* Preview by @bgoonz in +* -update by @bgoonz in +* async-js by @bgoonz in +* -update by @bgoonz in +* Merge pull request by @bgoonz in +* Merge pull request by @bgoonz in +* Merge pull request by @bgoonz in +* Merge pull request #1442 from bgoonz/preview by @bgoonz in +* cs-basics-in-js.md: added by @bgoonz in +* Merge pull request #1444 from bgoonz/preview by @bgoonz in +* _docs.scss: changed by @bgoonz in +* STABLE---FIXED-DOCS_FORMATTINGMerge pull request #1446 from bgoonz/preview by @bgoonz in +* -update by @bgoonz in +* -update by @bgoonz in +* _reset.scss: changed by @bgoonz in +* Merge pull request #1450 from bgoonz/preview by @bgoonz in +* -update by @bgoonz in +* -update by @bgoonz in +* Merge pull request by @bgoonz in +* Merge pull request #1454 from bgoonz/preview by @bgoonz in +* Merge pull request #1455 from bgoonz/master by @bgoonz in +* -update by @bgoonz in +* hi by @bgoonz in +* -update by @bgoonz in +* hi by @bgoonz in +* Add files via upload by @bgoonz in +* hi by @bgoonz in +* Update _general.scss by @bgoonz in +* index.md: changed by @bgoonz in +* Merge pull request #1464 from bgoonz/preview by @bgoonz in +* _general.scss: changed by @bgoonz in +* Merge pull request #1466 from bgoonz/preview by @bgoonz in +* portfolio-91689538.jpg: added by @bgoonz in +* _general.scss: changed by @bgoonz in +* Merge pull request by @bgoonz in +* _posts.scss: changed by @bgoonz in +* Merge pull request #1471 from bgoonz/preview by @bgoonz in +* Create python-quiz.md by @bgoonz in +* Merge pull request by @bgoonz in +* Merge pull request #1474 from bgoonz/preview by @bgoonz in +* Merge pull request by @bgoonz in +* -update by @bgoonz in +* Merge pull request #1639 from bgoonz/master by @bgoonz in +* -update by @bgoonz in +* Merge pull request by @bgoonz in +* Restyle -update by @restyled-io in +* Revert "Merge pull request #1574 from bgoonz/master" by @bgoonz in +* Restyled by clang-format by @bgoonz in +* Merge pull request #1654 from bgoonz/master by @bgoonz in +* Merge pull request #1655 from bgoonz/preview by @bgoonz in +* Bump url-parse from 1.4.3 to 1.5.7 in /notes/future-implementations/gatsby-plugin-algolia/example by @dependabot in +* Bump url-parse by @bgoonz in +* Update _general.scss by @bgoonz in +* -update by @bgoonz in +* -update by @bgoonz in +* Merge pull request by @bgoonz in +* Merge pull request #1664 from bgoonz/preview by @bgoonz in +* Add .circleci/config.yml by @bgoonz in +* Add .circleci/config.yml by @bgoonz in +* Create BGOONZ_BLOG_2.0.git by @ladykraken in +* 1a7db48b5f17639cbacd645504b3afd5fd2e170f by @ladykraken in +* BGOONZ_BLOG_2.0/.github/workflows/makefile.yml by @bgoonz in +* -update by @bgoonz in +* -update by @bgoonz in +* -update by @bgoonz in +* Merge pull request by @bgoonz in +* Merge pull request #1672 from bgoonz/preview by @bgoonz in +* Bump marked from 0.6.1 to 4.0.10 by @dependabot in +* Bump marked from 0.6.1 to 4.0.10 by @bgoonz in +* Merge pull request#1673from bgoonz/master by @bgoonz in +* Merge pull request#1682from bgoonz/preview by @bgoonz in +* Restyle Merge pull request#1682from bgoonz/preview by @restyled-io in +* Restyled by whitespace by @bgoonz in +* Restyle Restyled by whitespace by @restyled-io in +* Configure Sider by @sider in +* Merge pull request#1683from bgoonz/master by @bgoonz in +* pleaseeeee by @bgoonz in +* -update by @bgoonz in +* -update by @bgoonz in +* Restyle Merge pull request#1683from bgoonz/master by @restyled-io in +* Restyled by autopep8 by @bgoonz in +* Merge pull request #1695 from bgoonz/preview by @bgoonz in +* -update by @bgoonz in +* Merge pull request#1697from bgoonz/preview by @bgoonz in +* -update by @bgoonz in +* Preview by @bgoonz in +* 446 by @bgoonz in +* Merge pull request #1702 from bgoonz/master by @bgoonz in +* Merge pull request #1703 from bgoonz/preview by @bgoonz in +* img by @bgoonz in +* Merge pull request #1705 from bgoonz/master by @bgoonz in +* Merge pull request#1705from bgoonz/master by @bgoonz in +* overwriting with better lost history by @bgoonz in +* Merge pull request #1711 from bgoonz/master by @bgoonz in +* Merge pull request #1712 from bgoonz/preview by @bgoonz in +* Merge pull request #1713 from bgoonz/master by @bgoonz in +* Delete _docs.scss by @bgoonz in +* y by @bgoonz in +* -update by @bgoonz in +* Merge pull request #1716 from bgoonz/master by @bgoonz in +* Merge pull request #1717 from bgoonz/preview by @bgoonz in +* Delete lint.yml by @bgoonz in +* -update by @bgoonz in +* Merge pull request #1722 from bgoonz/master by @bgoonz in +* -update by @bgoonz in +* -update by @bgoonz in +* Merge pull request#1725from bgoonz/master by @bgoonz in +* Merge pull request#1727from bgoonz/preview removed unused code like algolia search by @bgoonz in +* Merge pull request #1728 from bgoonz/master by @bgoonz in +* Merge pull request #1729 from bgoonz/preview by @bgoonz in +* Update README.md by @bgoonz in +* jamstack.md: added by @bgoonz in +* Restyle jamstack.md: added by @restyled-io in +* Merge pull request #1733 from bgoonz/preview by @bgoonz in +* url.md: added by @bgoonz in +* Merge pull request #1736 from bgoonz/preview by @bgoonz in +* Restyle url.md: added by @restyled-io in +* Restyled by prettier-markdown by @bgoonz in +* Merge pull request #1739 from bgoonz/preview by @bgoonz in +* Merge pull request#1741from bgoonz/master by @bgoonz in +* markdown correcctions by @bgoonz in +* Restyle markdown correcctions by @restyled-io in +* Restyled by prettier-markdown by @bgoonz in +* js files by @bgoonz in +* logo-final-touchup.PNG: added by @bgoonz in +* Merge pull request #1749 from bgoonz/preview by @bgoonz in +* moved gists by @bgoonz in +* build(deps): bump axios from 0.16.2 to 0.21.2 by @dependabot in +* build(deps): bump axios from 0.16.2 to 0.21.2 by @bgoonz in +* Merge pull request#1750from bgoonz/master by @bgoonz in +* Merge pull request #1754 from bgoonz/preview by @bgoonz in +* styling by @bgoonz in +* leetcode by @bgoonz in +* Merge remote-tracking branch 'origin/preview' by @bgoonz in +* update by @bgoonz in +* Merge pull request #1761 from bgoonz/master by @bgoonz in +* Merge pull request #1763 from bgoonz/preview by @bgoonz in +* pull by @bgoonz in +* pull by @bgoonz in +* formatting by @bgoonz in +* package-lock.json deleted by @bgoonz in +* _general.scss: changed by @bgoonz in +* scss by @bgoonz in +* inital stable commit by @bgoonz in +* Merge remote-tracking branch 'origin/preview' by @bgoonz in +* iframe fixes by @bgoonz in +* formatting and connect table by @bgoonz in +* accessibility.md: added by @bgoonz in +* Merge pull request #1777 from bgoonz/preview by @bgoonz in +* Restyle accessibility.md: added by @restyled-io in +* hi by @bgoonz in +* Restyled by prettier-markdown by @bgoonz in +* Merge pull request #1781 from bgoonz/preview by @bgoonz in +* sitemap by @bgoonz in +* hi by @bgoonz in +* Add files via upload by @bgoonz in +* Merge pull request#1782from bgoonz/master by @bgoonz in +* Merge pull request #1789 from bgoonz/preview by @bgoonz in +* Merge pull request#1790from bgoonz/master by @bgoonz in +* Merge pull request #1791 from bgoonz/preview by @bgoonz in +* Merge pull request #1792 from bgoonz/master by @bgoonz in +* Merge pull request #1793 from bgoonz/preview by @bgoonz in +* Restyle Merge pull request#1790from bgoonz/master by @restyled-io in +* -update by @bgoonz in +* Restyled by clang-format by @bgoonz in +* Restyle -update by @restyled-io in +* Restyled by prettier-markdown by @bgoonz in +* Delete package-lock.json by @bgoonz in +* Create label.yml by @bgoonz in +* Restyle Restyled by clang-format by @restyled-io in +* -update by @bgoonz in +* Merge pull request #1803 from bgoonz/master by @bgoonz in +* Merge pull request #1804 from bgoonz/preview by @bgoonz in +* removed prototype from titles by @bgoonz in +* removed prototype from titles by @bgoonz in +* removed prototype from titles by @bgoonz in +* mdn by @bgoonz in +* Restyle mdn by @restyled-io in +* Restyled by prettier-markdown by @bgoonz in +* Merge remote-tracking branch 'origin/preview' by @bgoonz in +* hi by @bgoonz in +* hi by @bgoonz in +* hi by @bgoonz in +* Merge pull request#1811from bgoonz/master by @bgoonz in +* Restyle Merge pull request#1811from bgoonz/master by @restyled-io in +* Merge pull request #1817 from bgoonz/preview by @bgoonz in +* formatting by @bgoonz in +* Merge pull request #1820 from bgoonz/master by @bgoonz in +* Merge pull request #1821 from bgoonz/preview by @bgoonz in +* -update by @bgoonz in +* -update by @bgoonz in +* Merge pull request #1826 from bgoonz/master by @bgoonz in +* Merge pull request #1827 from bgoonz/preview by @bgoonz in +* -update by @bgoonz in +* -update by @bgoonz in +* update by @bgoonz in +* update by @bgoonz in +* Merge pull request#1828from bgoonz/master by @bgoonz in +* Restyle update by @restyled-io in +* Restyled by jq by @bgoonz in +* deleted script by @bgoonz in +* Merge pull request#1837from bgoonz/master by @bgoonz in +* Merge pull request #1839 from bgoonz/preview by @bgoonz in +* Merge pull request #1840 from bgoonz/master by @bgoonz in +* docs by @bgoonz in +* Update README.md by @bgoonz in +* Merge pull request#1842from bgoonz/master by @bgoonz in +* organized imports by @bgoonz in +* update by @bgoonz in +* Merge pull request#1845from bgoonz/master by @bgoonz in +* initial components by @bgoonz in +* hi by @bgoonz in +* Merge pull request #1848 from bgoonz/master by @bgoonz in +* de by @bgoonz in +* update by @bgoonz in +* Merge pull request#1852from bgoonz/master by @bgoonz in +* hi dad by @bgoonz in +* ds-algo by @bgoonz in +* hi by @bgoonz in +* Merge pull request#1855from bgoonz/master by @bgoonz in +* git-banner.png by @bgoonz in +* Merge pull request #1860 from bgoonz/preview by @bgoonz in +* Merge pull request#1861from bgoonz/master by @bgoonz in +* Merge pull request #1862 from bgoonz/preview by @bgoonz in +* hi by @bgoonz in +* Merge pull request #1863 from bgoonz/master by @bgoonz in +* Merge pull request#1864from bgoonz/preview by @bgoonz in +* hi by @bgoonz in +* formatting by @bgoonz in +* Merge pull request#1866from bgoonz/master by @bgoonz in +* Merge pull request #1868 from bgoonz/preview by @bgoonz in +* update by @bgoonz in +* update by @bgoonz in +* Merge pull request#1871from bgoonz/master by @bgoonz in +* Merge pull request #1874 from bgoonz/preview by @bgoonz in +* Merge pull request #1875 from bgoonz/master by @bgoonz in +* styling by @bgoonz in +* hi by @bgoonz in +* Merge pull request #1879 from bgoonz/master by @bgoonz in ## New Contributors -* @dependabot made their first contribution in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1650 -* @ladykraken made their first contribution in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1652 -* @sider made their first contribution in https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1685 -**Full Changelog**: https://github.com/bgoonz/BGOONZ_BLOG_2.0/compare/download...2022 +* @dependabot made their first contribution in +* @ladykraken made their first contribution in +* @sider made their first contribution in -
+**Full Changelog**: +
--- - - - diff --git a/README.md b/README.md index ec86fc5869..f36a7c20fb 100644 --- a/README.md +++ b/README.md @@ -1,53 +1,30 @@ -
+# Bgoonz Blog Readme -# [⇨WEBSITE🗺️⇦](https://bgoonz-blog.netlify.app/) - +### [⇨WEBSITE🗺️⇦](https://bgoonz-blog.netlify.app) -### [Github Org Link](https://github.com/BGOOONZ-BLOG/) - -
- ---- - -<<<<<<< HEAD - -======= ### [CHANGELOG](./CHANGELOG.md) ->>>>>>> master - - - -
-##### [Cloudfare-Backup](https://bgoonz-blog-2-0.pages.dev/) ⇨ [search](https://www.algolia.com/realtime-search-demo/web-dev-resource-hub-9e6b8aa8-6106-44c5-9f59-ff3f9531abd4) ⇨ [Backup Repo Deploy](https://bgoonzblog20-backup.netlify.app/#gsc.tab=0) ⇨ [Github pages](https://bgoonz.github.io/BGOONZ_BLOG_2.0/) ⇨ [Go To Site Wiki](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki) ⇨ [Gatsby Cloud Version](https://bgoonzblog20master.gatsbyjs.io/) +##### [⇨WEBSITE🗺️⇦](https://bgoonz-blog.netlify.app) [⇨**Cloudfare-Backup**⇦](https://bgoonz-blog-2-0.pages.dev/) [⇨**search**⇦](https://www.algolia.com/realtime-search-demo/web-dev-resource-hub-9e6b8aa8-6106-44c5-9f59-ff3f9531abd4) [⇨**Backup Repo Deploy**⇦](https://bgoonzblog20-backup.netlify.app/#gsc.tab=0) [⇨**Github pages**⇦](https://bgoonz.github.io/BGOONZ_BLOG_2.0/) [⇨**Go To Site Wiki**⇦](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki) [⇨**Gatsby Cloud Version**⇦](https://bgoonzblog20master.gatsbyjs.io/) [⇨**Vercel Version**⇦](https://bgoonz-blog-2-0.vercel.app/) [⇨**Cloudfare-Domain**⇦](www.webdevhub.us) [⇨**gh-pages**⇦](https://bgoonz.github.io/BGOONZ_BLOG_2.0/) [⇨**backup netlify deploy**⇦](https://bgoonz-blog20-backup.netlify.app/) +##### [⇨WEBSITE🗺️⇦](https://bgoonz-blog.netlify.app) [⇨**Cloudfare-Backup**⇦](https://bgoonz-blog-2-0.pages.dev/) [⇨**search**⇦](https://www.algolia.com/realtime-search-demo/web-dev-resource-hub-9e6b8aa8-6106-44c5-9f59-ff3f9531abd4) [⇨**Backup Repo Deploy**⇦](https://bgoonzblog20-backup.netlify.app/#gsc.tab=0) [⇨**Github pages**⇦](https://bgoonz.github.io/BGOONZ_BLOG_2.0/) [⇨**Go To Site Wiki**⇦](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki) [⇨**Gatsby Cloud Version**⇦](https://bgoonzblog20master.gatsbyjs.io/) [⇨**Vercel Version**⇦](https://bgoonz-blog-2-0.vercel.app/) [⇨**Cloudfare-Domain**⇦](www.webdevhub.us) [⇨**gh-pages**⇦](https://bgoonz.github.io/BGOONZ_BLOG_2.0/) [⇨**backup netlify deploy**⇦](https://bgoonz-blog20-backup.netlify.app/) -###### [⇨Privacy policy⇦](https://codepen.io/bgoonz/pen/LYLJZrW) +### Repos +### Repos -###### [⇨ Changes ⇦](https://visualping.io/jobs/3577650) +[Alt Backup](https://github.com/BGOOONZ-BLOG/bgoonz-blog2.0-v-5) +[Blog Content](https://github.com/bgoonz/MainBlogContent) -
-
+#### [⇨Privacy policy⇦](https://codepen.io/bgoonz/pen/LYLJZrW) [![Netlify Status](https://api.netlify.com/api/v1/badges/a1b7ee1a-11a7-4bd2-a341-2260656e216f/deploy-status)](https://app.netlify.com/sites/bgoonz-blog/deploys)[![CodeFactor](https://www.codefactor.io/repository/github/bgoonz/bgoonz_blog_2.0/badge)](https://www.codefactor.io/repository/github/bgoonz/bgoonz_blog_2.0) + ![GitHub visitors](https://visitor-badge-reloaded.herokuapp.com/badge?page_id=bgoonz.visitor.badge.reloaded&color=00bbbb&style=for-the-badge&logo=github) + [![Deploy Gatsby site to Pages](https://github.com/DUKE42web/BGOONZ_BLOG_2.0/actions/workflows/pa7ges.yml/badge.svg?branch=master&event=deployment)](https://github.com/DUKE42web/BGOONZ_BLOG_2.0/actions/workflows/pa7ges.yml) -[![Lint Code Base](https://github.com/bgoonz/BGOONZ_BLOG_2.0/actions/workflows/super-linter.yml/badge.svg)](https://github.com/bgoonz/BGOONZ_BLOG_2.0/actions/workflows/super-linter.yml) [![Deploy Gatsby site to Pages](https://github.com/bgoonz/BGOONZ_BLOG_2.0/actions/workflows/pages.yml/badge.svg)](https://github.com/bgoonz/BGOONZ_BLOG_2.0/actions/workflows/pages.yml) --- -<<<<<<< HEAD -![preview](https://github.com/bgoonz/BGOONZ_BLOG_2.0/blob/master/static/images/blog-preview.png?raw=true) - - - ---- - -![Foo](https://github.com/bgoonz/BGOONZ_BLOG_2.0/blob/master/static/images/Screenshot%202022-03-30%20at%2012-37-24%20Website%20Speed%20Test%20Tool%20-%20Testmysite.io%20by%20Netlify.png?raw=true) - -
-======= #### Branch Deploys ##### [Preview](https://preview--bgoonz-blog.netlify.app/) @@ -78,26 +55,12 @@ docky src/components/**/*.js --watch "src/components/**/*.js","./README.md" - - [⇨WEBSITE🗺️⇦ ⇨**Cloudfare-Backup**⇦ ⇨**search**⇦ ⇨**Backup Repo Deploy**⇦ ⇨**Github pages**⇦ ⇨**Go To Site Wiki**⇦ ⇨**Gatsby Cloud Version**⇦ ⇨**Vercel Version**⇦ ⇨**Cloudfare-Domain**⇦ ⇨**gh-pages**⇦ ⇨**backup netlify deploy**⇦](#website️-cloudfare-backup-search-backup-repo-deploy-github-pages-go-to-site-wiki-gatsby-cloud-version-vercel-version-cloudfare-domain-gh-pages-backup-netlify-deploy) - [Repos](#repos) - [⇨Privacy policy⇦](#privacy-policy) - - [](#) - - [Branch Deploys](#branch-deploys) - - [Preview](#preview) - - [local](#local) - - [](#-1) - - [](#-2) - - [](#-3) - - [](#-4) - - [](#-5) - - [](#-6) - [Table Of Contents](#table-of-contents) - - [](#-7) - [Useful Commands (internal use)](#useful-commands-internal-use) - - [Stable Points](#stable-points) - - [Links To Remember:](#links-to-remember) - [Web Dev Setup](#web-dev-setup) - [Basic Web Development Environment Setup](#basic-web-development-environment-setup) - [Basic Web Development Environment Setup](#basic-web-development-environment-setup-1) - [Windows Subsystem for Linux (WSL) and Ubuntu](#windows-subsystem-for-linux-wsl-and-ubuntu) - - [Test if you have Ubuntu installed by typing "Ubuntu" in the search box in the bottom app bar that reads "Type here to search". If you see a search result that reads **"Ubuntu 20.04 LTS"** with "App" under it, then you have it installed.](#test-if-you-have-ubuntu-installed-by-typing-ubuntu-in-the-search-box-in-the-bottom-app-bar-that-reads-type-here-to-search-if-you-see-a-search-result-that-reads-ubuntu-2004-lts-with-app-under-it-then-you-have-it-installed) - [Git](#git) - [Google Chrome](#google-chrome) - [Node.js](#nodejs) @@ -105,10 +68,7 @@ docky src/components/**/*.js --watch "src/components/**/*.js","./README.md" - - [Python 3](#python-3) - [Note about WSL](#note-about-wsl) - [Some other common instillations](#some-other-common-instillations) - - [](#-8) - - [Documentation Commands:](#documentation-commands) - - [documentation build src/components/ActionLink.js -f md\> ./notes/ActionLink.md](#documentation-build-srccomponentsactionlinkjs---f-md-notesactionlinkmd) - - [Blog Content:](#blog-content) + - [Blog Content](#blog-content) - [Bash Cheat Sheet (MY COMMANDS)](#bash-cheat-sheet-my-commands) - [1. Remove spaces from file and folder names and then remove numbers from files and folder names](#1-remove-spaces-from-file-and-folder-names-and-then-remove-numbers-from-files-and-folder-names) - [Description: need to : `sudo apt install rename`](#description-need-to--sudo-apt-install-rename) @@ -252,7 +212,6 @@ docky src/components/**/*.js --watch "src/components/**/*.js","./README.md" - - [Description](#description-28) - [code](#code-45) - [96. URL To Subscribe To YouTube Channel](#96-url-to-subscribe-to-youtube-channel) - - [| JavaScript libraries | Lodash ; Dojo ; core-js ; jQuery |](#-javascript-libraries--lodash--dojo--core-js--jquery-------------------------) - [96. URL To Subscribe To YouTube Channel](#96-url-to-subscribe-to-youtube-channel-1) - [Description](#description-29) - [code](#code-46) @@ -281,20 +240,15 @@ docky src/components/**/*.js --watch "src/components/**/*.js","./README.md" - - [To search all files who are not in .git directory](#to-search-all-files-who-are-not-in-git-directory) - [To find all files that have the same node (hard link) as MY\_FILE\_HERE](#to-find-all-files-that-have-the-same-node-hard-link-as-my_file_here) - [To find all files in the current directory and modify their permissions](#to-find-all-files-in-the-current-directory-and-modify-their-permissions) - - [find . -type f -exec chmod 644 {} ;](#find---type-f--exec-chmod-644--) - - [](#-9) - [Wiki Nav](#wiki-nav) - [Dependencies](#dependencies) - - [](#-10) - [Docs Structure](#docs-structure) - [SITEMAP](#sitemap) - - [](#-11) -- [](#-12) +- [](#) - [🚀 Quick start](#-quick-start) - [🧐 What's inside?](#-whats-inside) - [🎓 Learning Gatsby](#-learning-gatsby) - [💫 Deploy](#-deploy) - - [](#-13) - [Gatsby With Netlify CMS](#gatsby-with-netlify-cms) - [Prerequisites](#prerequisites) - [Set up a Netlify CMS-managed Gatsby site in 5 steps](#set-up-a-netlify-cms-managed-gatsby-site-in-5-steps) @@ -307,11 +261,9 @@ docky src/components/**/*.js --watch "src/components/**/*.js","./README.md" - - [Benefits of Netlify CMS, GitHub, and Netlify Workflow](#benefits-of-netlify-cms-github-and-netlify-workflow) - [You can learn more about Netlify CMS and how to configure it further in the Netlify CMS documentation](#you-can-learn-more-about-netlify-cms-and-how-to-configure-it-further-in-the-netlify-cms-documentation) - [Gatsby Project Structure | Gatsby](#gatsby-project-structure--gatsby) - - [The file/folder structure described above reflects Gatsby-specific files and folders. Since Gatsby sites are also React apps, it's common to use standard React code organization patterns such as folders like `/components` and `/utils` inside `/src`. The React docs have more information on a typical React app folder structure.](#the-filefolder-structure-described-above-reflects-gatsby-specific-files-and-folders-since-gatsby-sites-are-also-react-apps-its-common-to-use-standard-react-code-organization-patterns-such-as-folders-like-components-and-utils-inside-src-the-react-docs-have-more-information-on-a-typical-react-app-folder-structure) - [Layout Components | Gatsby](#layout-components--gatsby) - [Excerpt](#excerpt) - [Adding Markdown Pages | Gatsby](#adding-markdown-pages--gatsby) - - [](#-14) - [Overview](#overview) - [Syntax](#syntax) - [Parameters](#parameters) @@ -320,7 +272,6 @@ docky src/components/**/*.js --watch "src/components/**/*.js","./README.md" - - [Explanation](#explanation) - [Output](#output) - [Technoloy](#technoloy) - - [](#-15) - [SOURCECODE](#sourcecode) - [Overview](#overview-1) - [Syntax](#syntax-1) @@ -340,188 +291,57 @@ docky src/components/**/*.js --watch "src/components/**/*.js","./README.md" - - [Parameters](#parameters-4) - [Examples](#examples) +--- + ![preview](https://github.com/bgoonz/BGOONZ_BLOG_2.0/blob/master/static/images/blog-may-2022.png?raw=true) + --- ## Useful Commands (internal use) ```bash + npm i @stackbit/gatsby-plugin-menus babel-runtime chokidar classnames fs-extra gatsby gatsby-image gatsby-plugin-netlify gatsby-plugin-netlify-cms gatsby-plugin-sass gatsby-plugin-react-helmet gatsby-plugin-typescript --legacy-peer-deps + + git checkout 307a5cd # check out the commit that you want to reset to git checkout -b fixy # create a branch named fixy to do the work git merge -s ours master # merge master's history without changing any files git checkout master # switch back to master git merge fixy # and merge in the fixed branch git push # done, no need to force push! -``` - ---- - -## Stable Points - -- [stable 8-13-2021](https://github.com/bgoonz/BGOONZ_BLOG_2.0/commit/0c09a707f4bfddd974a31d97a4f8d716f1858ef8) or [or maybe](https://github.com/bgoonz/BGOONZ_BLOG_2.0/commit/68fba78e36fffcf21288ea0e90e1075bf31b2a82) -- [Stable September 11](https://github.com/side-projects-42/BGOONZ_BLOG_2.0) -- [October Stable](https://github.com/Web-Dev-Collaborative/october-stable) -- [November 2021 stable](https://github.com/bgoonz/BGOONZ_BLOG_2.0/commit/9ae5da5813cc9b48d2a57c84cd32cf4309078524) -- [Late November Stable](https://github.com/bgoonz/BGOONZ_BLOG_2.0/commit/40ecc95f000a848710c39e166961b8da7fca306b) -- [December](https://github.com/bgoonz/BGOONZ_BLOG_2.0/tree/fc4a6ba1d61a3ef0b893cc5a44e41672547a3cc6) -- [Late December](https://github.com/bgoonz/BGOONZ_BLOG_2.0/commit/848a8505eece492bfd9856eb63bd4acbee8bced6) -- [Late Febuary](https://deploy-preview-1697--bgoonz-blog.netlify.app/) -- [Late January](https://github.com/bgoonz/BGOONZ_BLOG_2.0/pull/1447) -- [Good stable point](https://github.com/bgoonz/BGOONZ_BLOG_2.0/commit/90f70928a145c8a784899baf62efc2a0d5697bf4) -- [Stable March 13th 2022](https://github.com/bgoonz/BGOONZ_BLOG_2.0/commit/c3f30229ac3dcd19ff54798227ce065c216e0c11) -- [Stable March 13th 2022](https://github.com/bgoonz/BGOONZ_BLOG_2.0/commit/99db7b97282d7190556b2a1b1ac61d6d9c67f970) -[netlify-deploy-preview](https://deploy-preview-2280--bgoonz-blog.netlify.app/docs/tools/) -- [May fix](https://github.com/bgoonz/BGOONZ_BLOG_2.0/commit/736d38cdcdd3692d6a3bf1d5485ac2b0a3824d02) - -- [Syntax hilighting working most recent](https://github.com/bgoonz/BGOONZ_BLOG_2.0/tree/db4d36067c1483c079389f1bd0e456c473c56710) -- [FINALLY FIXED](https://62b5863dd06870000889c5cf--bgoonz-blog.netlify.app/) - -- [Good deploy early Aug](https://github.com/bgoonz/BGOONZ_BLOG_2.0/commit/a6bb13adf39305b7292a88bb1b37bb4bb2e5e76c) - ---- -### Links To Remember: - - -- [Algolia Search UI](https://www.algolia.com/interface-demos/6ed0c3de-f9e4-4cc8-a7b2-c6c7c979cc5e) -- [Most recent stable commit](https://github.com/bgoonz/BGOONZ_BLOG_2.0/commit/2448c20614bfef5491240d7da5b5e5873db8b586) -- [sitemap](https://www.xml-sitemaps.com/download/bgoonz-blog.netlify.app-ee43723d7/sitemap.xml?view=1) -- [initial commit](https://github.com/bgoonz/BGOONZ_BLOG_2.0/commit/e8f12effd461b560b366ee0bde5231f2c1ce0a4c) -- [Static Html Version](https://github.com/Archive-42/bgoonz-blog-static) -- [commit pages](https://github.com/bgoonz/BGOONZ_BLOG_2.0/commits/master?after=496dfce7e627bc81c80f7c0b5c41ecf420500b4a+34&branch=master) -- [alt blog contact page](https://bgoonz-blog-v3-0.netlify.app/contact/) -- [Resource Archive](https://resourcerepo2.netlify.app/) -- [starter](https://codesandbox.io/s/ecstatic-wozniak-gj31v?autoresize=1&expanddevtools=1&fontsize=12&hidenavigation=1&theme=dark) -- [Instant Search Demo](https://codesandbox.io/s/magical-davinci-l4hq6) -- [midway-commit](https://github.com/bgoonz/BGOONZ_BLOG_2.0/tree/92d88002bebcde66b47d8109222ac62c64fa9909) -- [blog2.0 backups](https://gist.github.com/bgoonz/68203bca236305d93d75e87533c7e8b8) -- [backup repo](https://github.com/bgoonz/BGOONZ_BLOG_2.0) -- [Bookmark website](https://github.com/side-projects-42/superb-celery) -- [stable stackbit](https://github.com/bgoonz/BGOONZ_BLOG_2.0/commit/69a617bbce1113e65390d90e0085be422e7f23e1) -- [repl.it for questions](https://comments-3.bgoonz.repl.co/) -- [rotate pages](https://random-static-html-deploys.netlify.app/rotate.html) -- [More widgets](https://webdevhub-1.disqus.com/) +``` +--- + +![Test My Site](https://github.com/bgoonz/BGOONZ_BLOG_2.0/blob/master/static/images/Screenshot%202022-03-30%20at%2012-37-24%20Website%20Speed%20Test%20Tool%20-%20Testmysite.io%20by%20Netlify.png?raw=true) --- ## Web Dev Setup ->>>>>>> master
-<<<<<<< HEAD - Bash Commands - -## My Commands - -## # Find - -# To find files by case-insensitive extension (ex: .jpg, .jpg, .jpG) - -find . -iname "\*.jpg" -======= Web Dev Setup ## Basic Web Development Environment Setup ->>>>>>> master - -# To find directories -<<<<<<< HEAD -find . -type d +Windows Subsystem for Linux (WSL) and Ubuntu -# To find files -======= ### Basic Web Development Environment Setup ->>>>>>> master - -find . -type f - -<<<<<<< HEAD -# To find files by octal permission - -find . -type f -perm 777 - -# To find files with setuid bit set - -find . -xdev \( -perm -4000 \) -type f -print0 | xargs -0 ls -l - -# To find files with extension '.txt' and remove them - -find ./path/ -name '\*.txt' -exec rm '{}' \; - -# To find files with extension '.txt' and look for a string into them - -find ./path/ -name '\*.txt' | xargs grep 'string' - -# To find files with size bigger than 5 Mebibyte and sort them by size - -find . -size +5M -type f -print0 | xargs -0 ls -Ssh | sort -z - -# To find files bigger than 2 Megabyte and list them - -find . -type f -size +200000000c -exec ls -lh {} \; | awk '{ print $9 ": " $5 }' - -# To find files modified more than 7 days ago and list file information - -find . -type f -mtime +7d -ls - -# To find symlinks owned by a user and list file information - -find . -type l -user -ls - -# To search for and delete empty directories - -find . -type d -empty -exec rmdir {} \; -# To search for directories named build at a max depth of 2 directories +#### Windows Subsystem for Linux (WSL) and Ubuntu -find . -maxdepth 2 -name build -type d - -# To search all files who are not in .git directory - -find . ! -iwholename '_.git_' -type f - -# To find all files that have the same node (hard link) as MY_FILE_HERE - -find . -type f -samefile MY_FILE_HERE 2> /dev/null - -# To find all files in the current directory and modify their permissions - -find . -type f -exec chmod 644 {} \; - -# 1. Remove spaces from file and folder names and then remove numbers from files and folder names - -## Description: need to : `sudo apt install rename` - -> Notes: Issue when renaming file without numbers collides with existing file name... - -## # code - -```sh -find . -name "* *" -type d | rename 's/ /_/g' -find . -name "* *" -type f | rename 's/ /_/g' -``` - -```sh - -```sh -=======
-![Web Dev Setup](https://cdn-images-1.medium.com/max/800/0*aqKP1drNHmNm34zz.jpg) - -
- -###### Test if you have Ubuntu installed by typing "Ubuntu" in the search box in the bottom app bar that reads "Type here to search". If you see a search result that reads **"Ubuntu 20.04 LTS"** with "App" under it, then you have it installed. +Test if you have Ubuntu installed by typing "Ubuntu" in the search box in the bottom app bar that reads "Type here to search". If you see a search result that reads **"Ubuntu 20.04 LTS"** with "App" under it, then you have it installed. ``` 1. In the application search box in the bottom bar, type "PowerShell" to find the application named "Windows PowerShell" 2. Right-click on "Windows PowerShell" and choose "Run as administrator" from the popup menu @@ -543,32 +363,53 @@ find . -name "* *" -type f | rename 's/ /_/g' 18. You need to upgrade your packages, so type `sudo apt upgrade` (if prompted for your password, enter it) ``` ### Git + Git comes with Ubuntu, so there's nothing to install. However, you should configure it using the following instructions. + Open an Ubuntu terminal if you don't have one open already. -1. > You need to configure Git, so type `git config --global user.name "Your Name"` with replacing "Your Name" with your real name. -2. > You need to configure Git, so type `git config --global user.email your@email.com` with replacing "your@email.com" with your real email. + +1. > You need to configure Git, so type `git config --global user.name "Your Name"` with replacing "Your Name" with your real name. +2. > You need to configure Git, so type `git config --global user.email your@email.com` with replacing "your@email.com" with your real email. + **Note: if you want git to remember your login credentials type:** +``` git config --global credential.helper store +``` ### Google Chrome + Test if you have Chrome installed by typing "Chrome" in the search box in the bottom app bar that reads "Type here to search". If you see a search result that reads "Chrome" with "App" under it, then you have it installed. Otherwise, follow these instructions to install Google Chrome. + ### Node.js + Test if you have Node.js installed by opening an Ubuntu terminal and typing `node --version`. If it reports "Command 'node' not found", then you need to follow these directions. -1. > In the Ubuntu terminal, type `sudo apt update` and press Enter -2. > In the Ubuntu terminal, type `sudo apt install build-essential` and press Enter -3. > In the Ubuntu terminal, type `curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/install.sh | bash` and press Enter -4. > In the Ubuntu terminal, type `. ./.bashrc` and press Enter -5. > In the Ubuntu terminal, type `nvm install --lts` and press Enter -6. > Confirm that **node** is installed by typing `node --version` and seeing it print something that is not "Command not found"! + +1. > In the Ubuntu terminal, type `sudo apt update` and press Enter +2. > In the Ubuntu terminal, type `sudo apt install build-essential` and press Enter +3. > In the Ubuntu terminal, type `curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/install.sh | bash` and press Enter +4. > In the Ubuntu terminal, type `. ./.bashrc` and press Enter +5. > In the Ubuntu terminal, type `nvm install --lts` and press Enter +6. > Confirm that **node** is installed by typing `node --version` and seeing it print something that is not "Command not found"! + ### Unzip + You will often have to download a zip file and unzip it. It is easier to do this from the command line. So we need to install a linux unzip utility. + In the Ubuntu terminal type: `sudo apt install unzip` and press Enter + Mocha.js + Test if you have Mocha.js installed by opening an Ubuntu terminal and typing `which mocha`. If it prints a path, then you're good. Otherwise, if it prints nothing, install Mocha.js by typing `npm install -g mocha`. + ### Python 3 + Ubuntu does not come with Python 3. Install it using the command `sudo apt install python3`. Test it by typing `python3 --version` and seeing it print a number. + ### Note about WSL + As of the time of writing of this document, WSL has an issue renaming or deleting files if Visual Studio Code is open. So before doing any linux commands which manipulate files, make sure you **close** Visual Studio Code before running those commands in the Ubuntu terminal. + ### Some other common instillations + ```bash # Installing build essentials sudo apt-get install -y build-essential libssl-dev @@ -610,361 +451,228 @@ As of the time of writing of this document, WSL has an issue renaming or deletin # FileZilla - a FTP client sudo apt-get install -y filezilla ``` +
+ --- -### Documentation Commands: -documentation build src/components/DocsMenu.js -f md> ./notes/DocsMenu.md -documentation build src/components/Footer.js -f md> ./notes/Footer.md -documentation build src/components/Header.js -f md> ./notes/Header.md -documentation build src/components/index.js -f md> ./notes/index.md -documentation build src/components/SectionContent.js -f md> ./notes/SectionContent.md -documentation build src/components/SectionDocs.js -f md> ./notes/SectionDocs.md -documentation build src/components/SectionHero.js -f md> ./notes/SectionHero.md -documentation build src/components/CtaButtons.js -f md> ./notes/CtaButtons.md -documentation build src/components/DocsSubmenu.js -f md> ./notes/DocsSubmenu.md -documentation build src/components/FormField.js -f md> ./notes/FormField.md -documentation build src/components/Icon.js -f md> ./notes/Icon.md -documentation build src/components/Layout.js -f md> ./notes/Layout.md -documentation build src/components/SectionCta.js -f md> ./notes/SectionCta.md -documentation build src/components/SectionGrid.js -f md> ./notes/SectionGrid.md -documentation build src/components/Submenu.js -f md> ./notes/Submenu.md -documentation build src/components/ActionLink.js -f md> ./notes/ActionLink.md ---- -## Blog Content: + + + --- + +## Blog Content + --- -## Bash Cheat Sheet (MY COMMANDS) -
+--- +## Bash Cheat Sheet (MY COMMANDS) +
- Bash Cheat Sheet (MY COMMANDS) + Bash Cheat Sheet (MY COMMANDS) Notes: Issue when renaming file without numbers collides with existing file name... + ###### code + ```bash find . -name "* *" -type d | rename 's/ /_/g' find . -name "* *" -type f | rename 's/ /_/g' ``` + ```bash + ```bash ->>>>>>> master find $dir -type f | sed 's|\(.*/\)[^A-Z]*\([A-Z].*\)|mv \"&\" \"\1\2\"|' | sh + find $dir -type d | sed 's|\(.*/\)[^A-Z]*\([A-Z].*\)|mv \"&\" \"\1\2\"|' | sh for i in*.html; do mv "$i" "${i%-*}.html"; done for i in*.*; do mv "$i" "${i%-*}.${i##*.}"; done --- -<<<<<<< HEAD -## Description: combine the contents of every file in the contaning directory. - -> Notes: this includes the contents of the file it's self... - -## # code: - -======= ### Description: combine the contents of every file in the contaning directory. + >Notes: this includes the contents of the file it's self... + ###### code: ->>>>>>> master ```js //APPEND-DIR.js const fs = require('fs'); let cat = require('child_process') -.execSync('cat*') + .execSync('cat *') .toString('UTF-8'); -fs.writeFile('output.md', cat, err => { +fs.writeFile('output.md', cat, err => { if (err) throw err; }); -``` ---- -<<<<<<< HEAD - -# 2. Download Website Using Wget - -## Description - -> Notes: ==> sudo apt install wget - -## ## code -```sh +``` -======= +--- ## 2. Download Website Using Wget ### Description > Notes: ==> sudo apt install wget ###### code + ```bash ->>>>>>> master wget --limit-rate=200k --no-clobber --convert-links --random-wait -r -p -E -e robots=off -U mozilla https://bootcamp42.gitbook.io/python/ -``` ---- -<<<<<<< HEAD - -# 3. Clean Out Messy Git Repo -## Description: recursively removes git related folders as well as internal use files / attributions in addition to empty folders - -> Notes: To clear up clutter in repositories that only get used on your local machine. - -## ## code - -```sh +``` -======= +--- ## 3. Clean Out Messy Git Repo ### Description: recursively removes git related folders as well as internal use files / attributions in addition to empty folders > Notes: To clear up clutter in repositories that only get used on your local machine. ###### code + ```bash ->>>>>>> master find . -empty -type d -print -delete -find . \( -name ".git" -o -name ".gitignore" -o -name ".gitmodules" -o -name ".gitattributes" \) -exec rm -rf -- {} + -find . \( -name "*SECURITY.txt" -o -name "*RELEASE.txt" -o -name "*CHANGELOG.txt" -o -name "*LICENSE.txt" -o -name "*CONTRIBUTING.txt" -name "*HISTORY.md" -o -name "*LICENSE" -o -name "*SECURITY.md" -o -name "*RELEASE.md" -o -name "*CHANGELOG.md" -o -name "*LICENSE.md" -o -name "*CODE_OF_CONDUCT.md" -o -name "*CONTRIBUTING.md" \) -exec rm -rf -- {} + -``` ---- -<<<<<<< HEAD - -# 4. clone all of a user's git repositories -## Description: clone all of a user or organization's git repositories - -> Notes: - -## ## code +find . \( -name ".git" -o -name ".gitignore" -o -name ".gitmodules" -o -name ".gitattributes" \) -exec rm -rf -- {} + -# Generalized +find . \( -name "*SECURITY.txt" -o -name "*RELEASE.txt" -o -name "*CHANGELOG.txt" -o -name "*LICENSE.txt" -o -name "*CONTRIBUTING.txt" -name "*HISTORY.md" -o -name "*LICENSE" -o -name "*SECURITY.md" -o -name "*RELEASE.md" -o -name "*CHANGELOG.md" -o -name "*LICENSE.md" -o -name "*CODE_OF_CONDUCT.md" -o -name "*CONTRIBUTING.md" \) -exec rm -rf -- {} + -```sh +``` -======= +--- ## 4. clone all of a user's git repositories ### Description: clone all of a user or organization's git repositories > Notes: ###### code + ## Generalized + ```bash ->>>>>>> master CNTX={users|orgs}; NAME={username|orgname}; PAGE=1 curl "https://api.github.com/$CNTX/$NAME/repos?page=$PAGE&per_page=100" | grep -e 'git_url*' | cut -d \" -f 4 | xargs -L1 git clone ``` -<<<<<<< HEAD - -# Clone all Git User - -```sh -======= ## Clone all Git User + ```bash ->>>>>>> master CNTX={users}; NAME={bgoonz}; PAGE=1 curl "https://api.github.com/$CNTX/$NAME/repos?page=$PAGE&per_page=200"?branch=master | grep -e 'git_url*' | cut -d \" -f 4 | xargs -L1 git clone -``` -<<<<<<< HEAD - -# Clone all Git Organization -```sh - -======= +``` ## Clone all Git Organization + ```bash ->>>>>>> master CNTX={organizations}; NAME={TheAlgorithms}; PAGE=1 curl "https://api.github.com/$CNTX/$NAME/repos?page=$PAGE&per_page=200"?branch=master | grep -e 'git_url*' | cut -d \" -f 4 | xargs -L1 git clone -``` ---- -<<<<<<< HEAD - -# 5. Git Workflow -## Description - -## ## code +``` -```sh -======= +--- ## 5. Git Workflow + ### Description + ###### code + ```bash ->>>>>>> master git pull git init git add . git commit -m"update" git push -u origin master ``` -<<<<<<< HEAD - -```sh -======= ```bash ->>>>>>> master git init git add . git commit -m"update" git push -u origin main ``` -<<<<<<< HEAD - -```sh - -======= ```bash ->>>>>>> master git init git add . git commit -m"update" git push -u origin bryan-guner ``` -<<<<<<< HEAD - -```sh -======= ```bash ->>>>>>> master git init git add . git commit -m"update" git push -u origin gh-pages ``` -<<<<<<< HEAD - -```sh -======= ```bash ->>>>>>> master git init git add . git commit -m"update" git push -u origin preview ``` ---- -<<<<<<< HEAD - -# 6. Recursive Unzip In Place - -## Description: recursively unzips folders and then deletes the zip file by the same name - -> Notes: - -## ## code -```sh - -======= +--- ## 6. Recursive Unzip In Place ### Description: recursively unzips folders and then deletes the zip file by the same name > Notes: ###### code + ```bash ->>>>>>> master find . -name "*.zip" | while read filename; do unzip -o -d "`dirname "$filename"`" "$filename"; done; -find . -name "*.zip" -type f -print -delete -``` ---- -<<<<<<< HEAD -# 7. git pull keeping local changes - -## Description - -> Notes: - -## ## code +find . -name "*.zip" -type f -print -delete -```sh +``` -======= +--- ## 7. git pull keeping local changes ### Description > Notes: ###### code + ```bash ->>>>>>> master git stash git pull git stash pop -``` ---- -<<<<<<< HEAD - -# 8. Prettier Code Formatter - -## Description - -> Notes: -## ## code - -```sh +``` -======= +--- ## 8. Prettier Code Formatter ### Description > Notes: ###### code + ```bash ->>>>>>> master sudo npm i prettier -g -prettier --write . -``` ---- -<<<<<<< HEAD - -# 9. Pandoc -## Description - -> Notes: - -## ## code +prettier --write . -```sh +``` -======= +--- ## 9. Pandoc ### Description > Notes: ###### code + ```bash ->>>>>>> master find ./ -iname "*.md" -type f -exec sh -c 'pandoc --standalone "${0}" -o "${0%.md}.html"' {} \; -find ./ -iname "*.html" -type f -exec sh -c 'pandoc --wrap=none --from html --to markdown_strict "${0}" -o "${0%.html}.md"' {} \; -find ./ -iname "*.docx" -type f -exec sh -c 'pandoc "${0}" -o "${0%.docx}.md"' {} \; -``` ---- -<<<<<<< HEAD -# 10. Gitpod Installs - -## Description +find ./ -iname "*.html" -type f -exec sh -c 'pandoc --wrap=none --from html --to markdown_strict "${0}" -o "${0%.html}.md"' {} \; -> Notes: +find ./ -iname "*.docx" -type f -exec sh -c 'pandoc "${0}" -o "${0%.docx}.md"' {} \; -## ## code +``` -```sh -======= +--- ## 10. Gitpod Installs ### Description > Notes: ###### code + ```bash ->>>>>>> master sudo apt install tree sudo apt install pandoc -y sudo apt install rename -y @@ -974,122 +682,69 @@ npm i lebab -g npm i prettier -g npm i npm-recursive-install -g ``` -<<<<<<< HEAD - -```sh -======= ```bash ->>>>>>> master black . + prettier --write . npm-recursive-install ``` ---- -<<<<<<< HEAD - -# 11. Repo Utils Package -## Description: my standard repo utis package - -> Notes: - -## ## code - -```sh -======= +--- ## 11. Repo Utils Package ### Description: my standard repo utis package > Notes: ###### code + ```bash ->>>>>>> master npm i @bgoonz11/repoutils + ``` ---- -<<<<<<< HEAD -# 12. Unix Tree Package Usage - -## Description - -> Notes: - -## ## code - -```sh -======= +--- ## 12. Unix Tree Package Usage ### Description > Notes: ###### code + ```bash ->>>>>>> master tree -d -I 'node_modules' -tree -I 'node_modules' -<<<<<<< HEAD - -tree -f -I 'node_modules' > TREE.md - -tree -f -L 2 > README.md - -tree -f -I 'node_modules' > listing-path.md -tree -f -I 'node_modules' -d > TREE.md - -tree -f > README.md - -======= +tree -I 'node_modules' tree -f -I 'node_modules' >TREE.md + tree -f -L 2 >README.md + tree -f -I 'node_modules' >listing-path.md + tree -f -I 'node_modules' -d >TREE.md + tree -f >README.md ->>>>>>> master ``` ---- -<<<<<<< HEAD - -# 13. Find & Replace string in file & folder names recursively - -## Description - -> Notes: - -## ## code -```sh - -======= +--- ## 13. Find & Replace string in file & folder names recursively ### Description > Notes: ###### code + ```bash ->>>>>>> master find . -type f -exec rename 's/string1/string2/g' {} + + find . -type d -exec rename 's/-master//g' {} + + find . -type f -exec rename 's/\.download//g' {} + -find . -type d -exec rename 's/-main//g' {} + -rename 's/\.js\.download$/.js/'*.js\.download -rename 's/\.html\.markdown$/.md/' *.html\.markdown -find . -type d -exec rename 's/es6//g' {} + -``` ---- -<<<<<<< HEAD -# 14. Remove double extensions +find . -type d -exec rename 's/-main//g' {} + -## Description +rename 's/\.js\.download$/.js/' *.js\.download -> Notes: +rename 's/\.html\.markdown$/.md/' *.html\.markdown -## ## code +find . -type d -exec rename 's/es6//g' {} + -```sh -#!/bin/bash +``` -for file in *.md.md -======= +--- ## 14. Remove double extensions ### Description > Notes: @@ -1097,75 +752,50 @@ for file in *.md.md ```bash # !/bin/bash for file in*.md.md ->>>>>>> master do mv "${file}" "${file%.md}" done -# !/bin/bash + +#!/bin/bash + for file in *.html.html do mv "${file}" "${file%.html}" done ``` -<<<<<<< HEAD - -```sh - -#!/bin/bash - -for file in *.html.png -======= ```bash # !/bin/bash for file in*.html.png ->>>>>>> master do mv "${file}" "${file%.png}" done + for file in *.jpg.jpg do mv "${file}" "${file%.png}" done -``` ---- -<<<<<<< HEAD - -# 15. Truncate folder names down to 12 characters -## Description - -> Notes: - -## ## code - -```sh +``` -======= +--- ## 15. Truncate folder names down to 12 characters + ### Description: Truncate folder names down to 12 characters + > Notes: Truncate folder names down to 12 characters + ###### code + ```bash ->>>>>>> master for d in ./*; do mv $d ${d:0:12}; done -``` ---- -<<<<<<< HEAD - -# 16.Appendir.js - -## Description: combine the contents of every file in the contaning directory - -> Notes: this includes the contents of the file it's self... -## ## code +``` -======= +--- ## 16.Appendir.js ### Description: combine the contents of every file in the contaning directory > Notes: this includes the contents of the file it's self... ###### code ->>>>>>> master ```js //APPEND-DIR.js const fs = require('fs'); @@ -1174,263 +804,173 @@ fs.writeFile('output.md', cat, (err) => { if (err) throw err; }); ``` ---- -<<<<<<< HEAD - -# 17. Replace space in filename with underscore - -## Description: followed by replace `'#' with '_'` in directory name - -> Notes: Can be re-purposed to find and replace any set of strings in file or folder names. -## ## code - -```sh -======= +--- ## 17. Replace space in filename with underscore ### Description: followed by replace `'#' with '_'` in directory name > Notes: Can be re-purposed to find and replace any set of strings in file or folder names. ###### code + ```bash ->>>>>>> master find . -name "* *" -type f | rename 's/_//g' -find . -name "* *" -type d | rename 's/#/_/g' -``` ---- -<<<<<<< HEAD - -# 18. Filter & delete files by name and extension - -## Description -> Notes: +find . -name "* *" -type d | rename 's/#/_/g' -## ## code +``` -```sh -======= +--- ## 18. Filter & delete files by name and extension ### Description > Notes: ###### code + ```bash ->>>>>>> master find . -name '.bin' -type d -prune -exec rm -rf '{}' + + find . -name '*.html' -type d -prune -exec rm -rf '{}' + + find . -name 'nav-index' -type d -prune -exec rm -rf '{}' + + find . -name 'node-gyp' -type d -prune -exec rm -rf '{}' + -find . -name 'deleteme.txt' -type f -prune -exec rm -rf '{}' + -find . -name 'right.html' -type f -prune -exec rm -rf '{}' + -find . -name 'left.html' -type f -prune -exec rm -rf '{}' + -``` ---- -<<<<<<< HEAD -# 19. Remove lines containing string +find . -name 'deleteme.txt' -type f -prune -exec rm -rf '{}' + -## Description +find . -name 'right.html' -type f -prune -exec rm -rf '{}' + -> Notes: Remove lines not containing `'.js'` +find . -name 'left.html' -type f -prune -exec rm -rf '{}' + -```sh +``` -======= +--- ## 19. Remove lines containing string ### Description > Notes: Remove lines not containing `'.js'` ```bash ->>>>>>> master sudo sed -i '/\.js/!d' ./*scrap2.md ``` -<<<<<<< HEAD - -## ## code - -```sh -======= ###### code + ```bash ->>>>>>> master sudo sed -i '/githubusercontent/d' ./*sandbox.md + sudo sed -i '/githubusercontent/d' ./*scrap2.md + sudo sed -i '/github\.com/d' ./*out.md -sudo sed -i '/author/d' ./* -``` ---- -<<<<<<< HEAD -# 20. Remove duplicate lines from a text file +sudo sed -i '/author/d' ./* -## Description +``` -======= +--- ## 20. Remove duplicate lines from a text file + ### Description ->>>>>>> master > Notes: > //...syntax of uniq...// > $uniq [OPTION] [INPUT[OUTPUT]] > The syntax of this is quite easy to understand. Here, INPUT refers to the input file in which repeated lines need to be filtered out and if INPUT isn't specified then uniq reads from the standard input. OUTPUT refers to the output file in which you can store the filtered output generated by uniq command and as in case of INPUT if OUTPUT isn't specified then uniq writes to the standard output. -Now, let's understand the use of this with the help of an example. Suppose you have a text file named kt.txt which contains repeated lines that needs to be omitted. This can simply be done with uniq. -<<<<<<< HEAD - -## ## code -```sh -======= +Now, let's understand the use of this with the help of an example. Suppose you have a text file named kt.txt which contains repeated lines that needs to be omitted. This can simply be done with uniq. ###### code + ```bash ->>>>>>> master sudo apt install uniq uniq -u input.txt output.txt -``` ---- -<<<<<<< HEAD -# 21. Remove lines containing string - -## Description - -> Notes: - -## ## code +``` -```sh -======= +--- ## 21. Remove lines containing string ### Description > Notes: ###### code + ```bash ->>>>>>> master sudo sed -i '/githubusercontent/d' ./*sandbox.md + sudo sed -i '/githubusercontent/d' ./*scrap2.md + sudo sed -i '/github\.com/d' ./*out.md + --- title: add_days tags: date,intermediate firstSeen: 2020-10-28T16:19:04+02:00 lastUpdated: 2020-10-28T16:19:04+02:00 --- + sudo sed -i '/title:/d' ./*output.md sudo sed -i '/firstSeen/d' ./*output.md sudo sed -i '/lastUpdated/d' ./*output.md sudo sed -i '/tags:/d' ./*output.md + sudo sed -i '/badstring/d' ./* + sudo sed -i '/stargazers/d' ./repo.txt sudo sed -i '/node_modules/d' ./index.html sudo sed -i '/right\.html/d' ./index.html sudo sed -i '/right\.html/d' ./right.html -``` ---- -<<<<<<< HEAD -# 22. Zip directory excluding .git and node_modules all the way down (Linux) - -## Description - -> Notes: - -## ## code - -```sh +``` -#!/bin/bash -======= +--- ## 22. Zip directory excluding .git and node_modules all the way down (Linux) ### Descriptio: zip up an entire git directory > Notes: ###### code ```bash # !/bin/bash ->>>>>>> master TSTAMP=`date '+%Y%m%d-%H%M%S'` zip -r $1.$TSTAMP.zip $1 -x "**.git/*" -x "**node_modules/*" `shift; echo $@;` -printf "\nCreated: $1.$TSTAMP.zip\n" -<<<<<<< HEAD - -# usage: -# - zipdir thedir -# - zip thedir -x "**anotherexcludedsubdir/*" (important the double quotes to prevent glob expansion) - -# if in windows/git-bash, add 'zip' command this way: -# https://stackoverflow.com/a/55749636/1482990 -======= +printf "\nCreated: $1.$TSTAMP.zip\n" ## usage: ## - zipdir thedir ## - zip thedir -x "anotherexcludedsubdir" (important the double quotes to prevent glob expansion) + ## if in windows/git-bash, add 'zip' command this way: ## https://stackoverflow.com/a/55749636/1482990 ->>>>>>> master ``` ---- -<<<<<<< HEAD - -# 23. Delete files containing a certain string -## Description - -> Notes: - -## ## code - -```sh -find . | xargs grep -l www.redhat.com | awk '{print "rm "$1}' > doit.sh -======= +--- ## 23. Delete files containing a certain string ### Description > Notes: ###### code + ```bash find . | xargs grep -l www.redhat.com | awk '{print "rm "$1}' > doit.sh ->>>>>>> master vi doit.sh // check for murphy and his law source doit.sh ``` --- -<<<<<<< HEAD - -# 24 - -## Description - -> Notes: - -## ## code - -```sh - -#!/bin/sh - -# find ./ | grep -i "\.*$" > files -find ./ | sed -E -e 's/([^ ]+[ ]+){8}//' | grep -i "\.*$"> files +## 24 Generate sitemap +### Description +> Notes: bash command to auto generate sitemap.html which will list all files contained within parent directory. +###### code +```bash +# !/bin/sh +## find ./ | grep -i "\.*$" >files +find ./ | sed -E -e 's/([^ ]+[ ]+){8}//' | grep -i "\.*$">files listing="files" - out="" - html="sitemap.html" out="basename $out.html" html="sitemap.html" cmd() { - - echo ' ' - echo ' ' - echo ' ' - - echo ' ' - - echo ' ' - echo ' ' - echo ' ' - echo ' ' - - echo " directory " - echo ' ' - echo ' ' + echo ' ' + echo '' + echo '' + echo ' ' + echo ' ' + echo '' + echo ' ' + echo ' ' + echo " directory " + echo '' + echo '' echo "" - echo ' ' - echo ' ' - - echo ' ' - +echo ' ' + echo '' + echo '' echo "" - # continue with the HTML stuff - echo "" - echo "" - - echo "
    " - - awk '{print "
  • ",$1," 
  • "}' $listing - - # awk '{print "
  • "}; - - # {print " ",$1,"
  •  "}' \ $listing - + echo "
      " + awk '{print "
    • ",$1," 
    • "}' $listing + # awk '{print "
    • "}; + # {print " ",$1,"
    •  "}' \ $listing echo "" - - echo "
    " - - echo " " - - echo " " - + echo "
" + echo "" + echo "" } - -cmd $listing --sort=extension > > $html - +cmd $listing --sort=extension >>$html ``` - --- - -# 25. Index of Iframes - -## Description: Creates an index.html file that contains all the files in the working directory or any of it's sub folders as iframes instead of anchor tags - +## 25. Index of Iframes +### Description: Creates an index.html file that contains all the files in the working directory or any of it's sub folders as iframes instead of anchor tags > Notes: Useful Follow up Code: - -```sh - +```bash ``` - -## ## code - -```sh - -#!/bin/sh - -# find ./ | grep -i "\.*$" > files -find ./ | sed -E -e 's/([^ ]+[ ]+){8}//' | grep -i "\.*$"> files -listing="files" - -out="" - -html="index.html" -out="basename $out.html" -html="index.html" -cmd() { - - echo ' ' - echo ' ' - echo ' ' - - echo ' ' - - echo ' ' - echo ' ' - echo ' ' - echo ' ' - - echo " directory " - - echo "" - echo ' ' - echo ' ' - - echo ' ' - - echo "" - - # continue with the HTML stuff - - echo "" - - echo "" - - echo "
    " - - awk '{print ""}' $listing - - # awk '{print "
  • "}; - - # {print " ",$1,"
  •  "}' \ $listing - - echo "" - - echo "
" - - echo " " - - echo " " - -} - -cmd $listing --sort=extension > > $html - -``` - ---- - -# 26. Filter Corrupted Git Repo For Troublesome File - -## Description - -> Notes: - -## ## code - -```sh - -======= -## 24 Generate sitemap -### Description -> Notes: bash command to auto generate sitemap.html which will list all files contained within parent directory. -###### code -```bash -# !/bin/sh -## find ./ | grep -i "\.*$" >files -find ./ | sed -E -e 's/([^ ]+[ ]+){8}//' | grep -i "\.*$">files -listing="files" -out="" -html="sitemap.html" -out="basename $out.html" -html="sitemap.html" -cmd() { - echo ' ' - echo '' - echo '' - echo ' ' - echo ' ' - echo '' - echo ' ' - echo ' ' - echo " directory " - echo '' - echo '' - echo "" - echo '' - echo '' - echo '' - echo "" - # continue with the HTML stuff - echo "" - echo "" - echo "
    " - awk '{print "
  • ",$1," 
  • "}' $listing - # awk '{print "
  • "}; - # {print " ",$1,"
  •  "}' \ $listing - echo "" - echo "
" - echo "" - echo "" -} -cmd $listing --sort=extension >>$html -``` ---- -## 25. Index of Iframes -### Description: Creates an index.html file that contains all the files in the working directory or any of it's sub folders as iframes instead of anchor tags -> Notes: Useful Follow up Code: -```bash -``` -###### code -```bash -# !/bin/sh -## find ./ | grep -i "\.*$" >files -find ./ | sed -E -e 's/([^ ]+[ ]+){8}//' | grep -i "\.*$">files +###### code +```bash +# !/bin/sh +## find ./ | grep -i "\.*$" >files +find ./ | sed -E -e 's/([^ ]+[ ]+){8}//' | grep -i "\.*$">files listing="files" out="" html="index.html" @@ -1783,74 +1104,50 @@ cmd $listing --sort=extension >>$html ### Description > Notes: ###### code + ```bash ->>>>>>> master git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch assets/_index.html' HEAD -``` ---- -<<<<<<< HEAD - -# 27. OVERWRITE LOCAL CHANGES -## Description +``` -======= +--- ## 27. OVERWRITE LOCAL CHANGES + ### Description ->>>>>>> master Important: If you have any local changes, they will be lost. With or without --hard option, any local commits that haven't been pushed will be lost.[*] If you have any files that are not tracked by Git (e.g. uploaded user content), these files will not be affected. + > Notes: > First, run a fetch to update all origin/ refs to latest: -<<<<<<< HEAD - -## ## code - -```sh - -git fetch --all -# Backup your current branch: - -git branch backup-master -# Then, you have two options: - -git reset --hard origin/master -# OR If you are on some other branch: - -git reset --hard origin/ -# Explanation: -# git fetch downloads the latest from remote without trying to merge or rebase anything. - -# Then the git reset resets the master branch to what you just fetched. The --hard option changes all the files in your working tree to match the files in origin/master -======= ###### code + ```bash + git fetch --all ## Backup your current branch: + git branch backup-master ## Then, you have two options: + git reset --hard origin/master ## OR If you are on some other branch: + git reset --hard origin/ ## Explanation: ## git fetch downloads the latest from remote without trying to merge or rebase anything. + ## Then the git reset resets the master branch to what you just fetched. The --hard option changes all the files in your working tree to match the files in origin/master ->>>>>>> master git fetch --all git reset --hard origin/master -``` ---- -<<<<<<< HEAD -# 28. Remove Submodules - -## Description: To remove a submodule you need to +``` -======= +--- ## 28. Remove Submodules + ### Description: To remove a submodule you need to ->>>>>>> master > Notes: + > Delete the relevant section from the .gitmodules file. > Stage the .gitmodules changes git add .gitmodules > Delete the relevant section from .git/config. @@ -1858,130 +1155,72 @@ git reset --hard origin/master > Run rm -rf .git/modules/path_to_submodule (no trailing slash). > Commit git commit -m "Removed submodule " > Delete the now untracked submodule files rm -rf path_to_submodule -<<<<<<< HEAD - -## ## code - -```sh -======= ###### code + ```bash ->>>>>>> master git submodule deinit ``` ---- -<<<<<<< HEAD - -# 29. GET GISTS - -## Description -> Notes: - -## ## code - -```sh -======= +--- ## 29. GET GISTS ### Description > Notes: ###### code + ```bash ->>>>>>> master sudo apt install wget -wget -q -O - https://api.github.com/users/bgoonz/gists | grep raw_url | awk -F\" '{print $4}' | xargs -n3 wget -wget -q -O - https://api.github.com/users/amitness/gists | grep raw_url | awk -F\" '{print $4}' | xargs -n3 wget -wget -q -O - https://api.github.com/users/drodsou/gists | grep raw_url | awk -F\" '{print $4}' | xargs -n1 wget -wget -q -O - https://api.github.com/users/thomasmb/gists | grep raw_url | awk -F\" '{print $4}' | xargs -n1 wget -``` ---- -<<<<<<< HEAD -# 30. Remove Remote OriginL +wget -q -O - https://api.github.com/users/bgoonz/gists | grep raw_url | awk -F\" '{print $4}' | xargs -n3 wget -## Description +wget -q -O - https://api.github.com/users/amitness/gists | grep raw_url | awk -F\" '{print $4}' | xargs -n3 wget -> Notes: +wget -q -O - https://api.github.com/users/drodsou/gists | grep raw_url | awk -F\" '{print $4}' | xargs -n1 wget -## ## code +wget -q -O - https://api.github.com/users/thomasmb/gists | grep raw_url | awk -F\" '{print $4}' | xargs -n1 wget -```sh +``` -======= +--- ## 30. Remove Remote OriginL ### Description > Notes: ###### code + ```bash ->>>>>>> master git remote remove origin -``` ---- -<<<<<<< HEAD - -# 31. just clone .git folder - -## Description - -> Notes: - -## ## code -```sh +``` -======= +--- ## 31. just clone .git folder ### Description > Notes: ###### code + ```bash ->>>>>>> master git clone --bare --branch=master --single-branch https://github.com/bgoonz/My-Web-Dev-Archive.git -``` ---- -<<<<<<< HEAD - -# 32. Undo recent pull request - -## Description -> Notes: - -## ## code - -```sh +``` -======= +--- ## 32. Undo recent pull request ### Description > Notes: ###### code + ```bash ->>>>>>> master git reset --hard master@{"10 minutes ago"} -``` ---- -<<<<<<< HEAD - -# 33. Lebab - -## Description: ES5 --> ES6 - -> Notes: -## ## code - -```sh -# Safe: +``` -======= +--- ## 33. Lebab ### Description: ES5 --> ES6 > Notes: ###### code + ```bash ## Safe: ->>>>>>> master lebab --replace ./ --transform arrow lebab --replace ./ --transform arrow-return lebab --replace ./ --transform for-of @@ -1991,13 +1230,7 @@ git reset --hard master@{"10 minutes ago"} lebab --replace ./ --transform obj-method lebab --replace ./ --transform obj-shorthand lebab --replace ./ --transform multi-var -<<<<<<< HEAD - -# ALL: - -======= ## ALL: ->>>>>>> master lebab --replace ./ --transform obj-method lebab --replace ./ --transform class lebab --replace ./ --transform arrow @@ -2027,338 +1260,184 @@ lebab --replace ./ --transform template lebab --replace ./ --transform default-param lebab --replace ./ --transform destruct-param lebab --replace ./ --transform includes + ``` ---- -<<<<<<< HEAD -# 34. Troubleshoot Ubuntu Input/Output Error - -## Description: Open Powershell as Administrator - -> Notes: - -## ## code - -======= +--- ## 34. Troubleshoot Ubuntu Input/Output Error ### Description: Open Powershell as Administrator > Notes: ###### code ->>>>>>> master ```ps1 - wsl.exe --shutdown - Get-Service LxssManager | Restart-Service -``` ---- -<<<<<<< HEAD - -# 35. Export Medium as Markdown - -## Description - -> Notes: -## ## code + wsl.exe --shutdown -```sh -npm i mediumexporter -g + Get-Service LxssManager | Restart-Service -mediumexporter https://medium.com/codex/fundamental-data-structures-in-javascript-8f9f709c15b4 > ds.md +``` -======= +--- ## 35. Export Medium as Markdown ### Description > Notes: ###### code + ```bash npm i mediumexporter -g + mediumexporter https://medium.com/codex/fundamental-data-structures-in-javascript-8f9f709c15b4 >ds.md ->>>>>>> master ``` ---- -<<<<<<< HEAD - -# 36. Delete files in violation of a given size range (100MB for git) -## Description - -> Notes: - -## ## code - -```sh - -======= +--- ## 36. Delete files in violation of a given size range (100MB for git) ### Description > Notes: ###### code + ```bash ->>>>>>> master find . -size +75M -a -print -a -exec rm -f {} \; -find . -size +98M -a -print -a -exec rm -f {} \; -``` ---- -<<<<<<< HEAD - -# 37. download all links of given file type - -## Description - -> Notes: -## ## code +find . -size +98M -a -print -a -exec rm -f {} \; -```sh +``` -======= +--- ## 37. download all links of given file type ### Description > Notes: ###### code + ```bash ->>>>>>> master wget -r -A.pdf https://overapi.com/git -``` ---- -<<<<<<< HEAD - -# 38. Kill all node processes - -## Description - -> Notes: -## ## code +``` -```sh -======= +--- ## 38. Kill all node processes ### Description > Notes: ###### code + ```bash ->>>>>>> master killall -s KILL node -``` ---- -<<<<<<< HEAD -# 39. Remove string from file names recursively - -## Description: In the example below I am using this command to remove the string "-master" from all file names in the working directory and all of it's sub directories - -## ## code - -```sh -find -type f -exec sed -i 's/ / /g' {} + +``` -======= +--- ## 39. Remove string from file names recursively + ### Description: In the example below I am using this command to remove the string "-master" from all file names in the working directory and all of it's sub directories + ###### code + ```bash find -type f -exec sed -i 's///g' {} + ->>>>>>> master find . -type f -exec rename 's/-master//g' {} + -``` -<<<<<<< HEAD - -> Notes: The same could be done for folder names by changing the _-type f_ flag (for file) to a _-type d_ flag (for directory) -```sh -find -type d -exec sed -i 's/ / /g' {} + - -======= +``` > Notes: The same could be done for folder names by changing the*-type f*flag (for file) to a*-type d*flag (for directory) ```bash find -type d -exec sed -i 's///g' {} + ->>>>>>> master find . -type d -exec rename 's/-master//g' {} + -``` ---- -<<<<<<< HEAD - -# 40. Remove spaces from file and folder names recursively - -## Description: replaces spaces in file and folder names with an `_` underscore -> Notes: need to run `sudo apt install rename` to use this command - -## ## code - -```sh +``` -======= +--- ## 40. Remove spaces from file and folder names recursively ### Description: replaces spaces in file and folder names with an `_` underscore > Notes: need to run `sudo apt install rename` to use this command ###### code + ```bash ->>>>>>> master find . -name "* *" -type d | rename 's/ /_/g' find . -name "* *" -type f | rename 's/ /_/g' ``` ---- -<<<<<<< HEAD - -# 41. Zip Each subdirectories in a given directory into their own zip file -## Description - -> Notes: - -## ## code - -```sh -for i in */; do zip -r "${i%/}.zip" "$i"; done - -======= +--- ## 41. Zip Each subdirectories in a given directory into their own zip file ### Description > Notes: ###### code ```bash for i in*/; do zip -r "${i%/}.zip" "$i"; done ->>>>>>> master ``` ---- -<<<<<<< HEAD -# 90 - -# 91. Unzip PowerShell - -## Description - -> Notes: - -## ## code - -======= +--- ## 91. Unzip PowerShell ### Description > Notes: ###### code ->>>>>>> master ```ps1 + PARAM ( [string] $ZipFilesPath = "./", [string] $UnzipPath = "./RESULT" ) + $Shell = New-Object -com Shell.Application $Location = $Shell.NameSpace($UnzipPath) + $ZipFiles = Get-Childitem $ZipFilesPath -Recurse -Include *.ZIP + $progress = 1 foreach ($ZipFile in $ZipFiles) { -Write-Progress -Activity "Unzipping to $($UnzipPath)" -PercentComplete (($progress / ($ZipFiles.Count + 1))* 100) -CurrentOperation $ZipFile.FullName -Status "File $($Progress) of $($ZipFiles.Count)" + Write-Progress -Activity "Unzipping to $($UnzipPath)" -PercentComplete (($progress / ($ZipFiles.Count + 1)) * 100) -CurrentOperation $ZipFile.FullName -Status "File $($Progress) of $($ZipFiles.Count)" $ZipFolder = $Shell.NameSpace($ZipFile.fullname) -<<<<<<< HEAD - - $Location.Copyhere($ZipFolder.items(), 1040) # 1040 - No msgboxes to the user - http://msdn.microsoft.com/en-us/library/bb787866%28VS.85%29.aspx -======= $Location.Copyhere($ZipFolder.items(), 1040) # 1040 - No msgboxes to the user - https://msdn.microsoft.com/library/bb787866%28VS.85%29.aspx ->>>>>>> master $progress++ } -``` ---- -<<<<<<< HEAD - -# 92. return to bash from zsh -## Description - -> Notes: - -## ## code +``` -```sh -======= +--- ## 92. return to bash from zsh ### Description > Notes: ###### code + ```bash ->>>>>>> master sudo apt --purge remove zsh -``` ---- -<<<<<<< HEAD - -# 93. Symbolic Link - -## Description: to working directory - -> Notes: - -## ## code -```sh +``` -======= +--- ## 93. Symbolic Link ### Description: to working directory > Notes: ###### code + ```bash ->>>>>>> master ln -s "$(pwd)" ~/NameOfLink -ln -s "$(pwd)" ~/Downloads -``` ---- -<<<<<<< HEAD - -# 94. auto generate readme - -## Description: rename existing readme to blueprint.md - -> Notes: -## ## code +ln -s "$(pwd)" ~/Downloads -```sh +``` -======= +--- ## 94. auto generate readme ### Description: rename existing readme to blueprint.md > Notes: ###### code + ```bash ->>>>>>> master npx @appnest/readme generate -``` ---- -<<<<<<< HEAD - -# 95. Log into postgres - -## Description - -> Notes: -## ## code +``` -```sh -======= +--- ## 95. Log into postgres ### Description > Notes: ###### code + ```bash ->>>>>>> master sudo -u postgres psql ``` ---- -<<<<<<< HEAD - -## Technologies Used -======= +--- ## 96. URL To Subscribe To YouTube Channel ->>>>>>> master | URL | | -|----------------------|----------------------------------------------------------| +| -------------------- | -------------------------------------------------------- | | Miscellaneous | webpack ; Prism | | Widgets | Facebook ; AddThis | | Analytics | Moat ; Google Analytics ; Google Ads Conversion Tracking | @@ -2371,81 +1450,57 @@ sudo -u postgres psql | Tag managers | Google Tag Manager | | Live chat | Smartsupp ; LiveChat : Mesibo API | | JavaScript libraries | Lodash ; Dojo ; core-js ; jQuery | -<<<<<<< HEAD - - - ---- - -# 96. URL To Subscribe To YouTube Channel - -======= --- ## 96. URL To Subscribe To YouTube Channel ->>>>>>> master ## Description -> Notes: -<<<<<<< HEAD - -## ## code -======= +> Notes: ###### code ->>>>>>> master ```txt -https://www.youtube.com/channel/UC1HDa0wWnIKUf-b4yY9JecQ?sub_confirmation=1 -``` ---- -<<<<<<< HEAD -# 97. Embed Repl.it In Medium Post +https://www.youtube.com/channel/UC1HDa0wWnIKUf-b4yY9JecQ?sub_confirmation=1 -## ## code +``` -======= +--- ## 97. Embed Repl.it In Medium Post + ###### code ->>>>>>> master ```txt -https://repl.it/@bgoonz/Data-Structures-Algos-Codebase?lite=true&referrer=https%3A%2F%2Fbryanguner.medium.com -https://repl.it/@bgoonz/node-db1-project?lite=true&referrer=https%3A%2F%2Fbryanguner.medium.com -https://repl.it/@bgoonz/interview-prac?lite=true&referrer=https%3A%2F%2Fbryanguner.medium.com -https://repl.it/@bgoonz/Database-Prac?lite=true&referrer=https%3A%2F%2Fbryanguner.medium.com -``` ---- -<<<<<<< HEAD -# 98 +https://repl.it/@bgoonz/Data-Structures-Algos-Codebase?lite=true&referrer=https%3A%2F%2Fbryanguner.medium.com -## Description +https://repl.it/@bgoonz/node-db1-project?lite=true&referrer=https%3A%2F%2Fbryanguner.medium.com -> Notes: +https://repl.it/@bgoonz/interview-prac?lite=true&referrer=https%3A%2F%2Fbryanguner.medium.com -## ## code +https://repl.it/@bgoonz/Database-Prac?lite=true&referrer=https%3A%2F%2Fbryanguner.medium.com -```sh +``` -======= +--- ## 98 rRmove text target="parent" from files called right.html ### Description > Notes: ###### code ```bash ->>>>>>> master find . -name *right.html -type f -exec sed -i 's/target="_parent"//g' {} + -find . -name*right.html -type f -exec sed -i 's/target="_parent"//g' {} + -``` -<<<<<<< HEAD -======= +``` ## 99. Cheat Sheet + ### Description + > Notes: + ###### code + ```bash -# !/bin/bash +#!/bin/bash revert ## SHORTCUTS and HISTORY + + CTRL+A # move to beginning of line CTRL+B # moves backward one character CTRL+C # halts the current command @@ -2471,6 +1526,7 @@ CTRL+W # kills the word behind the cursor CTRL+X # lists the possible filename completions of the current word CTRL+Y # retrieves (yank) last item killed CTRL+Z # stops the current command, resume with fg in the foreground or bg in the background + ALT+B # moves backward one word ALT+D # deletes next word ALT+F # moves forward one word @@ -2483,26 +1539,41 @@ ALT+C # capitalizes the letter under the cursor. The cursor then moves to the ALT+R # reverts any changes to a command you've pulled from your history if you've edited it. ALT+? # list possible completions to what is typed ALT+^ # expand line to most recent match from history + CTRL+X then ( # start recording a keyboard macro CTRL+X then ) # finish recording keyboard macro CTRL+X then E # recall last recorded keyboard macro CTRL+X then CTRL+E # invoke text editor (specified by $EDITOR) on current command line then execute resultes as shell commands + BACKSPACE # deletes one character backward DELETE # deletes one character under cursor + history # shows command line history !! # repeats the last command ! # refers to command line 'n' ! # refers to command starting with 'string' + exit # logs out of current session + + ## BASH BASICS + + env # displays all environment variables + echo $SHELL # displays the shell you're using echo $BASH_VERSION # displays bash version + bash # if you want to use bash (type exit to go back to your previously opened shell) whereis bash # locates the binary, source and manual-page for a command which bash # finds out which program is executed as 'bash' (default: /bin/bash, can change across environments) + clear # clears content on window (hide displayed lines) + + ## FILE COMMANDS + + ls # lists your files in current directory, ls to print files in a specific directory ls -l # lists your files in 'long format', which contains the exact size of the file, who owns the file and who has the right to look at it, and when it was last modified ls -a # lists all files in 'long format', including hidden files (name beginning with '.') @@ -2540,7 +1611,11 @@ grep # looks for the string in the files grep -r # search recursively for pattern in directory head -n file_name | tail +n # Print nth line from file. head -y lines.txt | tail +x # want to display all the lines from x to y. This includes the xth and yth lines. + + ## DIRECTORY COMMANDS + + mkdir # makes a new directory rmdir # remove an empty directory rmdir -rf # remove a non-empty directory @@ -2552,10 +1627,15 @@ cp -r # copy into including sub-directorie pwd # tells you where you currently are cd ~ # changes to home. cd - # changes to previous working directory + + ## SSH, SYSTEM INFO & NETWORK COMMANDS + + ssh user@host # connects to host as user ssh -p user@host # connects to host on specified port as user ssh-copy-id user@host # adds your ssh key to host for user to enable a keyed or passwordless login + whoami # returns your username passwd # lets you change your password quota -v # shows what your disk quota is @@ -2577,13 +1657,19 @@ lsof # lists open files bg # lists stopped or background jobs ; resume a stopped job in the background fg # brings the most recent job in the foreground fg # brings job to the foreground + ping # pings host and outputs results whois # gets whois information for domain dig # gets DNS information for domain dig -x # reverses lookup host wget # downloads file + time # report time consumed by command execution + + ## VARIABLES + + varname=value # defines a variable varname=value command # defines a variable to be in the environment of a particular subprocess echo $varname # checks a variable's value @@ -2595,53 +1681,74 @@ read -p "prompt" # same as above but outputs a prompt to ask user fo column -t # display info in pretty columns (often used with pipe) let = # performs mathematical calculation using operators like +, -, *, /, % export VARNAME=value # defines an environment variable (will be available in subprocesses) + array[0]=valA # how to define an array array[1]=valB array[2]=valC array=([2]=valC [0]=valA [1]=valB) # another way array=(valA valB valC) # and another + ${array[i]} # displays array's value for this index. If no index is supplied, array element 0 is assumed ${#array[i]} # to find out the length of any element in the array ${#array[@]} # to find out how many values there are in the array + declare -a # the variables are treated as arrays declare -f # uses function names only declare -F # displays function names without definitions declare -i # the variables are treated as integers declare -r # makes the variables read-only declare -x # marks the variables for export via the environment + ${varname:-word} # if varname exists and isn't null, return its value; otherwise return word ${varname:word} # if varname exists and isn't null, return its value; otherwise return word ${varname:=word} # if varname exists and isn't null, return its value; otherwise set it word and then return its value ${varname:?message} # if varname exists and isn't null, return its value; otherwise print varname, followed by message and abort the current command or script ${varname:+word} # if varname exists and isn't null, return word; otherwise return null ${varname:offset:length} # performs substring expansion. It returns the substring of $varname starting at offset and up to length characters + ${variable#pattern} # if the pattern matches the beginning of the variable's value, delete the shortest part that matches and return the rest ${variable##pattern} # if the pattern matches the beginning of the variable's value, delete the longest part that matches and return the rest ${variable%pattern} # if the pattern matches the end of the variable's value, delete the shortest part that matches and return the rest ${variable%%pattern} # if the pattern matches the end of the variable's value, delete the longest part that matches and return the rest ${variable/pattern/string} # the longest match to pattern in variable is replaced by string. Only the first match is replaced ${variable//pattern/string} # the longest match to pattern in variable is replaced by string. All matches are replaced + ${#varname} # returns the length of the value of the variable as a character string + *(patternlist) # matches zero or more occurrences of the given patterns +(patternlist) # matches one or more occurrences of the given patterns ?(patternlist) # matches zero or one occurrence of the given patterns @(patternlist) # matches exactly one of the given patterns !(patternlist) # matches anything except one of the given patterns + $(UNIX command) # command substitution: runs the command and returns standard output + + ## FUNCTIONS + + ## The function refers to passed arguments by position (as if they were positional parameters), that is, $1, $2, and so forth. ## $@ is equal to "$1" "$2"... "$N", where N is the number of positional parameters. $# holds the number of positional parameters. + function functname() { shell commands } + unset -f functname # deletes a function definition declare -f # displays all defined functions in your login session + + ## FLOW CONTROLS + + statement1 && statement2 # and operator statement1 || statement2 # or operator + -a # and operator inside a test conditional expression -o # or operator inside a test conditional expression + ## STRINGS + str1 == str2 # str1 matches str2 str1 != str2 # str1 does not match str2 str1 < str2 # str1 is less than str2 (alphabetically) @@ -2650,7 +1757,9 @@ str1 \> str2 # str1 is sorted after str2 str1 \< str2 # str1 is sorted before str2 -n str1 # str1 is not null (has length greater than 0) -z str1 # str1 is null (has length 0) + ## FILES + -a file # file exists or its compilation is successful -d file # file exists and is a directory -e file # file exists; same -a @@ -2664,13 +1773,16 @@ str1 \< str2 # str1 is sorted before str2 -G file # file's group ID matches yours (or one of yours, if you are in multiple groups) file1 -nt file2 # file1 is newer than file2 file1 -ot file2 # file1 is older than file2 + ## NUMBERS + -lt # less than -le # less than or equal -eq # equal -ge # greater than or equal -gt # greater than -ne # not equal + if condition then statements @@ -2679,42 +1791,59 @@ then [else statements] fi + for x in {1..10} do statements done + for name [in list] do statements that can use $name done + for (( initialisation ; ending condition ; update )) do statements... done + case expression in pattern1 ) statements ;; pattern2 ) statements ;; esac + select name [in list] do statements that can use $name done + while condition; do statements done + until condition; do statements done + + ## COMMAND-LINE PROCESSING CYCLE + + ## The default order for command lookup is functions, followed by built-ins, with scripts and executables last. ## There are three built-ins that you can use to override this order: `command`, `builtin` and `enable`. + command # removes alias and function lookup. Only built-ins and commands found in the search path are executed builtin # looks up only built-in commands, ignoring functions and commands found in PATH enable # enables and disables shell built-ins + eval # takes arguments and run them through the command-line processing steps all over again + + ## INPUT/OUTPUT REDIRECTORS + + cmd1|cmd2 # pipe; takes standard output of cmd1 as standard input to cmd2 < file # takes standard input from file > file # directs standard output to file @@ -2735,71 +1864,108 @@ n<&m # file descriptor n is made to be a copy of the input file descriptor >&- # closes the standard output n>&- # closes the ouput from file descriptor n n<&- # closes the input from file descripor n + |tee # output command to both terminal and a file (-a to append to file) + + ## PROCESS HANDLING + + ## To suspend a job, type CTRL+Z while it is running. You can also suspend a job with CTRL+Y. ## This is slightly different from CTRL+Z in that the process is only stopped when it attempts to read input from terminal. ## Of course, to interrupt a job, type CTRL+C. + myCommand & # runs job in the background and prompts back the shell + jobs # lists all jobs (use with -l to see associated PID) + fg # brings a background job into the foreground fg %+ # brings most recently invoked background job fg %- # brings second most recently invoked background job fg %N # brings job number N fg %string # brings job whose command begins with string fg %?string # brings job whose command contains string + kill -l # returns a list of all signals on the system, by name and number kill PID # terminates process with specified PID kill -s SIGKILL 4500 # sends a signal to force or terminate the process kill -15 913 # Ending PID 913 process with signal 15 (TERM) kill %1 # Where %1 is the number of job as read from 'jobs' command. + ps # prints a line of information about the current running login shell and any processes running under it ps -a # selects all processes with a tty except session leaders + trap cmd sig1 sig2 # executes a command when a signal is received by the script trap "" sig1 sig2 # ignores that signals trap - sig1 sig2 # resets the action taken when the signal is received to the default + disown # removes the process from the list of jobs + wait # waits until all background jobs have finished sleep # wait # of seconds before continuing + pv # display progress bar for data handling commands. often used with pipe like |pv yes # give yes response everytime an input is requested from script/process + + ## TIPS & TRICKS + + ## set an alias cd; nano .bash_profile > alias gentlenode='ssh admin@gentlenode.com -p 3404' # add your alias in .bash_profile + ## to quickly go to a specific directory cd; nano .bashrc > shopt -s cdable_vars > export websites="/Users/mac/Documents/websites" + source .bashrc cd $websites + + ## DEBUGGING SHELL PROGRAMS + + bash -n scriptname # don't run commands; check for syntax errors only set -o noexec # alternative (set option in script) + bash -v scriptname # echo commands before running them set -o verbose # alternative (set option in script) + bash -x scriptname # echo commands after command-line processing set -o xtrace # alternative (set option in script) + trap 'echo $varname' EXIT # useful when you want to print out the values of variables at the point that your script exits + function errtrap { es=$? echo "ERROR line $1: Command exited with status $es." } + trap 'errtrap $LINENO' ERR # is run whenever a command in the surrounding script or function exits with non-zero status + function dbgtrap { echo "badvar is $badvar" } + trap dbgtrap DEBUG # causes the trap code to be executed before every statement in a function or script ## ...section of code in which the problem occurs... trap - DEBUG # turn off the DEBUG trap + function returntrap { echo "A return occurred" } + trap returntrap RETURN # is executed each time a shell function or a script executed with the . or source commands finishes executing + + ## COLORS AND BACKGROUNDS + ## note: \e or \x1B also work instead of \033 ## Reset Color_Off='\033[0m' # Text Reset + ## Regular Colors Black='\033[0;30m' # Black Red='\033[0;31m' # Red @@ -2809,6 +1975,7 @@ Blue='\033[0;34m' # Blue Purple='\033[0;35m' # Purple Cyan='\033[0;36m' # Cyan White='\033[0;97m' # White + ## Additional colors LGrey='\033[0;37m' # Ligth Gray DGrey='\033[0;90m' # Dark Gray @@ -2818,6 +1985,7 @@ LYellow='\033[0;93m'# Ligth Yellow LBlue='\033[0;94m' # Ligth Blue LPurple='\033[0;95m'# Light Purple LCyan='\033[0;96m' # Ligth Cyan + ## Bold BBlack='\033[1;30m' # Black BRed='\033[1;31m' # Red @@ -2827,6 +1995,7 @@ BBlue='\033[1;34m' # Blue BPurple='\033[1;35m'# Purple BCyan='\033[1;36m' # Cyan BWhite='\033[1;37m' # White + ## Underline UBlack='\033[4;30m' # Black URed='\033[4;31m' # Red @@ -2836,6 +2005,7 @@ UBlue='\033[4;34m' # Blue UPurple='\033[4;35m'# Purple UCyan='\033[4;36m' # Cyan UWhite='\033[4;37m' # White + ## Background On_Black='\033[40m' # Black On_Red='\033[41m' # Red @@ -2845,91 +2015,93 @@ On_Blue='\033[44m' # Blue On_Purple='\033[45m'# Purple On_Cyan='\033[46m' # Cyan On_White='\033[47m' # White + ## Example of usage echo -e "${Green}This is GREEN text${Color_Off} and normal text" echo -e "${Red}${On_White}This is Red test on White background${Color_Off}" ## option -e is mandatory, it enable interpretation of backslash escapes printf "${Red} This is red \n" + ``` +
+ > + #### Find + ## To find files by case-insensitive extension (ex: .jpg, .JPG, .jpG) + find . -iname "\*.jpg" + ## To find directories + find . -type d + ## To find files + find . -type f + ## To find files by octal permission + find . -type f -perm 777 + ## To find files with setuid bit set + find . -xdev \( -perm -4000 \) -type f -print0 | xargs -0 ls -l + ## To find files with extension '.txt' and remove them + find ./path/ -name '\*.txt' -exec rm '{}' \; + ## To find files with extension '.txt' and look for a string into them + find ./path/ -name '\*.txt' | xargs grep 'string' + ## To find files with size bigger than 5 Mebibyte and sort them by size + find . -size +5M -type f -print0 | xargs -0 ls -Ssh | sort -z + ## To find files bigger than 2 Megabyte and list them + find . -type f -size +200000000c -exec ls -lh {} \; | awk '{ print $9 ": " $5 }' + ## To find files modified more than 7 days ago and list file information + find . -type f -mtime +7d -ls + ## To find symlinks owned by a user and list file information + find . -type l -user -ls + ## To search for and delete empty directories + find . -type d -empty -exec rmdir {} \; + ## To search for directories named build at a max depth of 2 directories + find . -maxdepth 2 -name build -type d + ## To search all files who are not in .git directory + find . ! -iwholename '*.git*' -type f + ## To find all files that have the same node (hard link) as MY_FILE_HERE + find . -type f -samefile MY_FILE_HERE 2>/dev/null + ## To find all files in the current directory and modify their permissions + find . -type f -exec chmod 644 {} \; + --- ->>>>>>> master
+ --- + ![Preview](https://i.imgur.com/nieW1vp.png) + ## Wiki Nav -<<<<<<< HEAD - -- [Home](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki) -- [add copy to code blocks.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/add-copy-to-code-blocks.md) -- [Add site search w algolia.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/Add-site-search-w-algolia.md) -- [adding mailing list.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/adding-mailing-list.md) -- [Adding search 2 gatsby site.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/Adding-search-2-gatsby-site.md) -- [awesome.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/awesome.md) -- [broken links.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/broken-links.md) -- [configure custom domain.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/configure-custom-domain.md) -- [contentauthoring.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/contentauthoring.md) -- [full text search w lunar.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/full-text-search-w-lunar.md) -- [inject 4.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/inject-4.md) -- [inject3.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/inject3.md) -- [inject4.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/inject4.md) -- [injected content part2.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/injected-content-part2.md) -- [injected js part4.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/injected-js-part4.md) -- [injected part3.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/injected-part3.md) -- [links 2 embed.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/links-2-embed.md) -- [links to remember](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/links-to-remember) -- [Netlify Injected Content](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/Netlify-Injected-Content) -- [old version of index.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/old-version-of-index.md) -- [optimize vscode.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/optimize-vscode.md) -- [possibly useful snippets.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/possibly-useful-snippets.md) -- [privacy policy.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/privacy-policy.md) -- [random stuff.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/random-stuff.md) -- [random.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/random.md) -- [ref type](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/ref-type) -- [SEO.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/SEO.md) -- [stable points.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/stable-points.md) -- [tech used.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/tech-used.md) -- [Technologies Used.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/Technologies-Used.md) -- [THINGS TO EMBED.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/THINGS-TO-EMBED.md) -- [validation report.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/validation-report.md) -- [web archive.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/web-archive.md) -- [wordpress vs headless cms.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/wordpress-vs-headless-cms.md) - -======= - [Home](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki) - [add copy to code blocks.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/add-copy-to-code-blocks.md) - [Add site search w algolia.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/Add-site-search-w-algolia.md) @@ -2964,75 +2136,120 @@ find . -type f -exec chmod 644 {} \; - [validation report.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/validation-report.md) - [web archive.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/web-archive.md) - [wordpress vs headless cms.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/wordpress-vs-headless-cms.md) ->>>>>>> master --- + ## Dependencies
+ Click to expand! + - Click to expand! [![@algolia**](https://avatars.githubusercontent.com/u/2034458?s=40&v=4)](https://github.com/algolia)[algolia / algoliasearch-client-javascript](https://github.com/algolia/algoliasearch-client-javascript)@algolia/client-search `^ 4.10.3` + [![@algolia**](https://avatars.githubusercontent.com/u/2034458?s=40&v=4)](https://github.com/algolia)[algolia / algoliasearch-client-javascript](https://github.com/algolia/algoliasearch-client-javascript)@algolia/client-common `4.10.5` + ![@ghost**](https://avatars.githubusercontent.com/u/10137?s=40&v=4)@algolia/requester-common `4.10.5` + [![@algolia**](https://avatars.githubusercontent.com/u/2034458?s=40&v=4)](https://github.com/algolia)[algolia / algoliasearch-client-javascript](https://github.com/algolia/algoliasearch-client-javascript)@algolia/transporter `4.10.5` + [![@stackbit**](https://avatars.githubusercontent.com/u/38996451?s=40&v=4)](https://github.com/stackbit)[stackbit / gatsby-plugin-menus](https://github.com/stackbit/gatsby-plugin-menus)@stackbit/gatsby-plugin-menus `0.0.4` + [![@facebook**](https://avatars.githubusercontent.com/u/69631?s=40&v=4)](https://github.com/facebook)[facebook / jest](https://github.com/facebook/jest)babel-jest `^ 24.7.1` + [![@gatsbyjs**](https://avatars.githubusercontent.com/u/12551863?s=40&v=4)](https://github.com/gatsbyjs)[gatsbyjs / gatsby](https://github.com/gatsbyjs/gatsby)babel-preset-gatsby `^ 0.1.11` + [![@gatsbyjs**](https://avatars.githubusercontent.com/u/12551863?s=40&v=4)](https://github.com/gatsbyjs)[gatsbyjs / gatsby](https://github.com/gatsbyjs/gatsby) `^ 2.5.0` + [![@keyz**](https://avatars.githubusercontent.com/u/2268452?s=40&u=c3f56fe1d943474ffe4577a82ad79c1a79d7eb6e&v=4)](https://github.com/keyz)[keyz / identity-obj-proxy](https://github.com/keyz/identity-obj-proxy) `^ 3.0.0` + [![@facebook**](https://avatars.githubusercontent.com/u/69631?s=40&v=4)](https://github.com/facebook)[facebook / jest](https://github.com/facebook/jest) `^ 24.7.1` + [![@lodash**](https://avatars.githubusercontent.com/u/2565403?s=40&v=4)](https://github.com/lodash)[lodash / lodash](https://github.com/lodash/lodash) `^ 4.17.11` + [![@facebook**](https://avatars.githubusercontent.com/u/69631?s=40&v=4)](https://github.com/facebook)[facebook / react](https://github.com/facebook/react)react-test-renderer `^ 16.8.6` + [![@getkirby-v2**](https://avatars.githubusercontent.com/u/6985611?s=40&v=4)](https://github.com/getkirby-v2)[getkirby-v2 / algolia-plugin](https://github.com/getkirby-v2/algolia-plugin)algolia `0.0.0` + [![@ecomfe**](https://avatars.githubusercontent.com/u/2268460?s=40&v=4)](https://github.com/ecomfe)[ecomfe / babel-runtime](https://github.com/ecomfe/babel-runtime) `6.26.0` + [![@paulmillr**](https://avatars.githubusercontent.com/u/574696?s=40&u=7f4396380d73af134b898c8eaf7bb171f448f40f&v=4)](https://github.com/paulmillr)[paulmillr / chokidar](https://github.com/paulmillr/chokidar) `3.4.0` + [![@DefinitelyTyped**](https://avatars.githubusercontent.com/u/3637556?s=40&v=4)](https://github.com/DefinitelyTyped)[DefinitelyTyped / DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped)@types/node `^ 13` + [![@micromatch**](https://avatars.githubusercontent.com/u/26890389?s=40&v=4)](https://github.com/micromatch)[micromatch / anymatch](https://github.com/micromatch/anymatch) `~ 3.1.1` + [![@micromatch**](https://avatars.githubusercontent.com/u/26890389?s=40&v=4)](https://github.com/micromatch)[micromatch / braces](https://github.com/micromatch/braces) `~ 3.0.2` + [![@chaijs**](https://avatars.githubusercontent.com/u/1515293?s=40&v=4)](https://github.com/chaijs)[chaijs / chai](https://github.com/chaijs/chai) `^ 4.2` + [![@microsoft**](https://avatars.githubusercontent.com/u/6154722?s=40&v=4)](https://github.com/microsoft)[microsoft / dtslint](https://github.com/microsoft/dtslint) `^ 3.3.0` + [![@eslint**](https://avatars.githubusercontent.com/u/6019716?s=40&v=4)](https://github.com/eslint)[eslint / eslint](https://github.com/eslint/eslint) `^ 6.6.0` + [![@fsevents**](https://avatars.githubusercontent.com/u/48760001?s=40&v=4)](https://github.com/fsevents)[fsevents / fsevents](https://github.com/fsevents/fsevents) `~ 2.1.2` + [![@gulpjs**](https://avatars.githubusercontent.com/u/6200624?s=40&v=4)](https://github.com/gulpjs)[gulpjs / glob-parent](https://github.com/gulpjs/glob-parent) `~ 5.1.0` + [![@sindresorhus**](https://avatars.githubusercontent.com/u/170270?s=40&u=34acd557a042ac478d273a4621570cadb6b0bd89&v=4)](https://github.com/sindresorhus)[sindresorhus / is-binary-path](https://github.com/sindresorhus/is-binary-path) `~ 2.1.0` + [![@micromatch**](https://avatars.githubusercontent.com/u/26890389?s=40&v=4)](https://github.com/micromatch)[micromatch / is-glob](https://github.com/micromatch/is-glob) `~ 4.0.1` + [![@mochajs**](https://avatars.githubusercontent.com/u/8770005?s=40&v=4)](https://github.com/mochajs)[mochajs / mocha](https://github.com/mochajs/mocha) `^ 7.0.0` + [![@jonschlinkert**](https://avatars.githubusercontent.com/u/383994?s=40&u=335f06277f72722162e89bd5516849f2e82f37cf&v=4)](https://github.com/jonschlinkert)[jonschlinkert / normalize-path](https://github.com/jonschlinkert/normalize-path) `~ 3.0.0` + [![@istanbuljs**](https://avatars.githubusercontent.com/u/13523395?s=40&v=4)](https://github.com/istanbuljs)[istanbuljs / nyc](https://github.com/istanbuljs/nyc) `^ 15.0.0` + [![@paulmillr**](https://avatars.githubusercontent.com/u/574696?s=40&u=7f4396380d73af134b898c8eaf7bb171f448f40f&v=4)](https://github.com/paulmillr)[paulmillr / readdirp](https://github.com/paulmillr/readdirp) `~ 3.4.0` + [![@isaacs**](https://avatars.githubusercontent.com/u/9287?s=40&u=60a280618307ae965cadbe52da4baa7e351c848c&v=4)](https://github.com/isaacs)[isaacs / rimraf](https://github.com/isaacs/rimraf) `^ 3.0.0` + [![@sinonjs**](https://avatars.githubusercontent.com/u/6570253?s=40&v=4)](https://github.com/sinonjs)[sinonjs / sinon](https://github.com/sinonjs/sinon) `^ 9.0.1` + [![@domenic**](https://avatars.githubusercontent.com/u/617481?s=40&v=4)](https://github.com/domenic)[domenic / sinon-chai](https://github.com/domenic/sinon-chai) `^ 3.3.0` + [![@anodynos**](https://avatars.githubusercontent.com/u/856453?s=40&v=4)](https://github.com/anodynos)[anodynos / upath](https://github.com/anodynos/upath) `^ 1.2.0` + [![@JedWatson**](https://avatars.githubusercontent.com/u/872310?s=40&u=9548676d01f104232ee42e5ac0d985db77e6a5a4&v=4)](https://github.com/JedWatson)[JedWatson / classnames](https://github.com/JedWatson/classnames) `2.2.6` + [![@bestiejs**](https://avatars.githubusercontent.com/u/802850?s=40&v=4)](https://github.com/bestiejs)[bestiejs / benchmark.js](https://github.com/bestiejs/benchmark.js)benchmark `^ 1.0.0` + [![@browserify**](https://avatars.githubusercontent.com/u/6320506?s=40&v=4)](https://github.com/browserify)[browserify / browserify](https://github.com/browserify/browserify) `^ 14.1.0` + [![@mochajs**](https://avatars.githubusercontent.com/u/8770005?s=40&v=4)](https://github.com/mochajs)[mochajs / mocha](https://github.com/mochajs/mocha) `^ 2.1.0` + [![@jeromedecoster**](https://avatars.githubusercontent.com/u/158071?s=40&u=470a733fdc34a9fedab18ae4cf5109d2ea357425&v=4)](https://github.com/jeromedecoster)[jeromedecoster / opn-cli](https://github.com/jeromedecoster/opn-cli) `^ 3.1.0` + [![@documentationjs**](https://avatars.githubusercontent.com/u/11415556?s=40&v=4)](https://github.com/documentationjs)[documentationjs / documentation](https://github.com/documentationjs/documentation) `^ 13.2.5` + [![@babel**](https://avatars.githubusercontent.com/u/9637642?s=40&v=4)](https://github.com/babel)[babel / babel](https://github.com/babel/babel)@babel/core `7.12.3` + [Cloudfare-Backup](https://bgoonz-blog-2-0.pages.dev/) ↞↠ Search Website: [search](https://www.algolia.com/realtime-search-demo/web-dev-resource-hub-9e6b8aa8-6106-44c5-9f59-ff3f9531abd4) ↞↠ [Backup Repo Deploy](https://bgoonzblog20-backup.netlify.app/#gsc.tab=0) ↞↠ [Github pages](https://bgoonz.github.io/BGOONZ_BLOG_2.0/) ↞↠ [Go To Site Wiki](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki) +
+ --- + ## Docs Structure
+ Docs Structure + - Docs Structure ``` ├── blog │ ├── 300-react-questions.md @@ -3259,403 +2476,10 @@ find . -type f -exec chmod 644 {} \; ├── readme.md ├── showcase.md └── tree.md -23 directories, 202 files -``` -<<<<<<< HEAD - -# SITEMAP - -# [**🌍⇒https://bgoonz-blog.netlify.app/🗺️**](https://bgoonz-blog.netlify.app/) - -## [**🌍⇒blog🗺️**](https://bgoonz-blog.netlify.app/blog) - -## [**🌍⇒docs🗺️**](https://bgoonz-blog.netlify.app/docs) - -## [**🌍⇒readme🗺️**](https://bgoonz-blog.netlify.app/readme) - -## [**🌍⇒review🗺️**](https://bgoonz-blog.netlify.app/review) - -## [**🌍⇒showcase🗺️**](https://bgoonz-blog.netlify.app/showcase) - -## [**🌍⇒blog/awesome-graphql🗺️**](https://bgoonz-blog.netlify.app/blog/awesome-graphql) - -## [**🌍⇒blog/big-o-complexity🗺️**](https://bgoonz-blog.netlify.app/blog/big-o-complexity) - -## [**🌍⇒blog/blog-archive🗺️**](https://bgoonz-blog.netlify.app/blog/blog-archive) - -## [**🌍⇒blog/blogwcomments🗺️**](https://bgoonz-blog.netlify.app/blog/blogwcomments) - -## [**🌍⇒blog/data-structures🗺️**](https://bgoonz-blog.netlify.app/blog/data-structures) - -## [**🌍⇒blog/flow-control-in-python🗺️**](https://bgoonz-blog.netlify.app/blog/flow-control-in-python) - -## [**🌍⇒blog/functions-in-python🗺️**](https://bgoonz-blog.netlify.app/blog/functions-in-python) - -## [**🌍⇒blog/git-gateway🗺️**](https://bgoonz-blog.netlify.app/blog/git-gateway) - -## [**🌍⇒blog/interview-questions-js🗺️**](https://bgoonz-blog.netlify.app/blog/interview-questions-js) - -## [**🌍⇒blog/media-queries-explained🗺️**](https://bgoonz-blog.netlify.app/blog/media-queries-explained) - -## [**🌍⇒blog/my-medium🗺️**](https://bgoonz-blog.netlify.app/blog/my-medium) - -## [**🌍⇒blog/netlify-cms🗺️**](https://bgoonz-blog.netlify.app/blog/netlify-cms) - -## [**🌍⇒blog/platform-docs🗺️**](https://bgoonz-blog.netlify.app/blog/platform-docs) - -## [**🌍⇒blog/python-for-js-dev🗺️**](https://bgoonz-blog.netlify.app/blog/python-for-js-dev) - -## [**🌍⇒blog/python-resources🗺️**](https://bgoonz-blog.netlify.app/blog/python-resources) - -## [**🌍⇒blog/web-dev-trends🗺️**](https://bgoonz-blog.netlify.app/blog/web-dev-trends) - -## [**🌍⇒blog/web-scraping🗺️**](https://bgoonz-blog.netlify.app/blog/web-scraping) - -## [**🌍⇒docs/about🗺️**](https://bgoonz-blog.netlify.app/docs/about) - -## [**🌍⇒docs/articles🗺️**](https://bgoonz-blog.netlify.app/docs/articles) - -## [**🌍⇒docs/audio🗺️**](https://bgoonz-blog.netlify.app/docs/audio) - -## [**🌍⇒docs/career🗺️**](https://bgoonz-blog.netlify.app/docs/career) - -## [**🌍⇒docs/community🗺️**](https://bgoonz-blog.netlify.app/docs/community) - -## [**🌍⇒docs/content🗺️**](https://bgoonz-blog.netlify.app/docs/content) - -## [**🌍⇒docs/docs🗺️**](https://bgoonz-blog.netlify.app/docs/docs) - -## [**🌍⇒docs/faq🗺️**](https://bgoonz-blog.netlify.app/docs/faq) - -## [**🌍⇒docs/gallery🗺️**](https://bgoonz-blog.netlify.app/docs/gallery) - -## [**🌍⇒docs/interact🗺️**](https://bgoonz-blog.netlify.app/docs/interact) - -## [**🌍⇒docs/javascript🗺️**](https://bgoonz-blog.netlify.app/docs/javascript) - -## [**🌍⇒docs/leetcode🗺️**](https://bgoonz-blog.netlify.app/docs/leetcode) - -## [**🌍⇒docs/other-content🗺️**](https://bgoonz-blog.netlify.app/docs/other-content) - -## [**🌍⇒docs/privacy-policy🗺️**](https://bgoonz-blog.netlify.app/docs/privacy-policy) - -## [**🌍⇒docs/projects🗺️**](https://bgoonz-blog.netlify.app/docs/projects) - -## [**🌍⇒docs/python🗺️**](https://bgoonz-blog.netlify.app/docs/python) - -## [**🌍⇒docs/quick-reference🗺️**](https://bgoonz-blog.netlify.app/docs/quick-reference) - -## [**🌍⇒docs/react🗺️**](https://bgoonz-blog.netlify.app/docs/react) - -## [**🌍⇒docs/reference🗺️**](https://bgoonz-blog.netlify.app/docs/reference) - -## [**🌍⇒docs/search🗺️**](https://bgoonz-blog.netlify.app/docs/search) - -## [**🌍⇒docs/sitemap🗺️**](https://bgoonz-blog.netlify.app/docs/sitemap) - -## [**🌍⇒docs/tools🗺️**](https://bgoonz-blog.netlify.app/docs/tools) - -## [**🌍⇒docs/tutorials🗺️**](https://bgoonz-blog.netlify.app/docs/tutorials) - -## [**🌍⇒docs/about/eng-portfolio🗺️**](https://bgoonz-blog.netlify.app/docs/about/eng-portfolio) - -## [**🌍⇒docs/about/ideas-for-this-website🗺️**](https://bgoonz-blog.netlify.app/docs/about/ideas-for-this-website) - -## [**🌍⇒docs/about/intrests🗺️**](https://bgoonz-blog.netlify.app/docs/about/intrests) - -## [**🌍⇒docs/about/interview🗺️**](https://bgoonz-blog.netlify.app/docs/about/interview) - -## [**🌍⇒docs/about/resume🗺️**](https://bgoonz-blog.netlify.app/docs/about/resume) - -## [**🌍⇒docs/articles/basic-web-dev🗺️**](https://bgoonz-blog.netlify.app/docs/articles/basic-web-dev) - -## [**🌍⇒docs/articles/buffers🗺️**](https://bgoonz-blog.netlify.app/docs/articles/buffers) - -## [**🌍⇒docs/articles/dev-dep🗺️**](https://bgoonz-blog.netlify.app/docs/articles/dev-dep) - -## [**🌍⇒docs/articles/event-loop🗺️**](https://bgoonz-blog.netlify.app/docs/articles/event-loop) - -## [**🌍⇒docs/articles/fs-module🗺️**](https://bgoonz-blog.netlify.app/docs/articles/fs-module) - -## [**🌍⇒docs/articles/how-the-web-works🗺️**](https://bgoonz-blog.netlify.app/docs/articles/how-the-web-works) - -## [**🌍⇒docs/articles/http🗺️**](https://bgoonz-blog.netlify.app/docs/articles/http) - -## [**🌍⇒docs/articles/install🗺️**](https://bgoonz-blog.netlify.app/docs/articles/install) - -## [**🌍⇒docs/articles/intro🗺️**](https://bgoonz-blog.netlify.app/docs/articles/intro) - -## [**🌍⇒docs/articles/media-queries-no-more🗺️**](https://bgoonz-blog.netlify.app/docs/articles/media-queries-no-more) -## [**🌍⇒docs/articles/module-exports🗺️**](https://bgoonz-blog.netlify.app/docs/articles/module-exports) - -## [**🌍⇒docs/articles/nextjs🗺️**](https://bgoonz-blog.netlify.app/docs/articles/nextjs) - -## [**🌍⇒docs/articles/node-api-express🗺️**](https://bgoonz-blog.netlify.app/docs/articles/node-api-express) - -## [**🌍⇒docs/articles/node-cli-args🗺️**](https://bgoonz-blog.netlify.app/docs/articles/node-cli-args) - -## [**🌍⇒docs/articles/node-common-modules🗺️**](https://bgoonz-blog.netlify.app/docs/articles/node-common-modules) - -## [**🌍⇒docs/articles/node-env-variables🗺️**](https://bgoonz-blog.netlify.app/docs/articles/node-env-variables) - -## [**🌍⇒docs/articles/node-js-language🗺️**](https://bgoonz-blog.netlify.app/docs/articles/node-js-language) - -## [**🌍⇒docs/articles/node-package-manager🗺️**](https://bgoonz-blog.netlify.app/docs/articles/node-package-manager) - -## [**🌍⇒docs/articles/node-repl🗺️**](https://bgoonz-blog.netlify.app/docs/articles/node-repl) - -## [**🌍⇒docs/articles/node-run-cli🗺️**](https://bgoonz-blog.netlify.app/docs/articles/node-run-cli) - -## [**🌍⇒docs/articles/nodejs🗺️**](https://bgoonz-blog.netlify.app/docs/articles/nodejs) - -## [**🌍⇒docs/articles/nodevsbrowser🗺️**](https://bgoonz-blog.netlify.app/docs/articles/nodevsbrowser) - -## [**🌍⇒docs/articles/npm🗺️**](https://bgoonz-blog.netlify.app/docs/articles/npm) - -## [**🌍⇒docs/articles/npx🗺️**](https://bgoonz-blog.netlify.app/docs/articles/npx) - -## [**🌍⇒docs/articles/os-module🗺️**](https://bgoonz-blog.netlify.app/docs/articles/os-module) - -## [**🌍⇒docs/articles/package-lock🗺️**](https://bgoonz-blog.netlify.app/docs/articles/package-lock) - -## [**🌍⇒docs/articles/reading-files🗺️**](https://bgoonz-blog.netlify.app/docs/articles/reading-files) - -## [**🌍⇒docs/articles/semantic🗺️**](https://bgoonz-blog.netlify.app/docs/articles/semantic) - -## [**🌍⇒docs/articles/semantic-html🗺️**](https://bgoonz-blog.netlify.app/docs/articles/semantic-html) - -## [**🌍⇒docs/articles/the-uniform-resource-locator-(url)🗺️**]() - -## [**🌍⇒docs/articles/understanding-firebase🗺️**](https://bgoonz-blog.netlify.app/docs/articles/understanding-firebase) - -## [**🌍⇒docs/articles/v8🗺️**](https://bgoonz-blog.netlify.app/docs/articles/v8) - -## [**🌍⇒docs/articles/web-standards-checklist🗺️**](https://bgoonz-blog.netlify.app/docs/articles/web-standards-checklist) - -## [**🌍⇒docs/articles/webdev-tools🗺️**](https://bgoonz-blog.netlify.app/docs/articles/webdev-tools) - -## [**🌍⇒docs/articles/write-2-json-with-python🗺️**](https://bgoonz-blog.netlify.app/docs/articles/write-2-json-with-python) - -## [**🌍⇒docs/articles/writing-files🗺️**](https://bgoonz-blog.netlify.app/docs/articles/writing-files) - -## [**🌍⇒docs/audio/audio🗺️**](https://bgoonz-blog.netlify.app/docs/audio/audio) - -## [**🌍⇒docs/audio/audio-feature-extraction🗺️**](https://bgoonz-blog.netlify.app/docs/audio/audio-feature-extraction) - -## [**🌍⇒docs/audio/dfft🗺️**](https://bgoonz-blog.netlify.app/docs/audio/dfft) - -## [**🌍⇒docs/audio/discrete-fft🗺️**](https://bgoonz-blog.netlify.app/docs/audio/discrete-fft) - -## [**🌍⇒docs/audio/dtw-python-explained🗺️**](https://bgoonz-blog.netlify.app/docs/audio/dtw-python-explained) - -## [**🌍⇒docs/audio/dynamic-time-warping🗺️**](https://bgoonz-blog.netlify.app/docs/audio/dynamic-time-warping) - -## [**🌍⇒docs/audio/web-audio-api🗺️**](https://bgoonz-blog.netlify.app/docs/audio/web-audio-api) - -## [**🌍⇒docs/career/confidence🗺️**](https://bgoonz-blog.netlify.app/docs/career/confidence) - -## [**🌍⇒docs/career/dev-interview🗺️**](https://bgoonz-blog.netlify.app/docs/career/dev-interview) - -## [**🌍⇒docs/career/interview-dos-n-donts🗺️**](https://bgoonz-blog.netlify.app/docs/career/interview-dos-n-donts) - -## [**🌍⇒docs/career/job-boards🗺️**](https://bgoonz-blog.netlify.app/docs/career/job-boards) - -## [**🌍⇒docs/community/an-open-letter-2-future-developers🗺️**](https://bgoonz-blog.netlify.app/docs/community/an-open-letter-2-future-developers) - -## [**🌍⇒docs/community/video-chat🗺️**](https://bgoonz-blog.netlify.app/docs/community/video-chat) - -## [**🌍⇒docs/content/algo🗺️**](https://bgoonz-blog.netlify.app/docs/content/algo) - -## [**🌍⇒docs/content/archive🗺️**](https://bgoonz-blog.netlify.app/docs/content/archive) - -## [**🌍⇒docs/content/data-structures-algo🗺️**](https://bgoonz-blog.netlify.app/docs/content/data-structures-algo) - -## [**🌍⇒docs/content/gatsby-Queries-Mutations🗺️**](https://bgoonz-blog.netlify.app/docs/content/gatsby-Queries-Mutations) - -## [**🌍⇒docs/content/history-api🗺️**](https://bgoonz-blog.netlify.app/docs/content/history-api) - -## [**🌍⇒docs/content/projects🗺️**](https://bgoonz-blog.netlify.app/docs/content/projects) - -## [**🌍⇒docs/content/recent-projects🗺️**](https://bgoonz-blog.netlify.app/docs/content/recent-projects) - -## [**🌍⇒docs/content/trouble-shooting🗺️**](https://bgoonz-blog.netlify.app/docs/content/trouble-shooting) - -## [**🌍⇒docs/docs/appendix🗺️**](https://bgoonz-blog.netlify.app/docs/docs/appendix) - -## [**🌍⇒docs/docs/bash🗺️**](https://bgoonz-blog.netlify.app/docs/docs/bash) - -## [**🌍⇒docs/docs/content🗺️**](https://bgoonz-blog.netlify.app/docs/docs/content) - -## [**🌍⇒docs/docs/css🗺️**](https://bgoonz-blog.netlify.app/docs/docs/css) - -## [**🌍⇒docs/docs/data-structures-docs🗺️**](https://bgoonz-blog.netlify.app/docs/docs/data-structures-docs) - -## [**🌍⇒docs/docs/git-reference🗺️**](https://bgoonz-blog.netlify.app/docs/docs/git-reference) - -## [**🌍⇒docs/docs/git-repos🗺️**](https://bgoonz-blog.netlify.app/docs/docs/git-repos) - -## [**🌍⇒docs/docs/html-spec🗺️**](https://bgoonz-blog.netlify.app/docs/docs/html-spec) - -## [**🌍⇒docs/docs/markdown🗺️**](https://bgoonz-blog.netlify.app/docs/docs/markdown) - -## [**🌍⇒docs/docs/no-whiteboarding🗺️**](https://bgoonz-blog.netlify.app/docs/docs/no-whiteboarding) - -## [**🌍⇒docs/docs/node-docs-complete🗺️**](https://bgoonz-blog.netlify.app/docs/docs/node-docs-complete) - -## [**🌍⇒docs/docs/node-docs-full🗺️**](https://bgoonz-blog.netlify.app/docs/docs/node-docs-full) - -## [**🌍⇒docs/docs/regex-in-js🗺️**](https://bgoonz-blog.netlify.app/docs/docs/regex-in-js) - -## [**🌍⇒docs/docs/sitemap🗺️**](https://bgoonz-blog.netlify.app/docs/docs/sitemap) - -## [**🌍⇒docs/faq/contact🗺️**](https://bgoonz-blog.netlify.app/docs/faq/contact) - -## [**🌍⇒docs/faq/plug-ins🗺️**](https://bgoonz-blog.netlify.app/docs/faq/plug-ins) - -## [**🌍⇒docs/interact/callstack-visual🗺️**](https://bgoonz-blog.netlify.app/docs/interact/callstack-visual) +23 directories, 202 files -## [**🌍⇒docs/interact/clock🗺️**](https://bgoonz-blog.netlify.app/docs/interact/clock) - -## [**🌍⇒docs/interact/jupyter-notebooks🗺️**](https://bgoonz-blog.netlify.app/docs/interact/jupyter-notebooks) - -## [**🌍⇒docs/interact/other-sites🗺️**](https://bgoonz-blog.netlify.app/docs/interact/other-sites) - -## [**🌍⇒docs/interact/video-chat🗺️**](https://bgoonz-blog.netlify.app/docs/interact/video-chat) - -## [**🌍⇒docs/javascript/arrow-functions🗺️**](https://bgoonz-blog.netlify.app/docs/javascript/arrow-functions) - -## [**🌍⇒docs/javascript/await-keyword🗺️**](https://bgoonz-blog.netlify.app/docs/javascript/await-keyword) - -## [**🌍⇒docs/javascript/bigo🗺️**](https://bgoonz-blog.netlify.app/docs/javascript/bigo) - -## [**🌍⇒docs/javascript/clean-code🗺️**](https://bgoonz-blog.netlify.app/docs/javascript/clean-code) - -## [**🌍⇒docs/javascript/constructor-functions🗺️**](https://bgoonz-blog.netlify.app/docs/javascript/constructor-functions) - -## [**🌍⇒docs/javascript/promises🗺️**](https://bgoonz-blog.netlify.app/docs/javascript/promises) - -## [**🌍⇒docs/javascript/review🗺️**](https://bgoonz-blog.netlify.app/docs/javascript/review) - -## [**🌍⇒docs/javascript/this-is-about-this🗺️**](https://bgoonz-blog.netlify.app/docs/javascript/this-is-about-this) - -## [**🌍⇒docs/projects/medium-links🗺️**](https://bgoonz-blog.netlify.app/docs/projects/medium-links) - -## [**🌍⇒docs/projects/my-websites🗺️**](https://bgoonz-blog.netlify.app/docs/projects/my-websites) - -## [**🌍⇒docs/python/at-length🗺️**](https://bgoonz-blog.netlify.app/docs/python/at-length) - -## [**🌍⇒docs/python/basics🗺️**](https://bgoonz-blog.netlify.app/docs/python/basics) - -## [**🌍⇒docs/python/cheat-sheet🗺️**](https://bgoonz-blog.netlify.app/docs/python/cheat-sheet) - -## [**🌍⇒docs/python/comprehensive-guide🗺️**](https://bgoonz-blog.netlify.app/docs/python/comprehensive-guide) - -## [**🌍⇒docs/python/examples🗺️**](https://bgoonz-blog.netlify.app/docs/python/examples) - -## [**🌍⇒docs/python/flow-control🗺️**](https://bgoonz-blog.netlify.app/docs/python/flow-control) - -## [**🌍⇒docs/python/functions🗺️**](https://bgoonz-blog.netlify.app/docs/python/functions) - -## [**🌍⇒docs/python/google-sheets-api🗺️**](https://bgoonz-blog.netlify.app/docs/python/google-sheets-api) - -## [**🌍⇒docs/python/intro-for-js-devs🗺️**](https://bgoonz-blog.netlify.app/docs/python/intro-for-js-devs) - -## [**🌍⇒docs/python/python-ds🗺️**](https://bgoonz-blog.netlify.app/docs/python/python-ds) - -## [**🌍⇒docs/python/snippets🗺️**](https://bgoonz-blog.netlify.app/docs/python/snippets) - -## [**🌍⇒docs/quick-reference/Emmet🗺️**](https://bgoonz-blog.netlify.app/docs/quick-reference/Emmet) - -## [**🌍⇒docs/quick-reference/all-emojis🗺️**](https://bgoonz-blog.netlify.app/docs/quick-reference/all-emojis) - -## [**🌍⇒docs/quick-reference/create-react-app🗺️**](https://bgoonz-blog.netlify.app/docs/quick-reference/create-react-app) - -## [**🌍⇒docs/quick-reference/git-bash🗺️**](https://bgoonz-blog.netlify.app/docs/quick-reference/git-bash) - -## [**🌍⇒docs/quick-reference/git-tricks🗺️**](https://bgoonz-blog.netlify.app/docs/quick-reference/git-tricks) - -## [**🌍⇒docs/quick-reference/google-firebase🗺️**](https://bgoonz-blog.netlify.app/docs/quick-reference/google-firebase) - -## [**🌍⇒docs/quick-reference/heroku-error-codes🗺️**](https://bgoonz-blog.netlify.app/docs/quick-reference/heroku-error-codes) - -## [**🌍⇒docs/quick-reference/installation🗺️**](https://bgoonz-blog.netlify.app/docs/quick-reference/installation) - -## [**🌍⇒docs/quick-reference/markdown-dropdowns🗺️**](https://bgoonz-blog.netlify.app/docs/quick-reference/markdown-dropdowns) - -## [**🌍⇒docs/quick-reference/minifiction🗺️**](https://bgoonz-blog.netlify.app/docs/quick-reference/minifiction) - -## [**🌍⇒docs/quick-reference/new-repo-instructions🗺️**](https://bgoonz-blog.netlify.app/docs/quick-reference/new-repo-instructions) - -## [**🌍⇒docs/quick-reference/psql-setup🗺️**](https://bgoonz-blog.netlify.app/docs/quick-reference/psql-setup) - -## [**🌍⇒docs/quick-reference/pull-request-rubric🗺️**](https://bgoonz-blog.netlify.app/docs/quick-reference/pull-request-rubric) - -## [**🌍⇒docs/quick-reference/quick-links🗺️**](https://bgoonz-blog.netlify.app/docs/quick-reference/quick-links) - -## [**🌍⇒docs/quick-reference/topRepos🗺️**](https://bgoonz-blog.netlify.app/docs/quick-reference/topRepos) - -## [**🌍⇒docs/quick-reference/understanding-path🗺️**](https://bgoonz-blog.netlify.app/docs/quick-reference/understanding-path) - -## [**🌍⇒docs/quick-reference/vscode-themes🗺️**](https://bgoonz-blog.netlify.app/docs/quick-reference/vscode-themes) - -## [**🌍⇒docs/react/cheatsheet🗺️**](https://bgoonz-blog.netlify.app/docs/react/cheatsheet) - -## [**🌍⇒docs/react/createReactApp🗺️**](https://bgoonz-blog.netlify.app/docs/react/createReactApp) - -## [**🌍⇒docs/react/demo🗺️**](https://bgoonz-blog.netlify.app/docs/react/demo) - -## [**🌍⇒docs/react/jsx🗺️**](https://bgoonz-blog.netlify.app/docs/react/jsx) - -## [**🌍⇒docs/react/react-docs🗺️**](https://bgoonz-blog.netlify.app/docs/react/react-docs) - -## [**🌍⇒docs/react/react-in-depth🗺️**](https://bgoonz-blog.netlify.app/docs/react/react-in-depth) - -## [**🌍⇒docs/react/react2🗺️**](https://bgoonz-blog.netlify.app/docs/react/react2) - -## [**🌍⇒docs/react/render-elements🗺️**](https://bgoonz-blog.netlify.app/docs/react/render-elements) - -## [**🌍⇒docs/reference/awesome-lists🗺️**](https://bgoonz-blog.netlify.app/docs/reference/awesome-lists) - -## [**🌍⇒docs/reference/awesome-static🗺️**](https://bgoonz-blog.netlify.app/docs/reference/awesome-static) - -## [**🌍⇒docs/reference/bookmarks🗺️**](https://bgoonz-blog.netlify.app/docs/reference/bookmarks) - -## [**🌍⇒docs/reference/embed-the-web🗺️**](https://bgoonz-blog.netlify.app/docs/reference/embed-the-web) - -## [**🌍⇒docs/reference/github-search🗺️**](https://bgoonz-blog.netlify.app/docs/reference/github-search) - -## [**🌍⇒docs/reference/how-2-reinstall-npm🗺️**](https://bgoonz-blog.netlify.app/docs/reference/how-2-reinstall-npm) - -## [**🌍⇒docs/reference/how-to-kill-a-process🗺️**](https://bgoonz-blog.netlify.app/docs/reference/how-to-kill-a-process) - -## [**🌍⇒docs/reference/installing-node🗺️**](https://bgoonz-blog.netlify.app/docs/reference/installing-node) - -## [**🌍⇒docs/reference/intro-to-nodejs🗺️**](https://bgoonz-blog.netlify.app/docs/reference/intro-to-nodejs) - -## [**🌍⇒docs/reference/notes-template🗺️**](https://bgoonz-blog.netlify.app/docs/reference/notes-template) - -## [**🌍⇒docs/reference/psql🗺️**](https://bgoonz-blog.netlify.app/docs/reference/psql) - -## [**🌍⇒docs/reference/resources🗺️**](https://bgoonz-blog.netlify.app/docs/reference/resources) - -## [**🌍⇒docs/reference/vscode🗺️**](https://bgoonz-blog.netlify.app/docs/reference/vscode) - -## [**🌍⇒docs/reference/web-api's🗺️**](https://bgoonz-blog.netlify.app/docs/reference/web-api's) - -## [**🌍⇒docs/tools/data-structures🗺️**](https://bgoonz-blog.netlify.app/docs/tools/data-structures) - -## [**🌍⇒docs/tools/dev-utilities🗺️**](https://bgoonz-blog.netlify.app/docs/tools/dev-utilities) - -## [**🌍⇒docs/tools/google-cloud🗺️**](https://bgoonz-blog.netlify.app/docs/tools/google-cloud) - -## [**🌍⇒docs/tools/markdown-html🗺️**](https://bgoonz-blog.netlify.app/docs/tools/markdown-html) - -## [**🌍⇒docs/tools/more-tools🗺️**](https://bgoonz-blog.netlify.app/docs/tools/more-tools) - -## [**🌍⇒docs/tutorials/google-lighthouse-cli🗺️**](https://bgoonz-blog.netlify.app/docs/tutorials/google-lighthouse-cli) - -======= +``` ## SITEMAP [**🌍⇒https://bgoonz-blog.netlify.app/🗺️**](https://bgoonz-blog.netlify.app/) [**🌍⇒blog🗺️**](https://bgoonz-blog.netlify.app/blog) @@ -3852,514 +2676,123 @@ find . -type f -exec chmod 644 {} \; [**🌍⇒docs/tools/markdown-html🗺️**](https://bgoonz-blog.netlify.app/docs/tools/markdown-html) [**🌍⇒docs/tools/more-tools🗺️**](https://bgoonz-blog.netlify.app/docs/tools/more-tools) [**🌍⇒docs/tutorials/google-lighthouse-cli🗺️**](https://bgoonz-blog.netlify.app/docs/tutorials/google-lighthouse-cli) ->>>>>>> master
---- ---- ---- - -
- - - ↞↠ Getting Started With GatsbyJS ↞↠ -# ---- -## 🚀 Quick start -1. **Create a Gatsby site.** - Use the Gatsby CLI to create a new site, specifying the default starter. -<<<<<<< HEAD - - ```shell - # create a new Gatsby site using the default starter - gatsby new my-default-starter https://github.com/gatsbyjs/gatsby-starter-default - ``` - -======= -```bashell - # create a new Gatsby site using the default starter - gatsby new my-default-starter https://github.com/gatsbyjs/gatsby-starter-default -``` ->>>>>>> master -1. **Start developing.** - Navigate into your new site's directory and start it up. -<<<<<<< HEAD - - ```shell - cd my-default-starter/ - gatsby develop - ``` - -======= -```bashell - cd my-default-starter/ - gatsby develop -``` ->>>>>>> master -1. **Open the source code and start editing!** - Your site is now running at `http://localhost:8000`! -<<<<<<< HEAD - - _Note: You'll also see a second link:_`http://localhost:8000/___graphql`_. This is a tool you can use to experiment with querying your data. Learn more about using this tool in the [Gatsby tutorial](https://www.gatsbyjs.com/tutorial/part-five/#introducing-graphiql)._ - -======= - *Note: You'll also see a second link:*`http://localhost:8000/___graphql`_. This is a tool you can use to experiment with querying your data. Learn more about using this tool in the [Gatsby tutorial](https://www.gatsbyjs.com/tutorial/part-five/#introducing-graphiql)._ ->>>>>>> master - Open the `my-default-starter` directory in your code editor of choice and edit `src/pages/index.js`. Save your changes and the browser will update in real time! -## 🧐 What's inside? -A quick look at the top-level files and directories you'll see in a Gatsby project. - . - ├── node_modules - ├── src - ├── .gitignore - ├── .prettierrc - ├── gatsby-browser.js - ├── gatsby-config.js - ├── gatsby-node.js - ├── gatsby-ssr.js - ├── LICENSE - ├── package-lock.json - ├── package.json - └── README.md -1. **`/node_modules`**: This directory contains all of the modules of code that your project depends on (npm packages) are automatically installed. -2. **`/src`**: This directory will contain all of the code related to what you will see on the front-end of your site (what you see in the browser) such as your site header or a page template. `src` is a convention for "source code". -3. **`.gitignore`**: This file tells git which files it should not track / not maintain a version history for. -4. **`.prettierrc`**: This is a configuration file for [Prettier](https://prettier.io/). Prettier is a tool to help keep the formatting of your code consistent. -5. **`gatsby-browser.js`**: This file is where Gatsby expects to find any usage of the [Gatsby browser APIs](https://www.gatsbyjs.com/docs/browser-apis/) (if any). These allow customization/extension of default Gatsby settings affecting the browser. -6. **`gatsby-config.js`**: This is the main configuration file for a Gatsby site. This is where you can specify information about your site (metadata) like the site title and description, which Gatsby plugins you'd like to include, etc. (Check out the [config docs](https://www.gatsbyjs.com/docs/gatsby-config/) for more detail). -7. **`gatsby-node.js`**: This file is where Gatsby expects to find any usage of the [Gatsby Node APIs](https://www.gatsbyjs.com/docs/node-apis/) (if any). These allow customization/extension of default Gatsby settings affecting pieces of the site build process. -8. **`gatsby-ssr.js`**: This file is where Gatsby expects to find any usage of the [Gatsby server-side rendering APIs](https://www.gatsbyjs.com/docs/ssr-apis/) (if any). These allow customization of default Gatsby settings affecting server-side rendering. -9. **`LICENSE`**: This Gatsby starter is licensed under the 0BSD license. This means that you can see this file as a placeholder and replace it with your own license. -10. **`package-lock.json`** (See `package.json` below, first). This is an automatically generated file based on the exact versions of your npm dependencies that were installed for your project. **(You won't change this file directly).** -11. **`package.json`**: A manifest file for Node.js projects, which includes things like metadata (the project's name, author, etc). This manifest is how npm knows which packages to install for your project. -12. **`README.md`**: A text file containing useful reference information about your project. -## 🎓 Learning Gatsby -Looking for more guidance? Full documentation for Gatsby lives [on the website](https://www.gatsbyjs.com/). Here are some places to start: -<<<<<<< HEAD - -- **For most developers, we recommend starting with our [in-depth tutorial for creating a site with Gatsby**](https://www.gatsbyjs.com/tutorial/).\*\* It starts with zero assumptions about your level of ability and walks through every step of the process. -- -- **To dive straight into code samples, head [to our documentation**](https://www.gatsbyjs.com/docs/).\*\* In particular, check out the _Guides_, _API Reference_, and _Advanced Tutorials_ sections in the sidebar. - -======= -- **For most developers, we recommend starting with our [in-depth tutorial for creating a site with Gatsby**](https://www.gatsbyjs.com/tutorial/).\*\* It starts with zero assumptions about your level of ability and walks through every step of the process. -- -- **To dive straight into code samples, head [to our documentation**](https://www.gatsbyjs.com/docs/).\*\* In particular, check out the *Guides*, *API Reference*, and *Advanced Tutorials* sections in the sidebar. ->>>>>>> master -## 💫 Deploy -[![Deploy to Netlify**](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/BGOONZ_BLOG_2.0.git) -[![Deploy with Vercel**](https://vercel.com/button)](https://vercel.com/import/project?template=https://github.com/BGOONZ_BLOG_2.0.git) -<<<<<<< HEAD - - - ---- - -# Gatsby Project Structure | Gatsby - -======= ---- -### Gatsby With Netlify CMS -This tutorial will use [gatsby-personal-starter-blog](https://github.com/thomaswang/gatsby-personal-starter-blog), a Gatsby starter based on the official [gatsby-starter-blog](/starters/gatsbyjs/gatsby-starter-blog/). The differences are that `gatsby-personal-starter-blog` is configured to run the blog on a subdirectory, `/blog`, and comes pre-installed with [Netlify CMS](https://www.netlifycms.org/) for content editing. It also adds VS Code highlighting for code blocks. -## Prerequisites -- A GitHub account -- The [Gatsby CLI](/docs/reference/gatsby-cli/) installed -## Set up a Netlify CMS-managed Gatsby site in 5 steps -### Step 1 -Open your Terminal and run the following command from the Gatsby CLI to create a new Gatsby site using [gatsby-personal-starter-blog](https://github.com/thomaswang/gatsby-personal-starter-blog). -```shell -gatsby new [your-project-name] https://github.com/thomaswangio/gatsby-personal-starter-blog -``` -### Step 2 -Once the Gatsby site is finished installing all the packages and dependencies, you can now go into the directory and run the site locally. -```shell -cd [your-project-name] -gatsby develop -``` -Now you can go to `http://localhost:8000` to see your new site, but what's extra cool is that Netlify CMS is pre-installed and you can access it at `http://localhost:8000/admin` -A CMS, or content management system, is useful because you can add content like blog posts from a dashboard on your site, instead of having to add posts manually with Markdown. However, you'll likely want to be able to access the CMS from a deployed website, not just locally. For that, you'll need to deploy to Netlify through GitHub, set up continuous deployment, and do a few configurations. You'll go over this in [Step-5](#step-5). -### Step 3 -Open the project in your code editor and open `static/admin/config.yml`. Replace `your-username/your-repo-name` with your GitHub username and project name. This step is important for managing and deploying the Netlify CMS interface. -```diff -backend: -- name: test-repo -+ name: github -+ repo: your-username/your-repo-name -``` -#### Customizing your site -Head into `gatsby-config.js` and you can edit your siteMetadata, add a Google Analytics tracking ID, and your app icon/favicon. Test out the edits for the deployed build by quitting the development server and running `gatsby build && gatsby serve`. -You'll likely also want to edit the `README.md` and `package.json` files to include your own project details. -### Step 4 -Open [github.com](https://github.com) and create a new repository, with the same name as your project. Push your new Gatsby site's code to GitHub using the following Terminal commands: -```shell -git init -git add . -git commit -m "initial commit" -git remote add origin https://github.com/[your-username]/[your-repo-name].git -git push -u origin master -``` -Then, open [app.netlify.com](https://app.netlify.com) and add a "New site from Git". Choose your newly created repo and click on "Deploy site" with the default deployment settings. -> *Note: if you don't see the correct repo listed, you may need to install or reconfigure the Netlify app on GitHub.* -![Netlify Dashboard for Creating a new site](netlify-dashboard.png) -### Step 5 -To make sure that Netlify CMS has access to your GitHub repo, you need to set up an OAuth application on GitHub. The instructions for that are here: [Netlify's Using an Authorization Provider](https://www.netlify.com/docs/authentication-providers/#using-an-authentication-provider). -For the "Homepage URL" – you can use your Netlify subdomain, `[name-of-your-site].netlify.com`, or you can use a custom domain. To customize the subdomain, look for the "Edit site name" field under "Domain Management" for your project on the [Netlify app](https://app.netlify.com). To connect your Netlify site to your custom domain instead, see [Netlify’s instructions on custom domains](https://www.netlify.com/docs/custom-domains/). -Once you've configured an authentication provider then you'll be able to use Netlify CMS at your deployed site to add new posts. -![Netlify and GitHub Authorization](https://cdn.netlify.com/67edd5b656c432888d736cd40125cb61376905bb/c1cba/img/docs/github-oauth-config.png) -Copy the credentials of your new app listed on [GitHub OAuth Apps](https://github.com/settings/developers) and install a new auth provider on Netlify using them. -![Setting up access control](netlify-install-oauth-provider.png) -#### Benefits of Netlify CMS, GitHub, and Netlify Workflow -Congrats! Now that Netlify CMS is successfully configured to your project, every time you add a new post, the content will be stored in your repository and versioned on GitHub because Netlify CMS is Git-based. Also, thanks to [Netlify's Continuous Deployment](https://www.netlify.com/docs/continuous-deployment/), a new version will be deployed every time you add or edit a post. -You can learn more about Netlify CMS and how to configure it further in the [Netlify CMS documentation](https://www.netlifycms.org/docs/intro/) ---- ---- -## Gatsby Project Structure | Gatsby ->>>>>>> master -> ## Excerpt -> -> Inside a Gatsby project, you may see some or all of the following folders and files: Folders /.cache Automatically generated. This folder… ---- -Inside a Gatsby project, you may see some or all of the following folders and files: -``` -<<<<<<< HEAD -/|-- /.cache|-- /plugins|-- /public|-- /src |-- /api |-- /pages |-- /templates |-- html.js|-- /static|-- gatsby-config.js|-- gatsby-node.js|-- gatsby-ssr.js|-- gatsby-browser.js -``` - -## [](https://www.gatsbyjs.com/docs/reference/gatsby-project-structure/#folders)Folders - -- **`/.cache`** _Automatically generated._ This folder is an internal cache created automatically by Gatsby. The files inside this folder are not meant for modification. Should be added to the `.gitignore` file if not added already. -- **`/plugins`** This folder hosts any project-specific ("local") plugins that aren't published as an `npm` package. Check out the [plugin docs](https://www.gatsbyjs.com/docs/plugins/) for more detail. -- **`/public`** _Automatically generated._ The output of the build process will be exposed inside this folder. Should be added to the `.gitignore` file if not added already. -- **`/src`** This directory will contain all of the code related to what you will see on the frontend of your site (what you see in the browser), like your site header, or a page template. "src" is a convention for "source code". - - - **`/api`** JavaScript and TypeScript files under `src/api` become functions automatically with paths based on their file name. Check out the [functions guide](https://www.gatsbyjs.com/docs/reference/functions/) for more detail. - - **`/pages`** Components under `src/pages` become pages automatically with paths based on their file name. Check out the [pages recipes](https://www.gatsbyjs.com/docs/recipes/pages-layouts) for more detail. - - **`/templates`** Contains templates for programmatically creating pages. Check out the [templates docs](https://www.gatsbyjs.com/docs/conceptual/building-with-components/#page-template-components) for more detail. - - **`html.js`** For custom configuration of default `.cache/default_html.js`. Check out the [custom HTML docs](https://www.gatsbyjs.com/docs/custom-html/) for more detail. - -- **`/static`** If you put a file into the static folder, it will not be processed by webpack. Instead it will be copied into the public folder untouched. Check out the [assets docs](https://www.gatsbyjs.com/docs/how-to/images-and-media/static-folder/#adding-assets-outside-of-the-module-system) for more detail. - -## [](https://www.gatsbyjs.com/docs/reference/gatsby-project-structure/#files)Files - -- **`gatsby-browser.js`**: This file is where Gatsby expects to find any usage of the [Gatsby browser APIs](https://www.gatsbyjs.com/docs/reference/config-files/gatsby-browser/) (if any). These allow customization/extension of default Gatsby settings affecting the browser. -- **`gatsby-config.js`**: This is the main configuration file for a Gatsby site. This is where you can specify information about your site (metadata) like the site title and description, which Gatsby plugins you'd like to include, etc. Check out the [config docs](https://www.gatsbyjs.com/docs/reference/config-files/gatsby-config/) for more detail. -- **`gatsby-node.js`**: This file is where Gatsby expects to find any usage of the [Gatsby node APIs](https://www.gatsbyjs.com/docs/reference/config-files/gatsby-node/) (if any). These allow customization/extension of default Gatsby settings affecting pieces of the site build process. -- **`gatsby-ssr.js`**: This file is where Gatsby expects to find any usage of the [Gatsby server-side rendering APIs](https://www.gatsbyjs.com/docs/reference/config-files/gatsby-ssr/) (if any). These allow customization of default Gatsby settings affecting server-side rendering. - -## [](https://www.gatsbyjs.com/docs/reference/gatsby-project-structure/#miscellaneous)Miscellaneous - -======= -/| --- /.cache -|-- /plugins -|-- /public -|-- /src -|-- /api -|-- /pages -|-- /templates -|-- html.js -|-- /static -|-- gatsby-config.js -|-- gatsby-node.js -|-- gatsby-ssr.js -|-- gatsby-browser.js -``` -[Folders](https://www.gatsbyjs.com/docs/reference/gatsby-project-structure/#folders) -- **`/.cache`** *Automatically generated.* This folder is an internal cache created automatically by Gatsby. The files inside this folder are not meant for modification. Should be added to the `.gitignore` file if not added already. -- **`/plugins`** This folder hosts any project-specific ("local") plugins that aren't published as an `npm` package. Check out the [plugin docs](https://www.gatsbyjs.com/docs/plugins/) for more detail. -- **`/public`** *Automatically generated.* The output of the build process will be exposed inside this folder. Should be added to the `.gitignore` file if not added already. -- **`/src`** This directory will contain all of the code related to what you will see on the frontend of your site (what you see in the browser), like your site header, or a page template. "src" is a convention for "source code". - - **`/api`** JavaScript and TypeScript files under `src/api` become functions automatically with paths based on their file name. Check out the [functions guide](https://www.gatsbyjs.com/docs/reference/functions/) for more detail. - - **`/pages`** Components under `src/pages` become pages automatically with paths based on their file name. Check out the [pages recipes](https://www.gatsbyjs.com/docs/recipes/pages-layouts) for more detail. - - **`/templates`** Contains templates for programmatically creating pages. Check out the [templates docs](https://www.gatsbyjs.com/docs/conceptual/building-with-components/#page-template-components) for more detail. - - **`html.js`** For custom configuration of default `.cache/default_html.js`. Check out the [custom HTML docs](https://www.gatsbyjs.com/docs/custom-html/) for more detail. -- **`/static`** If you put a file into the static folder, it will not be processed by webpack. Instead it will be copied into the public folder untouched. Check out the [assets docs](https://www.gatsbyjs.com/docs/how-to/images-and-media/static-folder/#adding-assets-outside-of-the-module-system) for more detail. -[Files](https://www.gatsbyjs.com/docs/reference/gatsby-project-structure/#files) -- **`gatsby-browser.js`**: This file is where Gatsby expects to find any usage of the [Gatsby browser APIs](https://www.gatsbyjs.com/docs/reference/config-files/gatsby-browser/) (if any). These allow customization/extension of default Gatsby settings affecting the browser. -- **`gatsby-config.js`**: This is the main configuration file for a Gatsby site. This is where you can specify information about your site (metadata) like the site title and description, which Gatsby plugins you'd like to include, etc. Check out the [config docs](https://www.gatsbyjs.com/docs/reference/config-files/gatsby-config/) for more detail. -- **`gatsby-node.js`**: This file is where Gatsby expects to find any usage of the [Gatsby node APIs](https://www.gatsbyjs.com/docs/reference/config-files/gatsby-node/) (if any). These allow customization/extension of default Gatsby settings affecting pieces of the site build process. -- **`gatsby-ssr.js`**: This file is where Gatsby expects to find any usage of the [Gatsby server-side rendering APIs](https://www.gatsbyjs.com/docs/reference/config-files/gatsby-ssr/) (if any). These allow customization of default Gatsby settings affecting server-side rendering. -[Misc](https://www.gatsbyjs.com/docs/reference/gatsby-project-structure/#miscellaneous) -[Misc](https://www.gatsbyjs.com/docs/reference/gatsby-project-structure/#miscellaneous) ->>>>>>> master -The file/folder structure described above reflects Gatsby-specific files and folders. Since Gatsby sites are also React apps, it's common to use standard React code organization patterns such as folders like `/components` and `/utils` inside `/src`. The [React docs](https://reactjs.org/docs/faq-structure.html) have more information on a typical React app folder structure. ---- -<<<<<<< HEAD -# Layout Components | Gatsby -> ## Excerpt -> -======= -#### Layout Components | Gatsby -## Excerpt ->>>>>>> master -> In this guide, you'll learn Gatsby's approach to layouts, how to create and use layout components, and how to prevent layout components from… --- -In this guide, you'll learn Gatsby's approach to layouts, how to create and use layout components, and how to prevent layout components from unmounting. -<<<<<<< HEAD - -## [](https://www.gatsbyjs.com/docs/how-to/routing/layout-components/#gatsbys-approach-to-layouts)Gatsby's approach to layouts - -Gatsby does not, by default, automatically apply layouts to pages (there are, however, ways to do so which will be covered in a later section). Instead, Gatsby follows React's compositional model of importing and using components. This makes it possible to create multiple levels of layouts, e.g. a global header and footer, and then on some pages, a sidebar menu. It also makes it possible to pass data between layout and page components. - -## [](https://www.gatsbyjs.com/docs/how-to/routing/layout-components/#what-are-layout-components)What are layout components? - -Layout components are for sections of your site that you want to share across multiple pages. For example, Gatsby sites will commonly have a layout component with a shared header and footer. Other common things to add to layouts are a sidebar and/or navigation menu. On this page for example, the header at the top is part of gatsbyjs.com's layout component. +### Overview -## [](https://www.gatsbyjs.com/docs/how-to/routing/layout-components/#how-to-create-layout-components)How to create layout components +The **`_.get()` method** in Lodash retrieves the object’s value at a specific path. -======= -[Gatsby's approach to layouts](https://www.gatsbyjs.com/docs/how-to/routing/layout-components/#gatsbys-approach-to-layouts) -Gatsby does not, by default, automatically apply layouts to pages (there are, however, ways to do so which will be covered in a later section). Instead, Gatsby follows React's compositional model of importing and using components. This makes it possible to create multiple levels of layouts, e.g. a global header and footer, and then on some pages, a sidebar menu. It also makes it possible to pass data between layout and page components. -[What are layout components?](https://www.gatsbyjs.com/docs/how-to/routing/layout-components/#what-are-layout-components) -Layout components are for sections of your site that you want to share across multiple pages. For example, Gatsby sites will commonly have a layout component with a shared header and footer. Other common things to add to layouts are a sidebar and/or navigation menu. On this page for example, the header at the top is part of gatsbyjs.com's layout component. -[How to create layout components](https://www.gatsbyjs.com/docs/how-to/routing/layout-components/#how-to-create-layout-components) ->>>>>>> master -It is recommended to create your layout components alongside the rest of your components (e.g. into `src/components/`). -Here is an example of a very basic layout component at `src/components/layout.js`: -``` -import React from "react"export default function Layout({ children }) { return (
{children}
)} -``` -<<<<<<< HEAD +If the value is not present at the object’s specific path, it will be resolved as `undefined`. This method will return the default value if specified in such a case. -## [](https://www.gatsbyjs.com/docs/how-to/routing/layout-components/#how-to-import-and-add-layout-components-to-pages)How to import and add layout components to pages +### Syntax -======= -[](https://www.gatsbyjs.com/docs/how-to/routing/layout-components/#how-to-import-and-add-layout-components-to-pages)How to import and add layout components to pages ->>>>>>> master -If you want to apply a layout to a page, you will need to include the `Layout` component and wrap your page in it. For example, here is how you would apply your layout to the front page: -``` -import React from "react"import Layout from "../components/layout"export default function Home() { return (

I'm in a layout!

);} +```js +_.get(object, path, defaultValue) ``` -Repeat for every page and template that needs this layout. -<<<<<<< HEAD -## [](https://www.gatsbyjs.com/docs/how-to/routing/layout-components/#how-to-prevent-layout-components-from-unmounting)How to prevent layout components from unmounting - -======= -[How to prevent layout components from unmounting](https://www.gatsbyjs.com/docs/how-to/routing/layout-components/#how-to-prevent-layout-components-from-unmounting) ->>>>>>> master -As mentioned earlier, Gatsby does not, by default, automatically wrap pages in a layout component. The "top level" component is the page itself. As a result, when the "top level" component changes between pages, React will re-render all children. This means that shared components like navigations will unmount and remount. This will break CSS transitions or React state within those shared components. -If you need to set a wrapper component around page components that won't get unmounted on page changes, use the **`wrapPageElement`** [browser API](https://www.gatsbyjs.com/docs/reference/config-files/gatsby-browser/#wrapPageElement) and the [SSR equivalent](https://www.gatsbyjs.com/docs/reference/config-files/gatsby-ssr/#wrapPageElement). -Alternatively, you can prevent your layout component from unmounting by using [gatsby-plugin-layout](https://www.gatsbyjs.com/plugins/gatsby-plugin-layout/), which implements the `wrapPageElement` APIs for you. -<<<<<<< HEAD - -# Adding Markdown Pages | Gatsby +### Parameters -======= -## Adding Markdown Pages | Gatsby ->>>>>>> master -> ## Excerpt -> -> Gatsby can use Markdown files to create pages in your site. -> You add plugins to read and understand folders with Markdown files and from them… ---- -Gatsby can use Markdown files to create pages in your site. You add plugins to read and understand folders with Markdown files and from them create pages automatically. -Here are the steps Gatsby follows for making this happen. -1. Read files into Gatsby from the filesystem -2. Transform Markdown to HTML and [frontmatter](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#frontmatter-for-metadata-in-markdown-files) to data -3. Add a Markdown file -4. Create a Collection Route component for the Markdown files -<<<<<<< HEAD +This method accepts the following parameters: -## [](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#read-files-into-gatsby-from-the-filesystem)Read files into Gatsby from the filesystem +- **`object`**: The object in which the given path will be queried. +- **`path`**: The path used to retrieve the value from the object. +- **`defaultValue`**: The default value that will be returned for resolved values that are undefined. -Use the plugin [`gatsby-source-filesystem`](https://www.gatsbyjs.com/plugins/gatsby-source-filesystem/#gatsby-source-filesystem) to read files. +### Return value -## [](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#install)Install +This method will return the value at the specified path if found. Otherwise, it will return the default value if specified. -`npm install gatsby-source-filesystem` +### Example -## [](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#add-plugin)Add plugin +Let’s look at an example of the `_.get()` method in the code snippet below: -======= -[](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#read-files-into-gatsby-from-the-filesystem)Read files into Gatsby from the filesystem -Use the plugin [`gatsby-source-filesystem`](https://www.gatsbyjs.com/plugins/gatsby-source-filesystem/#gatsby-source-filesystem) to read files. -[](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#install)Install -`npm install gatsby-source-filesystem` -[Add Plugin](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#add-plugin)Add plugin ->>>>>>> master -Open `gatsby-config.js` to add the `gatsby-source-filesystem` plugin. The `path` option is how you set the directory to search for files. -``` -<<<<<<< HEAD -module.exports = { siteMetadata: { title: "My Gatsby Site", }, plugins: [ { resolve: `gatsby-source-filesystem`, options: { name: `markdown-pages`, path: `${__dirname}/src/markdown-pages`, }, }, ],} -======= -module.exports = { siteMetadata: { - title: "My Gatsby Site", }, -plugins: [ { - resolve: `gatsby-source-filesystem`, -options: { - name: `markdown-pages`, - path: `${__dirname}/src/markdown-pages`, -}, - }, -],} ->>>>>>> master -``` -Completing the above step means that you've "sourced" the Markdown files from the filesystem. You can now "transform" the Markdown to HTML and the YAML frontmatter to JSON. -<<<<<<< HEAD +### Explanation -## [](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#transform-markdown-to-html-and-frontmatter-to-data-using-gatsby-transformer-remark)Transform Markdown to HTML and frontmatter to data using `gatsby-transformer-remark` +In the HTML tab: -You'll use the plugin [`gatsby-transformer-remark`](https://www.gatsbyjs.com/plugins/gatsby-transformer-remark/) to recognize files which are Markdown and read their content. The plugin will convert the frontmatter metadata part of your Markdown files as `frontmatter` and the content part as HTML. +- **Line 5**: We import the `lodash` script. -## [](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#install-transformer-plugin)Install transformer plugin +In the JavaScript tab: -`npm install gatsby-transformer-remark` +- **Lines 2 to 15**: We create an object to perform a query. -## [](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#configure-plugin)Configure plugin +- **Line 18**: We define a variable `collegeYopPath` to get the value. -======= -[Transform Markdown to HTML and frontmatter to data using `gatsby-transformer-remark`](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#transform-markdown-to-html-and-frontmatter-to-data-using-gatsby-transformer-remark) -You'll use the plugin [`gatsby-transformer-remark`](https://www.gatsbyjs.com/plugins/gatsby-transformer-remark/) to recognize files which are Markdown and read their content. The plugin will convert the frontmatter metadata part of your Markdown files as `frontmatter` and the content part as HTML. -[Install transformer plugin](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#install-transformer-plugin) -`npm install gatsby-transformer-remark` -[Configure plugin](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#configure-plugin) ->>>>>>> master -Add this to `gatsby-config.js` after the previously added `gatsby-source-filesystem`. -``` -<<<<<<< HEAD -module.exports = { siteMetadata: { title: "My Gatsby Site", }, plugins: [ { resolve: `gatsby-source-filesystem`, options: { name: `markdown-pages`, path: `${__dirname}/src/markdown-pages`, }, }, `gatsby-transformer-remark`, ],} -``` +- **Lines 19**: We use the `_.get()` method and pass the `object`, `collegeYopPath`, and a default value as parameters. -## [](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#add-a-markdown-file)Add a Markdown file +- **Line 22**: We define a variable `falsyPath` to get the value. -Create a folder in the `/src` directory of your Gatsby application called `markdown-pages`. Now create a Markdown file inside it with the name `post-1.md`. +- **Lines 23**: We use the `_.get()` method and pass the `object`, `falsyPath` and a `default value` as parameters. -## [](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#frontmatter-for-metadata-in-markdown-files)Frontmatter for metadata in Markdown files +### Output -======= -module.exports = { siteMetadata: { - title: "My Gatsby Site", }, -plugins: [ { - resolve: `gatsby-source-filesystem`, -options: { - name: `markdown-pages`, - path: `${__dirname}/src/markdown-pages`, -}, - }, - `gatsby-transformer-remark`, ], -} -``` -[Add a Markdown file](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#add-a-markdown-file) -Create a folder in the `/src` directory of your Gatsby application called `markdown-pages`. Now create a Markdown file inside it with the name `post-1.md`. -[Frontmatter for metadata in Markdown files](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#frontmatter-for-metadata-in-markdown-files) ->>>>>>> master -When you create a Markdown file, you can include a set of key/value pairs that can be used to provide additional data relevant to specific pages in the GraphQL data layer. This data is called "frontmatter" and is denoted by the triple dashes at the start and end of the block. This block will be parsed by `gatsby-transformer-remark` as YAML. You can then query the data through the GraphQL API from your React components. -src/markdown-pages/post-1.md -``` ----slug: "/blog/my-first-post"date: "2019-05-04"title: "My first blog post"--- -``` -What is important in this step is the key pair `slug`. The value that is assigned to the key `slug` is used in order to navigate to your post. -<<<<<<< HEAD +- The `_.get()` method at **line 19** contains a valid path, and therefore the expression is resolved, and `2021` is printed on the console. +- The `_.get()` method at **Line 23** contains an invalid path, and therefore the expression is resolved as `undefined`. -## [](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#create-a-collection-route-for-the-markdown-files)Create a Collection Route for the Markdown files +## Technoloy +![tech-stack](https://github.com/bgoonz/BGOONZ_BLOG_2.0/blob/master/static/images/madewith.png?raw=true) -======= -[](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#create-a-collection-route-for-the-markdown-files)Create a Collection Route for the Markdown files ->>>>>>> master -Create `src/pages/{MarkdownRemark.frontmatter__slug}.js` and add the following code: -src/pages/{MarkdownRemark.frontmatter\_\_slug}.js -``` -<<<<<<< HEAD -import React from "react"import { graphql } from "gatsby"export default function Template({ data, }) { const { markdownRemark } = data const { frontmatter, html } = markdownRemark return (

{frontmatter.title}

{frontmatter.date}

)}export const pageQuery = graphql` query($id: String!) { markdownRemark(id: { eq: $id }) { html frontmatter { date(formatString: "MMMM DD, YYYY") slug title } } }` -======= -import React from "react" -import { graphql } from "gatsby"export default function Template({ data, }) { const { markdownRemark } = data const { frontmatter, html } = markdownRemark return (

{frontmatter.title}

{frontmatter.date}

)}export const pageQuery = graphql` query($id: String!) { markdownRemark(id: { - eq: $id }) { html frontmatter { date(formatString: "MMMM DD, YYYY") slug title } } }` ->>>>>>> master -``` -Two things are important in the file above: -1. A GraphQL query is made in the second half of the file to get the Markdown data. Gatsby has automagically given you all the Markdown metadata and HTML in this query's result. - **Note: To learn more about GraphQL, consider this [excellent resource](https://www.howtographql.com/)** -2. The result of the query is injected by Gatsby into the component as the `data` prop. `props.data.markdownRemark` is the property that has all the details of the Markdown file. -Next you could create a page component at `src/pages/blog/index.js` to serve as a listing page for all your blog posts. -This should get you started on some basic Markdown functionality in your Gatsby site. You can further customize the frontmatter and the component file to get desired effects! -For more information, have a look in the working example `using-markdown-pages`. You can find it in the [Gatsby examples section](https://github.com/gatsbyjs/gatsby/tree/master/examples). -<<<<<<< HEAD - -## [](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#other-tutorials)Other tutorials - -======= -[Other tutorials](https://www.gatsbyjs.com/docs/how-to/routing/adding-markdown-pages/#other-tutorials) ->>>>>>> master -
--- -<<<<<<< HEAD +## SOURCECODE -# Technoloy +--- -======= ### Overview + The **`_.get()` method** in Lodash retrieves the object’s value at a specific path. + If the value is not present at the object’s specific path, it will be resolved as `undefined`. This method will return the default value if specified in such a case. + ### Syntax + ```js _.get(object, path, defaultValue) ``` + ### Parameters + This method accepts the following parameters: -- **`object`**: The object in which the given path will be queried. -- **`path`**: The path used to retrieve the value from the object. -- **`defaultValue`**: The default value that will be returned for resolved values that are undefined. -### Return value -This method will return the value at the specified path if found. Otherwise, it will return the default value if specified. -### Example -Let’s look at an example of the `_.get()` method in the code snippet below: -### Explanation -In the HTML tab: -- **Line 5**: We import the `lodash` script. -In the JavaScript tab: -- **Lines 2 to 15**: We create an object to perform a query. -- **Line 18**: We define a variable `collegeYopPath` to get the value. -- **Lines 19**: We use the `_.get()` method and pass the `object`, `collegeYopPath`, and a default value as parameters. -- **Line 22**: We define a variable `falsyPath` to get the value. -- **Lines 23**: We use the `_.get()` method and pass the `object`, `falsyPath` and a `default value` as parameters. -### Output -- The `_.get()` method at **line 19** contains a valid path, and therefore the expression is resolved, and `2021` is printed on the console. -- The `_.get()` method at **Line 23** contains an invalid path, and therefore the expression is resolved as `undefined`. -## Technoloy ->>>>>>> master -![tech-stack](https://github.com/bgoonz/BGOONZ_BLOG_2.0/blob/master/static/images/madewith.png?raw=true) ---- -<<<<<<< HEAD -# SOURCECODE +- **`object`**: The object in which the given path will be queried. +- **`path`**: The path used to retrieve the value from the object. +- **`defaultValue`**: The default value that will be returned for resolved values that are undefined. -======= -## SOURCECODE ---- -### Overview -The **`_.get()` method** in Lodash retrieves the object’s value at a specific path. -If the value is not present at the object’s specific path, it will be resolved as `undefined`. This method will return the default value if specified in such a case. -### Syntax -```js -_.get(object, path, defaultValue) -``` -### Parameters -This method accepts the following parameters: -- **`object`**: The object in which the given path will be queried. -- **`path`**: The path used to retrieve the value from the object. -- **`defaultValue`**: The default value that will be returned for resolved values that are undefined. ### Return value + This method will return the value at the specified path if found. Otherwise, it will return the default value if specified. + ### Example + Let’s look at an example of the `_.get()` method in the code snippet below: + ### Explanation + In the HTML tab: -- **Line 5**: We import the `lodash` script. + +- **Line 5**: We import the `lodash` script. + In the JavaScript tab: -- **Lines 2 to 15**: We create an object to perform a query. -- **Line 18**: We define a variable `collegeYopPath` to get the value. -- **Lines 19**: We use the `_.get()` method and pass the `object`, `collegeYopPath`, and a default value as parameters. -- **Line 22**: We define a variable `falsyPath` to get the value. -- **Lines 23**: We use the `_.get()` method and pass the `object`, `falsyPath` and a `default value` as parameters. + +- **Lines 2 to 15**: We create an object to perform a query. + +- **Line 18**: We define a variable `collegeYopPath` to get the value. + +- **Lines 19**: We use the `_.get()` method and pass the `object`, `collegeYopPath`, and a default value as parameters. + +- **Line 22**: We define a variable `falsyPath` to get the value. + +- **Lines 23**: We use the `_.get()` method and pass the `object`, `falsyPath` and a `default value` as parameters. + ### Output -- The `_.get()` method at **line 19** contains a valid path, and therefore the expression is resolved, and `2021` is printed on the console. -- The `_.get()` method at **Line 23** contains an invalid path, and therefore the expression is resolved as `undefined`. + +- The `_.get()` method at **line 19** contains a valid path, and therefore the expression is resolved, and `2021` is printed on the console. +- The `_.get()` method at **Line 23** contains an invalid path, and therefore the expression is resolved as `undefined`. + --- ->>>>>>> master ``` + bryan@LAPTOP-9LGJ3JGS:/c/MY-WEB-DEV/BLOG____2.0/BLOG_2.0/src$ tree -f . ├── ./components @@ -4502,21 +2935,18 @@ bryan@LAPTOP-9LGJ3JGS:/c/MY-WEB-DEV/BLOG____2.0/BLOG_2.0/src$ tree -f ├── ./utils/toStyleObj.js ├── ./utils/toUrl.js └── ./utils/withPrefix.js + 21 directories, 119 files bryan@LAPTOP-9LGJ3JGS:/c/MY-WEB-DEV/BLOG____2.0/BLOG_2.0/src$ ``` --- -<<<<<<< HEAD - -# Source Code -======= ## Source Code ->>>>>>> master
+ Folder Structure (src) + - Folder Structure (src) ``` . ├── Combined_____-_____Doc.md @@ -4823,21 +3253,17 @@ bryan@LAPTOP-9LGJ3JGS:/c/MY-WEB-DEV/BLOG____2.0/BLOG_2.0/src$ ├── toStyleObj.js ├── toUrl.js └── withPrefix.js + 32 directories, 272 files ``` +
Click To See Component Sourcecode -<<<<<<< HEAD - -# Component Structure - -======= ## Component Structure ->>>>>>> master ``` . ├── ActionLink.js @@ -4859,17 +3285,17 @@ bryan@LAPTOP-9LGJ3JGS:/c/MY-WEB-DEV/BLOG____2.0/BLOG_2.0/src$ ├── Submenu.js ├── global.css └── index.js + ``` + --- + ```js import React from 'react'; import _ from 'lodash'; -<<<<<<< HEAD - -======= ->>>>>>> master import { Link, withPrefix, classNames } from '../utils'; import Icon from './Icon'; + export default class ActionLink extends React.Component { render() { let action = _.get(this.props, 'action', null); @@ -4888,7 +3314,7 @@ export default class ActionLink extends React.Component { 'button-icon': _.get(action, 'style', null) === 'icon' })} > - {_.get(action, 'style', null) === 'icon' &&_.get(action, 'icon_class', null) ? ( + {_.get(action, 'style', null) === 'icon' && _.get(action, 'icon_class', null) ? ( {_.get(action, 'label', null)} @@ -4901,14 +3327,8 @@ export default class ActionLink extends React.Component { } } ``` ---- -<<<<<<< HEAD - -```js -import React from 'react'; -import _ from 'lodash'; -======= +--- ### Table of Contents - [getPage][1] - [Parameters][2] @@ -4918,25 +3338,40 @@ import _ from 'lodash'; - [Parameters][6] - [Examples][7] ## getPage + Get the page at the provided `urlPath`. + ### Parameters -- `pages` **[Array][8]** Array of page objects. All pages must have 'url' field. -- `urlPath` **[string][9]** The url path to find the page by + +- `pages` **[Array][8]** Array of page objects. All pages must have 'url' field. +- `urlPath` **[string][9]** The url path to find the page by + Returns **[Object][10]** + ## getPageByFilePath + Get the page at the provided `filePath`. + ### Parameters -- `pages` **[Array][8]** Array of page objects. All pages must have 'url' field. -- `filePath` **[string][9]** The file path to find the page by + +- `pages` **[Array][8]** Array of page objects. All pages must have 'url' field. +- `filePath` **[string][9]** The file path to find the page by + Returns **[Object][10]** + ## getPages + Get all the pages located under the provided `urlPath`, not including the index page. I.e.: All pages having their URLs start with `urlPath` excluding the page having its URL equal to `urlPath`. + ### Parameters -- `pages` **[Array][8]** Array of page objects. All pages must have 'url' field. -- `urlPath` **[string][9]** The url path to filter pages by + +- `pages` **[Array][8]** Array of page objects. All pages must have 'url' field. +- `urlPath` **[string][9]** The url path to filter pages by + ### Examples + ```javascript pages => [ {url: '/'}, @@ -4945,13 +3380,16 @@ pages => [ {url: '/posts/hello'}, {url: '/posts/world'} ] + getPages(pages, /posts') => [ {url: '/posts/hello'}, {url: '/posts/world'} ] ``` + Returns **[Array][8]** + [1]: #getpage [2]: #parameters [3]: #getpagebyfilepath @@ -4962,15 +3400,16 @@ Returns **[Array][8]** [8]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array [9]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String [10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object + ```js import React from 'react'; import_ from 'lodash'; ->>>>>>> master import { Link, withPrefix, classNames } from '../utils'; + export default class CtaButtons extends React.Component { render() { let actions = _.get(this.props, 'actions', null); -return_.map(actions, (action, action_idx) => ( + return _.map(actions, (action, action_idx) => ( ( } : null)} className={classNames({ -button:_.get(action, 'style', null) === 'primary' || _.get(action, 'style', null) === 'secondary', -'button-secondary':_.get(action, 'style', null) === 'secondary' + button: _.get(action, 'style', null) === 'primary' || _.get(action, 'style', null) === 'secondary', + 'button-secondary': _.get(action, 'style', null) === 'secondary' })} > {_.get(action, 'label', null)} @@ -4991,21 +3430,19 @@ button:_.get(action, 'style', null) === 'primary' || _.get(action, 'style', null } } ``` + --- + ```js import React from 'react'; -<<<<<<< HEAD -import _ from 'lodash'; - -======= import_ from 'lodash'; ->>>>>>> master import { getPage, classNames, Link, withPrefix, pathJoin, getPages } from '../utils'; import DocsSubmenu from './DocsSubmenu'; + export default class DocsMenu extends React.Component { render() { let site = _.get(this.props, 'site', null); -let page =_.get(this.props, 'page', null); + let page = _.get(this.props, 'page', null); let root_docs_path = _.get(site, 'data.doc_sections.root_docs_path', null); let root_page = getPage(this.props.pageContext.pages, root_docs_path); return ( @@ -5019,7 +3456,7 @@ let page =_.get(this.props, 'page', null);
- -
- Click To See Template Sourcecode - -# Templates - -``` - -├── advanced.js -├── blog.js -├── docs.js -├── page.js -└── post.js -``` - -```js -import React from 'react'; -import _ from 'lodash'; -import { graphql } from 'gatsby'; - -import components, { Layout } from '../components/index'; - -// this minimal GraphQL query ensures that when 'gatsby develop' is running, -// any changes to content files are reflected in browser -export const query = graphql` - query ($url: String) { - sitePage(path: { eq: $url }) { - id - } - } -`; - -export default class Advanced extends React.Component { - render() { - return ( - - {_.map(_.get(this.props, 'pageContext.frontmatter.sections', null), (section, section_idx) => { - let component = _.upperFirst(_.camelCase(_.get(section, 'type', null))); - let Component = components[component]; - return ; - })} - - ); - } -} -``` - ---- - -```js -import React from 'react'; -import _ from 'lodash'; -import moment from 'moment-strftime'; -import { graphql } from 'gatsby'; - -import { Layout } from '../components/index'; -import { toStyleObj, withPrefix, getPages, Link } from '../utils'; - -// this minimal GraphQL query ensures that when 'gatsby develop' is running, -// any changes to content files are reflected in browser -export const query = graphql` - query ($url: String) { - sitePage(path: { eq: $url }) { - id - } - } -`; - -export default class Blog extends React.Component { - render() { - let display_posts = _.orderBy(getPages(this.props.pageContext.pages, '/blog'), 'frontmatter.date', 'desc'); - return ( - -
- {_.get(this.props, 'pageContext.frontmatter.image', null) && ( -
- )} -
-

{_.get(this.props, 'pageContext.frontmatter.title', null)}

- {_.get(this.props, 'pageContext.frontmatter.subtitle', null) && ( -

{_.get(this.props, 'pageContext.frontmatter.subtitle', null)}

- )} -
-
-
-
- {_.map(display_posts, (post, post_idx) => ( -
- {_.get(post, 'frontmatter.thumb_image', null) && ( - - {_.get(this.props, - - )} -
-
- -
-

- - {_.get(post, 'frontmatter.title', null)} - -

-
- {_.get(post, 'frontmatter.excerpt', null) && ( - -

{_.get(post, 'frontmatter.excerpt', null)}

- {_.get(this.props, 'pageContext.frontmatter.has_more_link', null) === true && - _.get(this.props, 'pageContext.frontmatter.more_link_text', null) && ( -

- - {_.get(this.props, 'pageContext.frontmatter.more_link_text', null)} - -

- )} -
- )} -
- ))} -
-
-
- ); - } -} -``` - ---- - -```js -import React from 'react'; -import _ from 'lodash'; -import { graphql } from 'gatsby'; - -import { Layout } from '../components/index'; -import DocsMenu from '../components/DocsMenu'; -import { htmlToReact, getPages, Link, withPrefix } from '../utils'; - -// this minimal GraphQL query ensures that when 'gatsby develop' is running, -// any changes to content files are reflected in browser -export const query = graphql` - query ($url: String) { - sitePage(path: { eq: $url }) { - id - } - } -`; - -export default class Docs extends React.Component { - render() { - let root_docs_path = _.trim(_.get(this.props, 'pageContext.site.data.doc_sections.root_docs_path', null), '/'); - let current_page_url = _.trim(_.get(this.props, 'pageContext.url', null), '/'); - return ( - -
-
- -
-
-
-

{_.get(this.props, 'pageContext.frontmatter.title', null)}

-
-
- {htmlToReact(_.get(this.props, 'pageContext.html', null))} - {root_docs_path !== current_page_url && - (() => { - let child_pages = _.orderBy(getPages(this.props.pageContext.pages, current_page_url), 'frontmatter.weight'); - let child_count = _.size(child_pages); - let has_children = child_count > 0 ? true : false; - return ( - - {has_children && ( -
    - {_.map(child_pages, (child_page, child_page_idx) => ( -
  • - - {_.get(child_page, 'frontmatter.title', null)} -
  • - ))} -
- )} -
- ); - })()} -
-
-
- -
-
-
- ); - } -} -``` - ---- - -```js -import React from 'react'; -import _ from 'lodash'; -import { graphql } from 'gatsby'; - -import { Layout } from '../components/index'; -import { toStyleObj, withPrefix, htmlToReact } from '../utils'; - -// this minimal GraphQL query ensures that when 'gatsby develop' is running, -// any changes to content files are reflected in browser -export const query = graphql` - query ($url: String) { - sitePage(path: { eq: $url }) { - id - } - } -`; - -export default class Page extends React.Component { - render() { - return ( - -
-
- {_.get(this.props, 'pageContext.frontmatter.image', null) && ( -
- )} -
-

{_.get(this.props, 'pageContext.frontmatter.title', null)}

- {_.get(this.props, 'pageContext.frontmatter.subtitle', null) && ( -
{htmlToReact(_.get(this.props, 'pageContext.frontmatter.subtitle', null))}
- )} -
-
-
-
{htmlToReact(_.get(this.props, 'pageContext.html', null))}
-
-
-
- ); - } -} -``` - ---- - -```js -import React from 'react'; -import _ from 'lodash'; -import moment from 'moment-strftime'; -import { graphql } from 'gatsby'; - -import { Layout } from '../components/index'; -import { toStyleObj, withPrefix, htmlToReact } from '../utils'; - -// this minimal GraphQL query ensures that when 'gatsby develop' is running, -// any changes to content files are reflected in browser -export const query = graphql` - query ($url: String) { - sitePage(path: { eq: $url }) { - id - } - } -`; - -export default class Post extends React.Component { - render() { - return ( - -
-
- {_.get(this.props, 'pageContext.frontmatter.image', null) && ( -
- )} -
-
- -
-

{_.get(this.props, 'pageContext.frontmatter.title', null)}

- {_.get(this.props, 'pageContext.frontmatter.subtitle', null) && ( -
{htmlToReact(_.get(this.props, 'pageContext.frontmatter.subtitle', null))}
- )} -
-
-
-
{htmlToReact(_.get(this.props, 'pageContext.html', null))}
-
-
-
- ); - } -} -``` - -
diff --git a/TODO.md b/TODO.md index eb12cf4b37..e9ac87d0d9 100644 --- a/TODO.md +++ b/TODO.md @@ -1,9 +1,15 @@ -# ToDo: +# To Do -1. embed this [tool](https://bgoonz.github.io/html-2-md-converter/) -2. Fix broken Links -3. Algolia Search -4. Visitor Content Authoring. -5. Dark Mode -6. https://github.com/bgoonz/MainBlogContent -7. Gatsby plugin Algolia +1. embed this [tool](https://bgoonz.github.io/html-2-md-converter/)✅ +2. Fix broken Links✅ +3. Algolia Search +4. Visitor Content Authoring.✅ +5. Dark Mode +6. {add content repo]() +7. Add vercel and other backups to readme or internal use page if it exists +8. [gh pages](https://bgoonz.github.io/BGOONZ_BLOG_2.0/) ✅ +9. -[Other repo 1](https://github.com/BGOOONZ-BLOG/bgoonz-blog2.0-v-5)✅ +10. Fix blog images and get rid of duplicates +11. add copy to clipboard to codeblocks +12. get prism or some sort of syntax highlighting working +13. diff --git a/bash-commands.md b/bash-commands.md index b181fe5918..7b0b027884 100644 --- a/bash-commands.md +++ b/bash-commands.md @@ -2,8 +2,8 @@
- Bash Cheat Sheet (MY COMMANDS) + Bash Cheat Sheet (MY COMMANDS) - - > - - - #### Find ## To find files by case-insensitive extension (ex: .jpg, .JPG, .jpG) @@ -1306,7 +1299,7 @@ echo ' ' # awk '{print "
  • "}; - # {print " ",$1,"
  •  "}' \ $listing + # {print " ",$1," "}' \ $listing echo "" @@ -1418,7 +1411,7 @@ echo ' ' # awk '{print "
  • "}; - # {print " ",$1,"
  •  "}' \ $listing + # {print " ",$1," "}' \ $listing echo "" diff --git a/docs/README.md b/docs/README.md index 9320a43f7d..927190a515 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,30 +1,20 @@ -# Bgoonz Blog Readme: +# Bgoonz Blog Readme ### [Github Org Link](https://github.com/BGOOONZ-BLOG/) ## [CHANGELOG](./CHANGELOG.md) -##### [Cloudfare-Backup](https://bgoonz-blog-2-0.pages.dev/) +##### [Cloudfare-Backup](https://bgoonz-blog-2-0.pages.dev/)⇨ [search](https://www.algolia.com/realtime-search-demo/web-dev-resource-hub-9e6b8aa8-6106-44c5-9f59-ff3f9531abd4) ⇨ [Backup Repo Deploy](https://bgoonzblog20-backup.netlify.app/#gsc.tab=0) ⇨ [Github pages](https://bgoonz.github.io/BGOONZ_BLOG_2.0/)⇨ [Go To Site Wiki](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki) ⇨ [Gatsby Cloud Version](https://bgoonzblog20master.gtsb.io/)⇨ [Vercel Version](https://bgoonz-blog-2-0.vercel.app/)⇨ [Cloudfare-Domain](www.webdevhub.us) ⇨ [gh-pages](https://bgoonz.github.io/BGOONZ_BLOG_2.0/) -⇨ [search](https://www.algolia.com/realtime-search-demo/web-dev-resource-hub-9e6b8aa8-6106-44c5-9f59-ff3f9531abd4) ⇨ [Backup Repo Deploy](https://bgoonzblog20-backup.netlify.app/#gsc.tab=0) ⇨ [Github pages](https://bgoonz.github.io/BGOONZ_BLOG_2.0/) - -⇨ [Go To Site Wiki](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki) ⇨ [Gatsby Cloud Version](https://bgoonzblog20master.gtsb.io/) - -⇨ [Vercel Version](https://bgoonz-blog-2-0.vercel.app/) - -⇨ [Cloudfare-Domain](www.webdevhub.us) ⇨ [gh-pages](https://bgoonz.github.io/BGOONZ_BLOG_2.0/) +###### [⇨Privacy policy⇦](https://codepen.io/bgoonz/pen/LYLJZrW) ### Repos -- [Alt Backup](https://github.com/BGOOONZ-BLOG/bgoonz-blog2.0-v-5) -- [Blog Content](https://github.com/bgoonz/MainBlogContent) - -###### [⇨Privacy policy⇦](https://codepen.io/bgoonz/pen/LYLJZrW) - - -![preview](https://github.com/bgoonz/BGOONZ_BLOG_2.0/blob/master/static/images/blog-may-2022.png?raw=true) +- [Alt Backup](https://github.com/BGOOONZ-BLOG/bgoonz-blog2.0-v-5) +- [Blog Content](https://github.com/bgoonz/MainBlogContent) --- + ## Useful Commands (internal use) ```bash @@ -39,9 +29,8 @@ git merge fixy # and merge in the fixed branch git push # done, no need to force push! - -![preview](https://github.com/bgoonz/BGOONZ_BLOG_2.0/blob/master/static/images/blog-may-2022.png?raw=true) + git checkout 307a5cd # check out the commit that you want to reset to git checkout -b fixy # create a branch named fixy to do the work @@ -51,9 +40,9 @@ git merge fixy # and merge in the fixed branch git push # done, no need to force push! +npm i @stackbit/gatsby-plugin-menus babel-runtime chokidar classnames fs-extra gatsby gatsby-image gatsby-plugin-netlify gatsby-plugin-netlify-cms gatsby-plugin-sass gatsby-plugin-react-helmet gatsby-plugin-typescript --legacy-peer-deps ``` -npm i @stackbit/gatsby-plugin-menus babel-runtime chokidar classnames fs-extra gatsby gatsby-image gatsby-plugin-netlify gatsby-plugin-netlify-cms gatsby-plugin-sass gatsby-plugin-react-helmet gatsby-plugin-typescript --legacy-peer-deps --- @@ -62,11 +51,17 @@ npm i @stackbit/gatsby-plugin-menus babel-runtime chokidar classnames fs-extra g [![gmail](https://img.icons8.com/color/96/000000/gmail.png)](mailto:bryan.guner@gmail.com)[![linkedin](https://img.icons8.com/color/96/000000/linkedin.png) ](https://www.linkedin.com/in/bryan-guner-046199128/)
    -Web Dev Setup + + +Web Dev Setup + + + [webpack](https://webpack.js.org/) ## Basic Web Development Environment Setup + Windows Subsystem for Linux (WSL) and Ubuntu --- @@ -82,92 +77,89 @@ Artificial neural networks, usually simply called neural networks, are computing Open Menu -- [Navigation](/docs/sitemap) Sub-menu -- [Docs](/docs) -- [Showcase](/showcase) -- [Contact!](/docs/faq/contact) -- [Python](/docs/python/python-ds) -- [JavaScript](/javascript) -- [Blog](/blog/) +- [Navigation](/docs/sitemap) Sub-menu +- [Docs](/docs) +- [Showcase](/showcase) +- [Contact!](/docs/faq/contact) +- [Python](/docs/python/python-ds) +- [JavaScript](/javascript) +- [Blog](/blog/) Sub-menu -- [Blog-Post-Archive](https://bgoonz.blogspot.com/) +- [Blog-Post-Archive](https://bgoonz.blogspot.com/) -- [Top Blog Posts](https://blog-w-comments.vercel.app/) +- [Top Blog Posts](https://blog-w-comments.vercel.app/) -- [Blog w Comments](/blogWcomments/) +- [Blog w Comments](/blogWcomments/) -- [Job Search](/docs/career/) +- [Job Search](/docs/career/) Sub-menu -- [Job Boards](/docs/career/job-boards) -- [Do's and Don'ts of interviews](/interview/dos-and-donts) -- [Career-Tips](https://bgoonz-blog.netlify.app/docs/career/) - -- [Interview Questions](/docs/interview/interview-questions) -- [Archive](/docs/archive) Sub-menu -- [Resource-Archive-Server](https://github.com/bgoonz/Learning-Assets) -- [Bootcamp Resources](https://lambda-resources.netlify.app/) +- [Job Boards](/docs/career/job-boards) +- [Do's and Don'ts of interviews](/interview/dos-and-donts) +- [Career-Tips](https://bgoonz-blog.netlify.app/docs/career/) -- [Web Dev Setup](https://bgoonz-blog.netlify.app/blog/webdev-setup/) +- [Interview Questions](/docs/interview/interview-questions) +- [Archive](/docs/archive) Sub-menu +- [Resource-Archive-Server](https://github.com/bgoonz/Learning-Assets) +- [Bootcamp Resources](https://lambda-resources.netlify.app/) +- [Web Dev Setup](https://bgoonz-blog.netlify.app/blog/webdev-setup/) -- [Top Repos](/docs) -- [MY_DOCS](https://bryan-guner.gitbook.io/my-docs/) - +- [Top Repos](/docs) +- [MY_DOCS](https://bryan-guner.gitbook.io/my-docs/) --- -- [WebAudioLab](https://bgoonz.github.io/WebAudioDaw/) - +- [WebAudioLab](https://bgoonz.github.io/WebAudioDaw/) -- [Condensed -Portfolio](https://bg-portfolio.netlify.app/) +- [Condensed -Portfolio](https://bg-portfolio.netlify.app/) -- [Family Promise Tracker](https://a.familypromiseservicetracker.dev/) +- [Family Promise Tracker](https://a.familypromiseservicetracker.dev/) -- [DTW-Guitar-FX-Automation](https://github.com/bgoonz/Revamped-Automatic-Guitar-Effect-Triggering) -- [Embeds Blog](https://bgoonz-blog-v3-0.netlify.app/embeds/) +- [DTW-Guitar-FX-Automation](https://github.com/bgoonz/Revamped-Automatic-Guitar-Effect-Triggering) +- [Embeds Blog](https://bgoonz-blog-v3-0.netlify.app/embeds/) -- [alt-blogs](https://bgoonz-blog-v3-0.netlify.app/) +- [alt-blogs](https://bgoonz-blog-v3-0.netlify.app/) -- [Games](https://bgoonz-games.netlify.app/) +- [Games](https://bgoonz-games.netlify.app/) -- [Blog Backup](https://bgoonz-blog-v3-0.netlify.app/) +- [Blog Backup](https://bgoonz-blog-v3-0.netlify.app/) -- [Cover Letter](https://bgoonz-cv.netlify.app/) +- [Cover Letter](https://bgoonz-cv.netlify.app/) -- [Project Centric](https://project-portfolio42.netlify.app/) +- [Project Centric](https://project-portfolio42.netlify.app/) -- [Wordpress Blog](https://bgoonz-blog.netlify.app/) +- [Wordpress Blog](https://bgoonz-blog.netlify.app/) -- [Project Portfolio Gallery](https://project-portfolio42.netlify.app/) +- [Project Portfolio Gallery](https://project-portfolio42.netlify.app/) -- [github-stats-website](https://bgoonz.github.io/github-stats-website/) +- [github-stats-website](https://bgoonz.github.io/github-stats-website/) -- [Admin](https://bgoonz-blog.netlify.app/admin/) +- [Admin](https://bgoonz-blog.netlify.app/admin/) Sub-menu -- [Write Docs](https://bgoonz-blog.netlify.app/admin/#/collections/docs) -- [Write Blog](https://bgoonz-blog.netlify.app/admin/#/collections/blog/new) -- [Webmaster](https://bgoonz-blog.netlify.app/admin/#/collections/blog/new) -- [Tools](/docs/tools) Sub-menu -- [Github HTML Previewer](https://githtmlpreview.netlify.app/) +- [Write Docs](https://bgoonz-blog.netlify.app/admin/#/collections/docs) +- [Write Blog](https://bgoonz-blog.netlify.app/admin/#/collections/blog/new) +- [Webmaster](https://bgoonz-blog.netlify.app/admin/#/collections/blog/new) +- [Tools](/docs/tools) Sub-menu +- [Github HTML Previewer](https://githtmlpreview.netlify.app/) -- [Text Tools](https://devtools42.netlify.app/) +- [Text Tools](https://devtools42.netlify.app/) -- [Ternary 2 If Else](https://ternary42.netlify.app/) +- [Ternary 2 If Else](https://ternary42.netlify.app/) -- [Web Dev Utility Tools](/hps://web-dev-utility-tools-bgoonz.netlify.app/) +- [Web Dev Utility Tools](/hps://web-dev-utility-tools-bgoonz.netlify.app/) -- [Setup Checker](https://github.com/bgoonz/web-dev-setup-checker) -- [PotluckPlanner](https://potluck-landing.netlify.app/) +- [Setup Checker](https://github.com/bgoonz/web-dev-setup-checker) +- [PotluckPlanner](https://potluck-landing.netlify.app/) -- [WebDev Quizzes](https://web-dev-interview-prep-quiz-website.netlify.app/) +- [WebDev Quizzes](https://web-dev-interview-prep-quiz-website.netlify.app/) -- [Github-Advanced-Search](https://github.com/search/advanced) +- [Github-Advanced-Search](https://github.com/search/advanced) Close Menu _🔎_ Search @@ -185,6 +177,7 @@ git add . git commit -m"update" git push -u origin gh-pages ``` + ```bash git init git add . @@ -195,6 +188,7 @@ git push -u origin preview [](https://webpack.js.org/) > Notes: + ###### code ```bash @@ -270,6 +264,7 @@ git add . git commit -m"update" git push -u origin gh-pages ``` + ```bash git init git add . @@ -284,6 +279,7 @@ git push -u origin preview ### [Convolutional Neural Networks](/neural networks) > Notes: + ###### code ### [Jamstack](/jamstack) @@ -500,7 +496,13 @@ get in touch! +1 (551) - 254 - 5505 [GitHub](https://github.com/bgoonz) [Youtube](https://www.youtube.com/channel/UC9-rYyUMsnEBK8G8fCyrXXA) [Instagram](https://www.instagram.com/bgoonz/?hl=en) [dev.to](https://dev.to/bgoonz) - Bash Commands + + + Bash Commands + + + + ## My Commands ## # Find # To find files by case-insensitive extension (ex: .jpg, .jpg, .jpG) @@ -539,7 +541,7 @@ find . -type f -exec chmod 644 {} \; ## Description: need to : `sudo apt install rename` > Notes: Issue when renaming file without numbers collides with existing file name... ## # code -````console +````shell find $dir -type f | sed 's|\(.*/\)[^A-Z]*\([A-Z].*\)|mv \"&\" \"\1\2\"|' | sh find $dir -type d | sed 's|\(.*/\)[^A-Z]*\([A-Z].*\)|mv \"&\" \"\1\2\"|' | sh for i in *.html; do mv "$i" "${i%-*}.html"; done @@ -551,29 +553,44 @@ let cat = require('child_process') .toString('UTF-8'); fs.writeFile('output.md', cat, err => { ```` + # 2. Download Website Using Wget + > Notes: ==> sudo apt install wget -wget --limit-rate=200k --no-clobber --convert-links --random-wait -r -p -E -e robots=off -U mozilla https://bootcamp42.gitbook.io/python/ +wget --limit-rate=200k --no-clobber --convert-links --random-wait -r -p -E -e robots=off -U mozilla + # 3. Clean Out Messy Git Repo + ## Description: recursively removes git related folders as well as internal use files / attributions in addition to empty folders + > Notes: To clear up clutter in repositories that only get used on your local machine. find . -empty -type d -print -delete find . \( -name ".git" -o -name ".gitignore" -o -name ".gitmodules" -o -name ".gitattributes" \) -exec rm -rf -- {} + find . \( -name "*SECURITY.txt" -o -name "*RELEASE.txt" -o -name "*CHANGELOG.txt" -o -name "*LICENSE.txt" -o -name "*CONTRIBUTING.txt" -name "*HISTORY.md" -o -name "*LICENSE" -o -name "*SECURITY.md" -o -name "*RELEASE.md" -o -name "*CHANGELOG.md" -o -name "*LICENSE.md" -o -name "*CODE_OF_CONDUCT.md" -o -name "*CONTRIBUTING.md" \) -exec rm -rf -- {} + + # 4. clone all of a user's git repositories + ## Description: clone all of a user or organization's git repositories + # Generalized + CNTX={users|orgs}; NAME={username|orgname}; PAGE=1 -curl "https://api.github.com/$CNTX/$NAME/repos?page=$PAGE&per_page=100" | +curl "$CNTX/$NAME/repos?page=$PAGE&per_page=100" | + # Clone all Git User + CNTX={users}; NAME={bgoonz}; PAGE=1 + # Clone all Git Organization + CNTX={organizations}; NAME={TheAlgorithms}; PAGE=1 -curl "https://api.github.com/$CNTX/$NAME/repos?page=$PAGE&per_page=200"?branch=master | +curl "$CNTX/$NAME/repos?page=$PAGE&per_page=200"?branch=master | grep -e 'git_url*' | cut -d \" -f 4 | xargs -L1 git clone + # 5. Git Workflow + git push -u origin master git push -u origin main git push -u origin bryan-guner @@ -582,21 +599,32 @@ git init git add . git commit -m"update" git push -u origin preview + # 6. Recursive Unzip In Place + ## Description: recursively unzips folders and then deletes the zip file by the same name + find . -name "*.zip" | while read filename; do unzip -o -d "`dirname "$filename"`" "$filename"; done; find . -name "*.zip" -type f -print -delete + # 7. git pull keeping local changes + git stash git pull git stash pop + # 8. Prettier Code Formatter + sudo npm i prettier -g + # 9. Pandoc + find ./ -iname "*.md" -type f -exec sh -c 'pandoc --standalone "${0}" -o "${0%.md}.html"' {} \; find ./ -iname "*.html" -type f -exec sh -c 'pandoc --wrap=none --from html --to markdown_strict "${0}" -o "${0%.html}.md"' {} \; find ./ -iname "*.docx" -type f -exec sh -c 'pandoc "${0}" -o "${0%.docx}.md"' {} \; + # 10. Gitpod Installs + sudo apt install tree sudo apt install pandoc -y sudo apt install rename -y @@ -608,10 +636,15 @@ npm i npm-recursive-install -g black . prettier --write . npm-recursive-install + # 11. Repo Utils Package + ## Description: my standard repo utis package + npm i @bgoonz11/repoutils + # 12. Unix Tree Package Usage + tree -d -I 'node_modules' tree -I 'node_modules' tree -f -I 'node_modules' > TREE.md @@ -619,27 +652,36 @@ tree -f -L 2 > README.md tree -f -I 'node_modules' > listing-path.md tree -f -I 'node_modules' -d > TREE.md tree -f > README.md + # 13. Find & Replace string in file & folder names recursively + find . -type f -exec rename 's/string1/string2/g' {} + find . -type f -exec rename 's/\.download//g' {} + find . -type d -exec rename 's/-main//g' {} + -rename 's/\.js\.download$/.js/' *.js\.download -rename 's/\.html\.markdown$/.md/' *.html\.markdown +rename 's/\.js\.download$/.js/'*.js\.download +rename 's/\.html\.markdown$/.md/'*.html\.markdown find . -type d -exec rename 's/es6//g' {} + + # 14. Remove double extensions -for file in *.md.md + +for file in*.md.md mv "${file}" "${file%.md}" -for file in *.html.html +for file in*.html.html mv "${file}" "${file%.html}" -for file in *.html.png -for file in *.jpg.jpg +for file in*.html.png +for file in*.jpg.jpg do mv "${file}" "${file%.png}" done + # 15. Truncate folder names down to 12 characters + for d in ./*; do mv $d ${d:0:12}; done + # 16.Appendir.js + ## Description: combine the contents of every file in the contaning directory + > Notes: this includes the contents of the file it's self... //APPEND-DIR.js const fs = require('fs'); @@ -647,12 +689,17 @@ let cat = require('child_process').execSync('cat *').toString('UTF-8'); fs.writeFile('output.md', cat, (err) => { if (err) throw err; }); + # 17. Replace space in filename with underscore + ## Description: followed by replace `'#' with '_'` in directory name + > Notes: Can be re-purposed to find and replace any set of strings in file or folder names. -find . -name "* *" -type f | rename 's/_//g' +find . -name "**" -type f | rename 's/_//g' find . -name "* *" -type d | rename 's/#/_/g' + # 18. Filter & delete files by name and extension + find . -name '.bin' -type d -prune -exec rm -rf '{}' + find . -name '*.html' -type d -prune -exec rm -rf '{}' + find . -name 'nav-index' -type d -prune -exec rm -rf '{}' + @@ -660,18 +707,24 @@ find . -name 'node-gyp' -type d -prune -exec rm -rf '{}' + find . -name 'deleteme.txt' -type f -prune -exec rm -rf '{}' + find . -name 'right.html' -type f -prune -exec rm -rf '{}' + find . -name 'left.html' -type f -prune -exec rm -rf '{}' + + # 19. Remove lines containing string + > Notes: Remove lines not containing `'.js'` sudo sed -i '/\.js/!d' ./*scrap2.md sudo sed -i '/author/d' ./* + # 20. Remove duplicate lines from a text file + > //...syntax of uniq...// > $uniq [OPTION] [INPUT[OUTPUT]] > The syntax of this is quite easy to understand. Here, INPUT refers to the input file in which repeated lines need to be filtered out and if INPUT isn't specified then uniq reads from the standard input. OUTPUT refers to the output file in which you can store the filtered output generated by uniq command and as in case of INPUT if OUTPUT isn't specified then uniq writes to the standard output. Now, let's understand the use of this with the help of an example. Suppose you have a text file named kt.txt which contains repeated lines that needs to be omitted. This can simply be done with uniq. sudo apt install uniq uniq -u input.txt output.txt + # 21. Remove lines containing string + sudo sed -i '/githubusercontent/d' ./*sandbox.md sudo sed -i '/githubusercontent/d' ./*scrap2.md sudo sed -i '/github\.com/d' ./*out.md @@ -688,27 +741,42 @@ sudo sed -i '/stargazers/d' ./repo.txt sudo sed -i '/node_modules/d' ./index.html sudo sed -i '/right\.html/d' ./index.html sudo sed -i '/right\.html/d' ./right.html + # 22. Zip directory excluding .git and node_modules all the way down (Linux) -#!/bin/bash + +# !/bin/bash + TSTAMP=`date '+%Y%m%d-%H%M%S'` -zip -r $1.$TSTAMP.zip $1 -x "**.git/*" -x "**node_modules/*" `shift; echo $@;` +zip -r $1.$TSTAMP.zip $1 -x "**.git/_" -x "**node_modules/_" `shift; echo $@;` printf "\nCreated: $1.$TSTAMP.zip\n" -# usage: + +# usage + # - zipdir thedir + # - zip thedir -x "**anotherexcludedsubdir/*" (important the double quotes to prevent glob expansion) -# if in windows/git-bash, add 'zip' command this way: -# https://stackoverflow.com/a/55749636/1482990 + +# if in windows/git-bash, add 'zip' command this way + +# + # 23. Delete files containing a certain string + find . | xargs grep -l www.redhat.com | awk '{print "rm "$1}' > doit.sh vi doit.sh // check for murphy and his law source doit.sh + # 24 + html="sitemap.html" echo ' ' echo ' ' awk '{print "
  • ",$1," 
  • "}' $listing + # 25. Index of Iframes + ## Description: Creates an index.html file that contains all the files in the working directory or any of it's sub folders as iframes instead of anchor tags + > Notes: Useful Follow up Code: ```bash @@ -799,7 +867,7 @@ echo ' ' # awk '{print "
  • "}; - # {print " ",$1,"
  •  "}' \ $listing + # {print " ",$1," "}' \ $listing echo "" @@ -1115,7 +1183,7 @@ find . -type f -exec rename 's/-master//g' {} + ``` -> Notes: The same could be done for folder names by changing the *-type f* flag (for file) to a *-type d* flag (for directory) +> Notes: The same could be done for folder names by changing the _-type f_ flag (for file) to a _-type d_ flag (for directory) ```bash find -type d -exec sed -i 's///g' {} + @@ -1919,7 +1987,7 @@ find . -maxdepth 2 -name build -type d ## To search all files who are not in .git directory -find . ! -iwholename '*.git*' -type f +find . ! -iwholename '_.git_' -type f ## To find all files that have the same node (hard link) as MY_FILE_HERE @@ -1937,53 +2005,54 @@ find . -type f -exec chmod 644 {} \; ![Preview](https://i.imgur.com/nieW1vp.png) - ## Wiki Nav - -- [Home](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki) -- [add copy to code blocks.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/add-copy-to-code-blocks.md) -- [Add site search w algolia.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/Add-site-search-w-algolia.md) -- [adding mailing list.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/adding-mailing-list.md) -- [Adding search 2 gatsby site.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/Adding-search-2-gatsby-site.md) -- [awesome.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/awesome.md) -- [broken links.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/broken-links.md) -- [configure custom domain.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/configure-custom-domain.md) -- [contentauthoring.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/contentauthoring.md) -- [full text search w lunar.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/full-text-search-w-lunar.md) -- [inject 4.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/inject-4.md) -- [inject3.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/inject3.md) -- [inject4.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/inject4.md) -- [injected content part2.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/injected-content-part2.md) -- [injected js part4.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/injected-js-part4.md) -- [injected part3.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/injected-part3.md) -- [links 2 embed.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/links-2-embed.md) -- [links to remember](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/links-to-remember) -- [Netlify Injected Content](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/Netlify-Injected-Content) -- [old version of index.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/old-version-of-index.md) -- [optimize vscode.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/optimize-vscode.md) -- [possibly useful snippets.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/possibly-useful-snippets.md) -- [privacy policy.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/privacy-policy.md) -- [random stuff.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/random-stuff.md) -- [random.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/random.md) -- [ref type](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/ref-type) -- [SEO.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/SEO.md) -- [stable points.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/stable-points.md) -- [tech used.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/tech-used.md) -- [Technologies Used.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/Technologies-Used.md) -- [THINGS TO EMBED.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/THINGS-TO-EMBED.md) -- [validation report.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/validation-report.md) -- [web archive.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/web-archive.md) -- [wordpress vs headless cms.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/wordpress-vs-headless-cms.md) - +- [Home](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki) +- [add copy to code blocks.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/add-copy-to-code-blocks.md) +- [Add site search w algolia.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/Add-site-search-w-algolia.md) +- [adding mailing list.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/adding-mailing-list.md) +- [Adding search 2 gatsby site.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/Adding-search-2-gatsby-site.md) +- [awesome.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/awesome.md) +- [broken links.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/broken-links.md) +- [configure custom domain.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/configure-custom-domain.md) +- [contentauthoring.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/contentauthoring.md) +- [full text search w lunar.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/full-text-search-w-lunar.md) +- [inject 4.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/inject-4.md) +- [inject3.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/inject3.md) +- [inject4.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/inject4.md) +- [injected content part2.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/injected-content-part2.md) +- [injected js part4.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/injected-js-part4.md) +- [injected part3.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/injected-part3.md) +- [links 2 embed.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/links-2-embed.md) +- [links to remember](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/links-to-remember) +- [Netlify Injected Content](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/Netlify-Injected-Content) +- [old version of index.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/old-version-of-index.md) +- [optimize vscode.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/optimize-vscode.md) +- [possibly useful snippets.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/possibly-useful-snippets.md) +- [privacy policy.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/privacy-policy.md) +- [random stuff.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/random-stuff.md) +- [random.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/random.md) +- [ref type](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/ref-type) +- [SEO.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/SEO.md) +- [stable points.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/stable-points.md) +- [tech used.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/tech-used.md) +- [Technologies Used.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/Technologies-Used.md) +- [THINGS TO EMBED.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/THINGS-TO-EMBED.md) +- [validation report.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/validation-report.md) +- [web archive.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/web-archive.md) +- [wordpress vs headless cms.md](https://github.com/bgoonz/BGOONZ_BLOG_2.0/wiki/wordpress-vs-headless-cms.md) --- ## Dependencies -
    - Click to expand! + + +Click to expand! + + + [![@algolia**](https://avatars.githubusercontent.com/u/2034458?s=40&v=4)](https://github.com/algolia)[algolia / algoliasearch-client-javascript](https://github.com/algolia/algoliasearch-client-javascript)@algolia/client-search `^ 4.10.3` @@ -2083,9 +2152,13 @@ find . -type f -exec chmod 644 {} \; ## Docs Structure -
    - Docs Structure + + + Docs Structure + + + ``` ├── blog @@ -2689,7 +2762,13 @@ docky ./../src/components/pages/**/*.md \ # specify the components to parse - [https://bgoonz-blog.netlify.app/interview-questions-js](https://bgoonz-blog.netlify.app/interview-questions-js) - [https://bgoonz-blog.netlify.app/readme](https://bgoonz-blog.netlify.app/readme) - [https://bgoonz-blog.netlify.app/showcase](https://bgoonz-blog.netlify.app/showcase) - ↞↠ Getting Started With GatsbyJS ↞↠ + + + ↞↠ Getting Started With GatsbyJS ↞↠ + + + + # @@ -2700,14 +2779,13 @@ docky ./../src/components/pages/**/*.md \ # specify the components to parse ![tech-stack](https://github.com/bgoonz/BGOONZ_BLOG_2.0/blob/master/static/images/madewith.png?raw=true) ``` + --- ## SOURCECODE --- - - ### Overview The **`_.get()` method** in Lodash retrieves the object’s value at a specific path. @@ -2724,9 +2802,9 @@ _.get(object, path, defaultValue) This method accepts the following parameters: -- **`object`**: The object in which the given path will be queried. -- **`path`**: The path used to retrieve the value from the object. -- **`defaultValue`**: The default value that will be returned for resolved values that are undefined. +- **`object`**: The object in which the given path will be queried. +- **`path`**: The path used to retrieve the value from the object. +- **`defaultValue`**: The default value that will be returned for resolved values that are undefined. ### Return value @@ -2740,25 +2818,24 @@ Let’s look at an example of the `_.get()` method in the code snippet below: In the HTML tab: -- **Line 5**: We import the `lodash` script. +- **Line 5**: We import the `lodash` script. In the JavaScript tab: -- **Lines 2 to 15**: We create an object to perform a query. +- **Lines 2 to 15**: We create an object to perform a query. -- **Line 18**: We define a variable `collegeYopPath` to get the value. +- **Line 18**: We define a variable `collegeYopPath` to get the value. -- **Lines 19**: We use the `_.get()` method and pass the `object`, `collegeYopPath`, and a default value as parameters. +- **Lines 19**: We use the `_.get()` method and pass the `object`, `collegeYopPath`, and a default value as parameters. -- **Line 22**: We define a variable `falsyPath` to get the value. +- **Line 22**: We define a variable `falsyPath` to get the value. -- **Lines 23**: We use the `_.get()` method and pass the `object`, `falsyPath` and a `default value` as parameters. +- **Lines 23**: We use the `_.get()` method and pass the `object`, `falsyPath` and a `default value` as parameters. ### Output -- The `_.get()` method at **line 19** contains a valid path, and therefore the expression is resolved, and `2021` is printed on the console. -- The `_.get()` method at **Line 23** contains an invalid path, and therefore the expression is resolved as `undefined`. - +- The `_.get()` method at **line 19** contains a valid path, and therefore the expression is resolved, and `2021` is printed on the console. +- The `_.get()` method at **Line 23** contains an invalid path, and therefore the expression is resolved as `undefined`. --- @@ -2916,7 +2993,12 @@ bryan@LAPTOP-9LGJ3JGS:/c/MY-WEB-DEV/BLOG____2.0/BLOG_2.0/src$ ## Source Code
    - Folder Structure (src) + + + Folder Structure (src) + + + ``` . @@ -3231,7 +3313,12 @@ bryan@LAPTOP-9LGJ3JGS:/c/MY-WEB-DEV/BLOG____2.0/BLOG_2.0/src$
    - Click To See Component Sourcecode + + + Click To See Component Sourcecode + + + ## Component Structure @@ -3302,15 +3389,16 @@ export default class ActionLink extends React.Component { ``` --- + ### Table of Contents -- [getPage][1] - - [Parameters][2] -- [getPageByFilePath][3] - - [Parameters][4] -- [getPages][5] - - [Parameters][6] - - [Examples][7] +- [getPage][1] + - [Parameters][2] +- [getPageByFilePath][3] + - [Parameters][4] +- [getPages][5] + - [Parameters][6] + - [Examples][7] ## getPage @@ -3318,8 +3406,8 @@ Get the page at the provided `urlPath`. ### Parameters -- `pages` **[Array][8]** Array of page objects. All pages must have 'url' field. -- `urlPath` **[string][9]** The url path to find the page by +- `pages` **[Array][8]** Array of page objects. All pages must have 'url' field. +- `urlPath` **[string][9]** The url path to find the page by Returns **[Object][10]** @@ -3329,8 +3417,8 @@ Get the page at the provided `filePath`. ### Parameters -- `pages` **[Array][8]** Array of page objects. All pages must have 'url' field. -- `filePath` **[string][9]** The file path to find the page by +- `pages` **[Array][8]** Array of page objects. All pages must have 'url' field. +- `filePath` **[string][9]** The file path to find the page by Returns **[Object][10]** @@ -3342,8 +3430,8 @@ the page having its URL equal to `urlPath`. ### Parameters -- `pages` **[Array][8]** Array of page objects. All pages must have 'url' field. -- `urlPath` **[string][9]** The url path to filter pages by +- `pages` **[Array][8]** Array of page objects. All pages must have 'url' field. +- `urlPath` **[string][9]** The url path to filter pages by ### Examples @@ -3376,8 +3464,6 @@ Returns **[Array][8]** [9]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String [10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object - - ```js import React from 'react'; import _ from 'lodash'; diff --git a/notes/future-implementations/src/hooks/index.js b/docs/hooks/index.js similarity index 100% rename from notes/future-implementations/src/hooks/index.js rename to docs/hooks/index.js diff --git a/src/utils/hooks/useDarkMode.js b/docs/hooks/useDarkMode.js similarity index 100% rename from src/utils/hooks/useDarkMode.js rename to docs/hooks/useDarkMode.js diff --git a/notes/future-implementations/src/hooks/useEventListener.js b/docs/hooks/useEventListener.js similarity index 100% rename from notes/future-implementations/src/hooks/useEventListener.js rename to docs/hooks/useEventListener.js diff --git a/notes/future-implementations/src/hooks/useMediaQuery.js b/docs/hooks/useMediaQuery.js similarity index 100% rename from notes/future-implementations/src/hooks/useMediaQuery.js rename to docs/hooks/useMediaQuery.js diff --git a/notes/future-implementations/src/hooks/useOnClickOutside.js b/docs/hooks/useOnClickOutside.js similarity index 100% rename from notes/future-implementations/src/hooks/useOnClickOutside.js rename to docs/hooks/useOnClickOutside.js diff --git a/src/utils/hooks/useQueryParam.js b/docs/hooks/useQueryParam.js similarity index 100% rename from src/utils/hooks/useQueryParam.js rename to docs/hooks/useQueryParam.js diff --git a/src/utils/hooks/useSize.js b/docs/hooks/useSize.js similarity index 100% rename from src/utils/hooks/useSize.js rename to docs/hooks/useSize.js diff --git a/src/utils/hooks/useStorage.js b/docs/hooks/useStorage.js similarity index 100% rename from src/utils/hooks/useStorage.js rename to docs/hooks/useStorage.js diff --git a/gatsby-browser.jsx b/gatsby-browser.jsx deleted file mode 100644 index 9c867a7d5e..0000000000 --- a/gatsby-browser.jsx +++ /dev/null @@ -1,9 +0,0 @@ -const React = require("react") -const Layout = require("./src/components/layout") -// Logs when the client route changes -exports.onRouteUpdate = ({ location, prevLocation }) => { - console.log("new pathname", location.pathname) - console.log("old pathname", prevLocation ? prevLocation.pathname : null) -} -// Wraps every page in a component -exports.wrapPageElement = ({ element, props }) => {{element} \ No newline at end of file diff --git a/gatsby-ssr.js b/gatsby-ssr.js index ee23f0b8c3..3e33e7940d 100644 --- a/gatsby-ssr.js +++ b/gatsby-ssr.js @@ -2,34 +2,8 @@ /** * Implement Gatsby's SSR (Server Side Rendering) APIs in this file. * - * {/* // search-create.js -// - -you can access meta information about the module using the `import.meta` object. - - console.log(import.meta); // { url: "file:///home/user/my-module.js" } - -It returns an object with a `url` property indicating the base URL of the module. This will either be the URL from which the script was obtained, for external scripts, or the document base URL of the containing document, for inline scripts. - -Note that this will include query parameters and/or hash (i.e., following the `?` or `#`). - -For example, with the following HTML: - - - -..the following JavaScript file will log the \``someURLInfo` parameter: - - // index.mjs - new URL(import.meta.url).searchParams.get('someURLInfo'); // 5 - -The same applies when a file imports another: - - // index.mjs - import './index2.mjs?someURLInfo=5'; - - // index2.mjs - new URL(import.meta.url).searchParams.get('someURLInfo'); // 5 - -Note that while Node.js will pass on query parameters (or the hash) as in the latter example, as of Node 14.1.0, a URL with query parameters will err when loading in the form `node --experimental-modules index.mjs?someURLInfo=5` (it is treated as a file rather than a URL in this context). - -Such file-specific argument passing may be complementary to that used in the application-wide `location.href` (with query strings or hash added after the HTML file path) (or on Node.js, through `process.argv`). - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#prod-ImportMeta
    HTML Standard (HTML) -
    - -#hostgetimportmetaproperties
    - -`import.meta` - -64 - -79 - -62 - -No - -51 - -11.1 - -64 - -64 - -62 - -47 - -12 - -9.0 - -## See also - -- [`import`](import) -- [`export`](export) - - - -Statements/import.meta" Statements/import.meta - ---- ---- - -# WebAssembly.Module.imports() - -The `WebAssembly.imports()` function returns an array containing descriptions of all the declared imports of the given `Module`. - -## Syntax - - WebAssembly.Module.imports(module) - -### Parameters - -_module_ -A [`WebAssembly.Module`](../module) object. - -### Return value - -An array containing objects representing the imported functions of the given module. - -### Exceptions - -If module is not a [`WebAssembly.Module`](../module) object instance, a [`TypeError`](../../typeerror) is thrown. - -## Examples - -### Using imports - -The following example (see imports.html [source code](https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/imports.html); [see it live also](https://mdn.github.io/webassembly-examples/js-api-examples/imports.html)) compiles the loaded simple.wasm module. This module is then queried for its imports. - - WebAssembly.compileStreaming(fetch('simple.wasm')) - .then(function(mod) { - var imports = WebAssembly.Module.imports(mod); - console.log(imports[0]); - }); - -The output looks like this: - - { module: "imports", name: "imported_func", kind: "function" } - -## Specifications - -
    Specification
    WebAssembly JavaScript Interface (WebAssembly JavaScript Interface) -
    - -#dom-module-imports
    - -`imports` - -57 - -16 - -52 - -Disabled in the Firefox 52 Extended Support Release (ESR). - -No - -44 - -11 - -57 - -57 - -52 - -Disabled in the Firefox 52 Extended Support Release (ESR). - -43 - -11 - -7.0 - -## See also - -- [WebAssembly](https://developer.mozilla.org/en-US/docs/WebAssembly) overview page -- [WebAssembly concepts](https://developer.mozilla.org/en-US/docs/WebAssembly/Concepts) -- [Using the WebAssembly JavaScript API](https://developer.mozilla.org/en-US/docs/WebAssembly/Using_the_JavaScript_API) - - - -Global_Objects/WebAssembly/Module/imports" Global_Objects/WebAssembly/Module/imports - ---- ---- - -# Math.imul() - -The `Math.imul()` function returns the result of the C-like 32-bit multiplication of the two parameters. - -## Syntax - - Math.imul(a, b) - -### Parameters - -`a` -First number. - -`b` -Second number. - -### Return value - -The result of the C-like 32-bit multiplication of the given arguments. - -## Description - -`Math.imul()` allows for 32-bit integer multiplication with C-like semantics. This feature is useful for projects like [Emscripten](https://en.wikipedia.org/wiki/Emscripten). - -Because `imul()` is a static method of `Math`, you always use it as `Math.imul()`, rather than as a method of a `Math` object you created (`Math` is not a constructor). - -If you use normal JavaScript floating point numbers in imul, you will experience a degrade in performance. This is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point. The reason imul exists is because it is faster in only one (so far) circumstance: AsmJS. AsmJS allows for JIST-optimizers to more easily implement internal integers in JavaScript. Multiplying two numbers stored internally as integers (which is only possible with AsmJS) with imul is the only potential circumstance where Math.imul may prove performant in current browsers. - -## Examples - -### Using Math.imul() - - Math.imul(2, 4); // 8 - Math.imul(-1, 8); // -8 - Math.imul(-2, -2); // 4 - Math.imul(0xffffffff, 5); // -5 - Math.imul(0xfffffffe, 5); // -10 - -## Polyfill - -This can be emulated with the following function: - - if (!Math.imul) Math.imul = function(a, b) { - var aHi = (a >>> 16) & 0xffff; - var aLo = a & 0xffff; - var bHi = (b >>> 16) & 0xffff; - var bLo = b & 0xffff; - // the shift by 0 fixes the sign on the high part - // the final |0 converts the unsigned value into a signed value - return ((aLo * bLo) + (((aHi * bLo + aLo * bHi) << 16) >>> 0) | 0); - }; - -However, the following function is more performant because it is likely that browsers in which this polyfill would be used do not optimize with an internal integer type in JavaScript, instead using floating points for all numbers. - - if (!Math.imul) Math.imul = function(opA, opB) { - opB |= 0; // ensure that opB is an integer. opA will automatically be coerced. - // floating points give us 53 bits of precision to work with plus 1 sign bit - // automatically handled for our convienence: - // 1. 0x003fffff /*opA & 0x000fffff*/ * 0x7fffffff /*opB*/ = 0x1fffff7fc00001 - // 0x1fffff7fc00001 < Number.MAX_SAFE_INTEGER /*0x1fffffffffffff*/ - var result = (opA & 0x003fffff) * opB; - // 2. We can remove an integer coersion from the statement above because: - // 0x1fffff7fc00001 + 0xffc00000 = 0x1fffffff800001 - // 0x1fffffff800001 < Number.MAX_SAFE_INTEGER /*0x1fffffffffffff*/ - if (opA & 0xffc00000 /*!== 0*/) result += (opA & 0xffc00000) * opB |0; - return result |0; - }; - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-math.imul
    - -`imul` - -28 - -12 - -20 - -No - -16 - -7 - -≤37 - -28 - -20 - -15 - -7 - -1.5 - -## See also - -- [Emscripten](https://en.wikipedia.org/wiki/Emscripten) - - - -Global_Objects/Math/imul" Global_Objects/Math/imul - ---- ---- - -# in operator - -The `in` returns `true` if the specified property is in the specified object or its prototype chain. - -## Syntax - - prop in object - -### Parameters - -`prop` -A string or symbol representing a property name or array index (non-symbols will be coerced to strings). - -`object` -Object to check if it (or its prototype chain) contains the property with specified name (`prop`). - -## Examples - -### Basic usage - -The following examples show some uses of the `in` operator. - - // Arrays - let trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'] - 0 in trees // returns true - 3 in trees // returns true - 6 in trees // returns false - 'bay' in trees // returns false (you must specify the index number, not the value at that index) - 'length' in trees // returns true (length is an Array property) - Symbol.iterator in trees // returns true (arrays are iterable, works only in ES2015+) - - // Predefined objects - 'PI' in Math // returns true - - // Custom objects - let mycar = {make: 'Honda', model: 'Accord', year: 1998} - 'make' in mycar // returns true - 'model' in mycar // returns true - -You must specify an object on the right side of the `in` operator. For example, you can specify a string created with the `String` constructor, but you cannot specify a string literal. - - let color1 = new String('green') - 'length' in color1 // returns true - - let color2 = 'coral' - // generates an error (color2 is not a String object) - 'length' in color2 - -### Using `in` with deleted or undefined properties - -If you delete a property with the `delete` operator, the `in` operator returns `false` for that property. - - let mycar = {make: 'Honda', model: 'Accord', year: 1998} - delete mycar.make - 'make' in mycar // returns false - - let trees = new Array('redwood', 'bay', 'cedar', 'oak', 'maple') - delete trees[3] - 3 in trees // returns false - -If you set a property to [`undefined`](../global_objects/undefined) but do not delete it, the `in` operator returns true for that property. - - let mycar = {make: 'Honda', model: 'Accord', year: 1998} - mycar.make = undefined - 'make' in mycar // returns true - - let trees = new Array('redwood', 'bay', 'cedar', 'oak', 'maple') - trees[3] = undefined - 3 in trees // returns true - -The `in` operator will return `false` for empty array slots. Even if accessing it directly returns `undefined`. - - let empties = new Array(3) - empties[2] // returns undefined - 2 in empties // returns false - -To avoid this, make sure a new array is always filled with non-empty values or not write to indexes past the end of array. - - let empties = new Array(3).fill(undefined) - 2 in empties // returns true - -### Inherited properties - -The `in` operator returns `true` for properties in the prototype chain. (If you want to check for only _non-inherited_ properties, use [`Object.prototype.hasOwnProperty()`](../global_objects/object/hasownproperty) instead.) - - 'toString' in {} // returns true - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-relational-operators
    - -`in` - -1 - -12 - -1 - -5.5 - -4 - -1 - -1 - -18 - -4 - -10.1 - -1 - - - -- `for...in` -- `delete` -- [`Object.prototype.hasOwnProperty()`](../global_objects/object/hasownproperty) -- [`Reflect.has()`](../global_objects/reflect/has) -- [Enumerability and ownership of properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) - - - -Operators/in" Operators/in - ---- ---- - -# TypeError: cannot use 'in' operator to search for 'x' in 'y' - -The JavaScript exception "right-hand side of 'in' should be an object" occurs when the [`in` operator](../operators/in) was used to search in strings, or in numbers, or other primitive types. It can only be used to check if a property is in an object. - -## Message - - TypeError: Invalid operand to 'in' (Edge) - TypeError: right-hand side of 'in' should be an object, got 'x' (Firefox) - TypeError: cannot use 'in' operator to search for 'x' in 'y' (Firefox, Chrome) - -## Error type - -[`TypeError`](../global_objects/typeerror) - -## What went wrong? - -The [`in` operator](../operators/in) can only be used to check if a property is in an object. You can't search in strings, or in numbers, or other primitive types. - -## Examples - -### Searching in strings - -Unlike in other programming languages (e.g. Python), you can't search in strings using the [`in` operator](../operators/in). - - "Hello" in "Hello World"; - // TypeError: cannot use 'in' operator to search for 'Hello' in 'Hello World' - -Instead you will need to use [`String.prototype.indexOf()`](../global_objects/string/indexof), for example. - - "Hello World".indexOf("Hello") !== -1; - // true - -### The operand can't be null or undefined - -Make sure the object you are inspecting isn't actually [`null`](../global_objects/null) or [`undefined`](../global_objects/undefined). - - var foo = null; - "bar" in foo; - // TypeError: cannot use 'in' operator to search for 'bar' in 'foo' (Chrome) - // TypeError: right-hand side of 'in' should be an object, got null (Firefox) - -The `in` operator always expects an object. - - var foo = { baz: "bar" }; - "bar" in foo; // false - - "PI" in Math; // true - "pi" in Math; // false - -### Searching in arrays - -Be careful when using the `in` operator to search in [`Array`](../global_objects/array) objects. The `in` operator checks the index number, not the value at that index. - - var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; - 3 in trees; // true - "oak" in trees; // false - -## See also - -- [`in` operator](../operators/in) - -Errors/in_operator_no_object" Errors/in_operator_no_object - ---- ---- - -# Array.prototype.includes() - -The `includes()` method determines whether an array includes a certain value among its entries, returning `true` or `false` as appropriate. - -## Syntax - - includes(searchElement) - includes(searchElement, fromIndex) - -### Parameters - -`searchElement` -The value to search for. - -**Note:** When comparing strings and characters, `includes()` is _case-sensitive_. - -`fromIndex` Optional -The position in this array at which to begin searching for `searchElement`. - -The first element to be searched is found at `fromIndex` for positive values of `fromIndex`, or at `arr.length + fromIndex` for negative values of `fromIndex` (using the [absolute value](#) of `fromIndex` as the number of elements from the end of the array at which to start the search). - -Defaults to `0`. - -### Return value - -A [`Boolean`](../boolean) which is `true` if the value `searchElement` is found within the array (or the part of the array indicated by the index `fromIndex`, if specified). - -Values of zero are all considered to be equal, regardless of sign. (That is, `-0` is considered to be equal to both `0` and `+0`), but `false` is _not_ considered to be the same as `0`. - -**Note:** Technically speaking, `includes()` uses the `sameValueZero` algorithm to determine whether the given element is found. - -## Examples - - [1, 2, 3].includes(2) // true - [1, 2, 3].includes(4) // false - [1, 2, 3].includes(3, 3) // false - [1, 2, 3].includes(3, -1) // true - [1, 2, NaN].includes(NaN) // true - -### `fromIndex` is greater than or equal to the array length - -If `fromIndex` is greater than or equal to the length of the array, `false` is returned. The array will not be searched. - - let arr = ['a', 'b', 'c'] - - arr.includes('c', 3) // false - arr.includes('c', 100) // false - -### Computed index is less than 0 - -If `fromIndex` is negative, the computed index is calculated to be used as a position in the array at which to begin searching for `searchElement`. If the computed index is less or equal than `-1 * arr.length`, the entire array will be searched. - - // array length is 3 - // fromIndex is -100 - // computed index is 3 + (-100) = -97 - - let arr = ['a', 'b', 'c'] - - arr.includes('a', -100) // true - arr.includes('b', -100) // true - arr.includes('c', -100) // true - arr.includes('a', -2) // false - -### includes() used as a generic method - -`includes()` method is intentionally generic. It does not require `this` value to be an Array object, so it can be applied to other kinds of objects (e.g. array-like objects). - -The example below illustrates `includes()` method called on the function's [arguments](../../functions/arguments) object. - - (function() { - console.log(Array.prototype.includes.call(arguments, 'a')) // true - console.log(Array.prototype.includes.call(arguments, 'd')) // false - })('a','b','c') - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-array.prototype.includes
    - -`includes` - -47 - -14 - -43 - -No - -34 - -9 - -47 - -47 - -43 - -34 - -9 - -5.0 - -## See also - -- [`TypedArray.prototype.includes()`](../typedarray/includes) -- [`String.prototype.includes()`](../string/includes) -- [`Array.prototype.indexOf()`](indexof) -- [`Array.prototype.find()`](find) -- [`Array.prototype.findIndex()`](findindex) - -Global_Objects/Array/includes" Global_Objects/Array/includes - ---- ---- - -# Increment (++) - -The increment operator (`++`) increments (adds one to) its operand and returns a value. - -## Syntax - - Operator: x++ or ++x - -## Description - -If used postfix, with operator after operand (for example, `x++`), the increment operator increments and returns the value before incrementing. - -If used prefix, with operator before operand (for example, `++x`), the increment operator increments and returns the value after incrementing. - -## Examples - -### Postfix increment - - let x = 3; - y = x++; - - // y = 3 - // x = 4 - -### Prefix increment - - let a = 2; - b = ++a; - - // a = 3 - // b = 3 - -## Specifications - -
    Specification
    ECMAScript (ECMA-262) -
    - -The definition of 'Increment operator' in that specification.
    - -`Increment` - -2 - -12 - -1 - -3 - -3 - -4 - -1 - -18 - -4 - -10.1 - -3.2 - - - -- [Addition operator](addition) -- [Subtraction operator](subtraction) -- [Division operator](division) -- [Multiplication operator](multiplication) -- [Remainder operator](remainder) -- [Exponentiation operator](exponentiation) -- [Decrement operator](decrement) -- [Unary negation operator](unary_negation) -- [Unary plus operator](unary_plus) - - - -Operators/Increment" Operators/Increment - ---- ---- - -# JavaScript reference - -This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more [about this reference](about). - -## Built-ins - -[JavaScript standard built-in objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects), along with their methods and properties. - -### Value properties - -- [`Infinity`](global_objects/infinity) -- [`NaN`](global_objects/nan) -- [`undefined`](global_objects/undefined) -- [`globalThis`](global_objects/globalthis) - -### Function properties - -- [`eval()`](global_objects/eval) -- [`isFinite()`](global_objects/isfinite) -- [`isNaN()`](global_objects/isnan) -- [`parseFloat()`](global_objects/parsefloat) -- [`parseInt()`](global_objects/parseint) -- [`decodeURI()`](global_objects/decodeuri) -- [`decodeURIComponent()`](global_objects/decodeuricomponent) -- [`encodeURI()`](global_objects/encodeuri) -- [`encodeURIComponent()`](global_objects/encodeuricomponent) - -### Fundamental objects - -- [`Object`](global_objects/object) -- [`Function`](global_objects/function) -- [`Boolean`](global_objects/boolean) -- [`Symbol`](global_objects/symbol) - -### Error objects - -- [`Error`](global_objects/error) -- [`AggregateError`](global_objects/aggregateerror) -- [`EvalError`](global_objects/evalerror) -- [`InternalError`](global_objects/internalerror) -- [`RangeError`](global_objects/rangeerror) -- [`ReferenceError`](global_objects/referenceerror) -- [`SyntaxError`](global_objects/syntaxerror) -- [`TypeError`](global_objects/typeerror) -- [`URIError`](global_objects/urierror) - -### Numbers & dates - -- [`Number`](global_objects/number) -- [`BigInt`](global_objects/bigint) -- [`Math`](global_objects/math) -- [`Date`](global_objects/date) - -### Text processing - -- [`String`](global_objects/string) -- [`RegExp`](global_objects/regexp) - -### Indexed Collections - -- [`Array`](global_objects/array) -- [`Int8Array`](global_objects/int8array) -- [`Uint8Array`](global_objects/uint8array) -- [`Uint8ClampedArray`](global_objects/uint8clampedarray) -- [`Int16Array`](global_objects/int16array) -- [`Uint16Array`](global_objects/uint16array) -- [`Int32Array`](global_objects/int32array) -- [`Uint32Array`](global_objects/uint32array) -- [`Float32Array`](global_objects/float32array) -- [`Float64Array`](global_objects/float64array) -- [`BigInt64Array`](global_objects/bigint64array) -- [`BigUint64Array`](global_objects/biguint64array) - -### Keyed collections - -- [`Map`](global_objects/map) -- [`Set`](global_objects/set) -- [`WeakMap`](global_objects/weakmap) -- [`WeakSet`](global_objects/weakset) - -### Structured data - -- [`ArrayBuffer`](global_objects/arraybuffer) -- [`SharedArrayBuffer`](global_objects/sharedarraybuffer) -- [`Atomics`](global_objects/atomics) -- [`DataView`](global_objects/dataview) -- [`JSON`](global_objects/json) - -### Control abstraction - -- [`GeneratorFunction`](global_objects/generatorfunction) -- `AsyncGeneratorFunction` -- [`Generator`](global_objects/generator) -- `AsyncGenerator` -- [`AsyncFunction`](global_objects/asyncfunction) -- [`Promise`](global_objects/promise) - -### Reflection - -- [`Reflect`](global_objects/reflect) -- [`Proxy`](global_objects/proxy) - -### Internationalization - -- [`Intl`](global_objects/intl) -- [`Intl.Collator`](global_objects/intl/collator) -- [`Intl.DateTimeFormat`](global_objects/intl/datetimeformat) -- [`Intl.DisplayNames`](global_objects/intl/displaynames) -- [`Intl.ListFormat`](global_objects/intl/listformat) -- [`Intl.Locale`](global_objects/intl/locale) -- [`Intl.NumberFormat`](global_objects/intl/numberformat) -- [`Intl.PluralRules`](global_objects/intl/pluralrules) -- [`Intl.RelativeTimeFormat`](global_objects/intl/relativetimeformat) - -### WebAssembly - -- [`WebAssembly`](global_objects/webassembly) -- [`WebAssembly.Module`](global_objects/webassembly/module) -- [`WebAssembly.Instance`](global_objects/webassembly/instance) -- [`WebAssembly.Memory`](global_objects/webassembly/memory) -- [`WebAssembly.Table`](global_objects/webassembly/table) -- [`WebAssembly.CompileError`](global_objects/webassembly/compileerror) -- [`WebAssembly.LinkError`](global_objects/webassembly/linkerror) -- [`WebAssembly.RuntimeError`](global_objects/webassembly/runtimeerror) - -## Statements - -[JavaScript statements and declarations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements) - -### Control flow - -- [`Block`](statements/block) -- [`break`](statements/break) -- [`continue`](statements/continue) -- [`Empty`](statements/empty) -- [`if...else`](statements/if...else) -- [`switch`](statements/switch) -- [`throw`](statements/throw) -- [`try...catch`](statements/try...catch) - -### Declarations - -- [`var`](statements/var) -- [`let`](statements/let) -- [`const`](statements/const) - -### Functions and classes - -- [`function`](statements/function) -- [`function*`](statements/function*) -- [`async function`](statements/async_function) -- [`return`](statements/return) -- [`class`](statements/class) - -### Iterations - -- [`do...while`](statements/do...while) -- [`for`](statements/for) -- `for each...in` -- [`for...in`](statements/for...in) -- [`for...of`](statements/for...of) -- [`for await...of`](statements/for-await...of) -- [`while`](statements/while) - -### Other - -- [`debugger`](statements/debugger) -- [`export`](statements/export) -- [`import`](statements/import) -- [`label`](statements/label) -- [`with`](statements/with) - -## Expressions and operators - -[JavaScript expressions and operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators). - -### Primary expressions - -- [`this`](operators/this) -- [`function`](operators/function) -- [`class`](operators/class) -- [`function*`](operators/function*) -- [`yield`](operators/yield) -- [`yield*`](operators/yield*) -- [`async function`](operators/async_function) -- [`await`](operators/await) -- [`[]`](global_objects/array) -- [`{}`](operators/object_initializer) -- [`/ab+c/i`](global_objects/regexp) -- [`( )`](operators/grouping) -- [`null`](global_objects/null) - -### Left-hand-side expressions - -- [Property accessors](operators/property_accessors) -- [Optional chaining](operators/optional_chaining) -- [`new`](operators/new) -- [`new.target`](operators/new.target) -- [`import.meta`](statements/import.meta) -- [`super`](operators/super) -- [`...obj`](operators/spread_syntax) - -### Increment & decrement - -- [`A++`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#increment) -- [`A--`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#decrement) -- [`++A`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#increment) -- [`--A`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#decrement) - -### Unary operators - -- [`delete`](operators/delete) -- [`void`](operators/void) -- [`typeof`](operators/typeof) -- [`+`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#unary_plus) -- [`-`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#unary_negation) -- [`~`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#bitwise_not) -- [`!`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#logical_not) - -### Arithmetic operators - -- [`+`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#addition) -- [`-`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#subtraction) -- [`/`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#division) -- [`*`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#multiplication) -- [`%`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#remainder) -- [`**`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#exponentiation) - -### Relational operators - -- [`in`](operators/in) -- [`instanceof`](operators/instanceof) -- [`<`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#less_than_operator) -- [`>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#greater_than_operator) -- [`<=`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#less_than_or_equal_operator) -- [`>=`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#greater_than_or_equal_operator) - -### Equality operators - -- [`==`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#equality) -- [`!=`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#inequality) -- [`===`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#identity) -- [`!==`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#nonidentity) - -### Bitwise shift operators - -- [`<<`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#left_shift) -- [`>>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#right_shift) -- [`>>>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#unsigned_right_shift) - -### Binary bitwise operators - -- [`&`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#bitwise_and) -- [`|`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#bitwise_or) -- [`^`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#bitwise_xor) - -### Binary logical operators - -- [`&&`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#logical_and) -- [`||`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#logical_or) - -### Conditional (ternary) operator - -- [`(condition ? ifTrue : ifFalse)`](operators/conditional_operator) - -### Assignment operators - -- [`=`](#) -- [`*=`](#) -- [`/=`](#) -- [`%=`](#) -- [`+=`](#) -- [`-=`](#) -- [`<<=`](#) -- [`>>=`](#) -- [`>>>=`](#) -- [`&=`](#) -- [`^=`](#) -- [`|=`](#) -- [`[a, b] = [1, 2]`](operators/destructuring_assignment) -- [`{a, b} = {a:1, b:2}`](operators/destructuring_assignment) - -## Functions - -This chapter documents how to work with JavaScript functions to develop your applications. - -- [`arguments`](functions/arguments) -- [Arrow functions](functions/arrow_functions) -- [Default parameters](functions/default_parameters) -- [Rest parameters](functions/rest_parameters) - -## Additional reference pages - -- [Lexical grammar](lexical_grammar) -- [Data types and data structures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures) -- [Strict mode](strict_mode) -- [Deprecated features](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features) - -https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference - ---- ---- - -# Array.prototype.indexOf() - -The `indexOf()` method returns the first index at which a given element can be found in the array, or -1 if it is not present. - -## Syntax - - indexOf(searchElement) - indexOf(searchElement, fromIndex) - -### Parameters - -`searchElement` -Element to locate in the array. - -`fromIndex` Optional -The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array. Note: if the provided index is negative, the array is still searched from front to back. If the provided index is 0, then the whole array will be searched. Default: 0 (entire array is searched). - -### Return value - -The first index of the element in the array; **-1** if not found. - -## Description - -`indexOf()` compares `searchElement` to elements of the Array using [strict equality](../../operators/strict_equality) (the same method used by the `===` or triple-equals operator). - -**Note:** For the String method, see [`String.prototype.indexOf()`](../string/indexof). - -## Examples - -### Using indexOf() - -The following example uses `indexOf()` to locate values in an array. - - var array = [2, 9, 9]; - array.indexOf(2); // 0 - array.indexOf(7); // -1 - array.indexOf(9, 2); // 2 - array.indexOf(2, -1); // -1 - array.indexOf(2, -3); // 0 - -### Finding all the occurrences of an element - - var indices = []; - var array = ['a', 'b', 'a', 'c', 'a', 'd']; - var element = 'a'; - var idx = array.indexOf(element); - while (idx != -1) { - indices.push(idx); - idx = array.indexOf(element, idx + 1); - } - console.log(indices); - // [0, 2, 4] - -### Finding if an element exists in the array or not and updating the array - - function updateVegetablesCollection (veggies, veggie) { - if (veggies.indexOf(veggie) === -1) { - veggies.push(veggie); - console.log('New veggies collection is : ' + veggies); - } else if (veggies.indexOf(veggie) > -1) { - console.log(veggie + ' already exists in the veggies collection.'); - } - } - - var veggies = ['potato', 'tomato', 'chillies', 'green-pepper']; - - updateVegetablesCollection(veggies, 'spinach'); - // New veggies collection is : potato,tomato,chillies,green-pepper,spinach - updateVegetablesCollection(veggies, 'spinach'); - // spinach already exists in the veggies collection. - -## Polyfill - -`indexOf()` was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all browsers. You can work around this by utilizing the following code at the beginning of your scripts. This will allow you to use `indexOf()` when there is still no native support. This algorithm matches the one specified in ECMA-262, 5th edition, assuming [`TypeError`](../typeerror) and [`Math.abs()`](../math/abs) have their original values. - - // This version tries to optimize by only checking for "in" when looking for undefined and - // skipping the definitely fruitless NaN search. Other parts are merely cosmetic conciseness. - // Whether it is actually faster remains to be seen. - if (!Array.prototype.indexOf) - Array.prototype.indexOf = (function(Object, max, min) { - "use strict" - return function indexOf(member, fromIndex) { - if (this === null || this === undefined) - throw TypeError("Array.prototype.indexOf called on null or undefined") - - var that = Object(this), Len = that.length >>> 0, i = min(fromIndex | 0, Len) - if (i < 0) i = max(0, Len + i) - else if (i >= Len) return -1 - - if (member === void 0) { // undefined - for (; i !== Len; ++i) if (that[i] === void 0 && i in that) return i - } else if (member !== member) { // NaN - return -1 // Since NaN !== NaN, it will never be found. Fast-path it. - } else // all else - for (; i !== Len; ++i) if (that[i] === member) return i - - return -1 // if the value was not found, then return -1 - } - })(Object, Math.max, Math.min) - -However, if you are more interested in all the little technical bits defined by the ECMA standard, and are less concerned about performance or conciseness, then you may find this more descriptive polyfill to be more useful. - - // Production steps of ECMA-262, Edition 5, 15.4.4.14 - // Reference: https://es5.github.io/#x15.4.4.14 - if (!Array.prototype.indexOf) { - Array.prototype.indexOf = function(searchElement, fromIndex) { - "use strict"; - var k; - - // 1. Let o be the result of calling ToObject passing - // the this value as the argument. - if (this == null) { - throw new TypeError('"this" is null or not defined'); - } - - var o = Object(this); - - // 2. Let lenValue be the result of calling the Get - // internal method of o with the argument "length". - // 3. Let len be ToUint32(lenValue). - var len = o.length >>> 0; - - // 4. If len is 0, return -1. - if (len === 0) { - return -1; - } - - // 5. If argument fromIndex was passed let n be - // ToInteger(fromIndex); else let n be 0. - var n = fromIndex | 0; - - // 6. If n >= len, return -1. - if (n >= len) { - return -1; - } - - // 7. If n >= 0, then Let k be n. - // 8. Else, n<0, Let k be len - abs(n). - // If k is less than 0, then let k be 0. - k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); - - // 9. Repeat, while k < len - for (; k < len; k++) { - // a. Let Pk be ToString(k). - // This is implicit for LHS operands of the in operator - // b. Let kPresent be the result of calling the - // HasProperty internal method of o with argument Pk. - // This step can be combined with c - // c. If kPresent is true, then - // i. Let elementK be the result of calling the Get - // internal method of o with the argument ToString(k). - // ii. Let same be the result of applying the - // Strict Equality Comparison Algorithm to - // searchElement and elementK. - // iii. If same is true, return k. - if (k in o && o[k] === searchElement) - return k; - } - return -1; - }; - } - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-array.prototype.indexof
    - -`indexOf` - -1 - -12 - -1.5 - -9 - -9.5 - -3 - -≤37 - -18 - -4 - -10.1 - -1 - - - -- [`Array.prototype.lastIndexOf()`](lastindexof) -- [`TypedArray.prototype.indexOf()`](../typedarray/indexof) -- [`String.prototype.indexOf()`](../string/indexof) - -Global_Objects/Array/indexOf" Global_Objects/Array/indexOf - ---- ---- - -# Inequality (!=) - -The inequality operator (`!=`) checks whether its two operands are not equal, returning a Boolean result. Unlike the [strict inequality](strict_inequality) operator, it attempts to convert and compare operands that are of different types. - -## Syntax - - x != y - -## Description - -The inequality operator checks whether its operands are not equal. It is the negation of the [equality](equality) operator so the following two lines will always give the same result: - - x != y - - !(x == y) - -For details of the comparison algorithm, see the page for the [equality](equality) operator. - -Like the equality operator, the inequality operator will attempt to convert and compare operands of different types: - - 3 != "3"; // false - -To prevent this, and require that different types are considered to be different, use the [strict inequality](strict_inequality) operator instead: - - 3 !== "3"; // true - -## Examples - -### Comparison with no type conversion - - 1 != 2; // true - "hello" != "hola"; // true - - 1 != 1; // false - "hello" != "hello"; // false - -### Comparison with type conversion - - "1" != 1; // false - 1 != "1"; // false - 0 != false; // false - 0 != null; // true - 0 != undefined; // true - 0 != !!null; // false, look at Logical NOT operator - 0 != !!undefined; // false, look at Logical NOT operator - null != undefined; // false - - const number1 = new Number(3); - const number2 = new Number(3); - number1 != 3; // false - number1 != number2; // true - -### Comparison of objects - - const object1 = {"key": "value"} - const object2 = {"key": "value"}; - - object1 != object2 // true - object2 != object2 // false - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-equality-operators
    - -`Inequality` - -1 - -12 - -1 - -3 - -3 - -1 - -1 - -18 - -4 - -10.1 - -1 - - - -- [Equality operator](equality) -- [Strict equality operator](strict_equality) -- [Strict inequality operator](strict_inequality) - - - -Operators/Inequality" Operators/Inequality - ---- ---- - -# Infinity - -The global property `Infinity` is a numeric value representing infinity. - -Property attributes of `Infinity` - -Writable - -no - -Enumerable - -no - -Configurable - -no - -## Description - -`Infinity` is a property of the _global object_. In other words, it is a variable in global scope. - -The initial value of `Infinity` is [`Number.POSITIVE_INFINITY`](number/positive_infinity). The value `Infinity` (positive infinity) is greater than any other number. - -This value behaves slightly differently than mathematical infinity; see [`Number.POSITIVE_INFINITY`](number/positive_infinity) for details. - -As defined by the ECMAScript 5 specification, `Infinity` is read-only (implemented in JavaScript 1.8.5 / Firefox 4). - -## Examples - -### Using Infinity - - console.log(Infinity ); /* Infinity */ - console.log(Infinity + 1 ); /* Infinity */ - console.log(Math.pow(10, 1000)); /* Infinity */ - console.log(Math.log(0) ); /* -Infinity */ - console.log(1 / Infinity ); /* 0 */ - console.log(1 / 0 ); /* Infinity */ - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-value-properties-of-the-global-object-infinity
    - -`Infinity` - -1 - -12 - -1 - -4 - -4 - -1 - -1 - -18 - -4 - -10.1 - -1 - - - -- [`Number.NEGATIVE_INFINITY`](number/negative_infinity) -- [`Number.POSITIVE_INFINITY`](number/positive_infinity) -- [`Number.isFinite`](number/isfinite) - -Global_Objects/Infinity" Global_Objects/Infinity - ---- ---- - -# WebAssembly.Instance - -A `WebAssembly.Instance` object is a stateful, executable instance of a [`WebAssembly.Module`](module). `Instance` objects contain all the [Exported WebAssembly functions](https://developer.mozilla.org/en-US/docs/WebAssembly/Exported_functions) that allow calling into WebAssembly code from JavaScript. - -## Constructor - -[`WebAssembly.Instance()`](instance/instance) -Creates a new `Instance` object. - -## Instance properties - -[`Instance.prototype.exports`](instance/exports) -Returns an object containing as its members all the functions exported from the WebAssembly module instance, to allow them to be accessed and used by JavaScript. Read-only. - -## Examples - -### Synchronously instantiating a WebAssembly module - -The `WebAssembly.Instance()` constructor function can be called to synchronously instantiate a given [`WebAssembly.Module`](module) object, for example: - - const importObject = { - imports: { - imported_func: function(arg) { - console.log(arg); - } - } - }; - - fetch('simple.wasm').then(response => - response.arrayBuffer() - ).then(bytes => { - let mod = new WebAssembly.Module(bytes); - let instance = new WebAssembly.Instance(mod, importObject); - instance.exports.exported_func(); - }) - -The preferred way to get an `Instance` is asynchronously, for example using the [`WebAssembly.instantiateStreaming()`](instantiatestreaming) function like this: - - const importObject = { - imports: { - imported_func: function(arg) { - console.log(arg); - } - } - }; - - WebAssembly.instantiateStreaming(fetch('simple.wasm'), importObject) - .then(obj => obj.instance.exports.exported_func()); - -This also demonstrates how the `exports` property is used to access exported functions. - -## Specifications - -
    Specification
    WebAssembly JavaScript Interface (WebAssembly JavaScript Interface) -
    - -#instances
    - -`Instance` - -57 - -16 - -52 - -Disabled in the Firefox 52 Extended Support Release (ESR). - -No - -44 - -11 - -57 - -57 - -52 - -Disabled in the Firefox 52 Extended Support Release (ESR). - -43 - -11 - -7.0 - -`Instance` - -57 - -16 - -52 - -Disabled in the Firefox 52 Extended Support Release (ESR). - -No - -44 - -11 - -57 - -57 - -52 - -Disabled in the Firefox 52 Extended Support Release (ESR). - -43 - -11 - -7.0 - -`exports` - -57 - -16 - -52 - -Disabled in the Firefox 52 Extended Support Release (ESR). - -No - -44 - -11 - -57 - -57 - -52 - -Disabled in the Firefox 52 Extended Support Release (ESR). - -43 - -11 - -7.0 - -## See also - -- [WebAssembly](https://developer.mozilla.org/en-US/docs/WebAssembly) overview page -- [WebAssembly concepts](https://developer.mozilla.org/en-US/docs/WebAssembly/Concepts) -- [Using the WebAssembly JavaScript API](https://developer.mozilla.org/en-US/docs/WebAssembly/Using_the_JavaScript_API) - - - -Global_Objects/WebAssembly/Instance" Global_Objects/WebAssembly/Instance - ---- ---- - -# instanceof - -The `instanceof` tests to see if the `prototype` property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value. - -## Syntax - - object instanceof constructor - -### Parameters - -`object` -The object to test. - -`constructor` -Function to test against - -## Description - -The `instanceof` operator tests the presence of `constructor.prototype` in `object`'s prototype chain. - - // defining constructors - function C() {} - function D() {} - - let o = new C() - - // true, because: Object.getPrototypeOf(o) === C.prototype - o instanceof C - - // false, because D.prototype is nowhere in o's prototype chain - o instanceof D - - o instanceof Object // true, because: - C.prototype instanceof Object // true - - C.prototype = {} - let o2 = new C() - - o2 instanceof C // true - - // false, because C.prototype is nowhere in - // o's prototype chain anymore - o instanceof C - - D.prototype = new C() // add C to [[Prototype]] linkage of D - let o3 = new D() - o3 instanceof D // true - o3 instanceof C // true since C.prototype is now in o3's prototype chain - -Note that the value of an `instanceof` test can change based on changes to the `prototype` property of constructors. It can also be changed by changing an object's prototype using `Object.setPrototypeOf`. It is also possible using the non-standard `__proto__` property. - -### `instanceof` and multiple context (e.g. frames or windows) - -Different scopes have different execution environments. This means that they have different built-ins (different global object, different constructors, etc.). This may result in unexpected results. For instance, `[] instanceof window.frames[0].Array` will return `false`, because ` Array.prototype !== ``window.frames[0].Array.prototype ` and arrays inherit from the former. - -This may not make sense at first, but for scripts dealing with multiple frames or windows, and passing objects from one context to another via functions, this will be a valid and strong issue. For instance, you can securely check if a given object is, in fact, an Array using `Array.isArray(myObj)` - -For example, checking if a [Node](https://developer.mozilla.org/en-US/docs/Web/API/Node) is a [SVGElement](https://developer.mozilla.org/en-US/docs/Web/API/SVGElement) in a different context, you can use `myNode instanceof myNode.ownerDocument.defaultView.SVGElement`. - -## Examples - -### Using instanceof with String - -The following example shows the behavior of `instanceof` with `String` objects. - - let literalString = 'This is a literal string'; - let stringObject = new String('String created with constructor'); - - literalString instanceof String; // false, string literal is not a String - stringObject instanceof String; // true - - literalString instanceof Object; // false, string literal is not an Object - stringObject instanceof Object; // true - - stringObject instanceof Date; // false - -### Using instanceof with Date - -The following example shows the behavior of `instanceof` with `Date` objects. - - let myDate = new Date(); - - myDate instanceof Date; // true - myDate instanceof Object; // true - myDate instanceof String; // false - -### Objects created using Object.create() - -The following example shows the behavior of `instanceof` with objects created using `Object.create()` - - function Shape() { - } - - function Rectangle() { - Shape.call(this); // call super constructor. - } - - Rectangle.prototype = Object.create(Shape.prototype); - - Rectangle.prototype.constructor = Rectangle; - - let rect = new Rectangle(); - - rect instanceof Object; // true - rect instanceof Shape; // true - rect instanceof Rectangle; // true - rect instanceof String; // false - - let literalObject = {}; - let nullObject = Object.create(null); - nullObject.name = "My object"; - - literalObject instanceof Object; // true, every object literal has Object.prototype as prototype - ({}) instanceof Object; // true, same case as above - nullObject instanceof Object; // false, prototype is end of prototype chain (null) - -### Demonstrating that `mycar` is of type `Car` and type `Object` - -The following code creates an object type `Car` and an instance of that object type, `mycar`. The `instanceof` operator demonstrates that the `mycar` object is of type `Car` and of type `Object`. - - function Car(make, model, year) { - this.make = make; - this.model = model; - this.year = year; - } - let mycar = new Car('Honda', 'Accord', 1998) - let a = mycar instanceof Car // returns true - let b = mycar instanceof Object // returns true - -### Not an instanceof - -To test if an object is not an `instanceof` a specific constructor, you can do - - if (!(mycar instanceof Car)) { - // Do something, like: - // mycar = new Car(mycar) - } - -This is really different from: - - if (!mycar instanceof Car) - -This will always be `false`. (`!mycar` will be evaluated before `instanceof`, so you always try to know if a boolean is an instance of `Car`). - -## Specifications - -
    Specification
    ECMAScript (ECMA-262) -
    - -The definition of 'Relational Operators' in that specification.
    - -`instanceof` - -1 - -12 - -1 - -5 - -4 - -1 - -1 - -18 - -4 - -10.1 - -1 - - - -- `typeof` -- [`Symbol.hasInstance`](../global_objects/symbol/hasinstance) -- [`Object.prototype.isPrototypeOf`](../global_objects/object/isprototypeof) - - - -Operators/instanceof" Operators/instanceof - ---- ---- - -# WebAssembly.instantiate() - -The `WebAssembly.instantiate()` function allows you to compile and instantiate WebAssembly code. This function has two overloads: - -- The primary overload takes the WebAssembly binary code, in the form of a [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays) or [`ArrayBuffer`](../arraybuffer), and performs both compilation and instantiation in one step. The returned `Promise` resolves to both a compiled [`WebAssembly.Module`](module) and its first [`WebAssembly.Instance`](instance). -- The secondary overload takes an already-compiled [`WebAssembly.Module`](module) and returns a `Promise` that resolves to an `Instance` of that `Module`. This overload is useful if the `Module` has already been compiled. - -**Warning:** This method is not the most efficient way of fetching and instantiating wasm modules. If at all possible, you should use the newer [`WebAssembly.instantiateStreaming()`](instantiatestreaming) method instead, which fetches, compiles, and instantiates a module all in one step, directly from the raw bytecode, so doesn't require conversion to an [`ArrayBuffer`](../arraybuffer). - -## Syntax - -### Primary overload — taking wasm binary code - - WebAssembly.instantiate(bufferSource, importObject); - -#### Parameters - -_bufferSource_ -A [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays) or [`ArrayBuffer`](../arraybuffer) containing the binary code of the .wasm module you want to compile. - -_importObject_ Optional -An object containing the values to be imported into the newly-created `Instance`, such as functions or [`WebAssembly.Memory`](memory) objects. There must be one matching property for each declared import of the compiled module or else a [`WebAssembly.LinkError`](linkerror) is thrown. - -#### Return value - -A `Promise` that resolves to a `ResultObject` which contains two fields: - -- `module`: A [`WebAssembly.Module`](module) object representing the compiled WebAssembly module. This `Module` can be instantiated again, shared via [`postMessage()`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage) or [cached in IndexedDB](https://developer.mozilla.org/en-US/docs/WebAssembly/Caching_modules). -- `instance`: A [`WebAssembly.Instance`](instance) object that contains all the [Exported WebAssembly functions](https://developer.mozilla.org/en-US/docs/WebAssembly/Exported_functions). - -#### Exceptions - -- If either of the parameters are not of the correct type or structure, a [`TypeError`](../typeerror) is thrown. -- If the operation fails, the promise rejects with a [`WebAssembly.CompileError`](compileerror), [`WebAssembly.LinkError`](linkerror), or [`WebAssembly.RuntimeError`](runtimeerror), depending on the cause of the failure. - -### Secondary overload — taking a module object instance - - WebAssembly.instantiate(module, importObject); - -#### Parameters - -_module_ -The [`WebAssembly.Module`](module) object to be instantiated. - -_importObject_ Optional -An object containing the values to be imported into the newly-created `Instance`, such as functions or [`WebAssembly.Memory`](memory) objects. There must be one matching property for each declared import of `module` or else a [`WebAssembly.LinkError`](linkerror) is thrown. - -#### Return value - -A `Promise` that resolves to an [`WebAssembly.Instance`](instance) object. - -#### Exceptions - -- If either of the parameters are not of the correct type or structure, a [`TypeError`](../typeerror) is thrown. -- If the operation fails, the promise rejects with a [`WebAssembly.CompileError`](compileerror), [`WebAssembly.LinkError`](linkerror), or [`WebAssembly.RuntimeError`](runtimeerror), depending on the cause of the failure. - -## Examples - -**Note**: You'll probably want to use [`WebAssembly.instantiateStreaming()`](instantiatestreaming) in most cases, as it is more efficient than `instantiate()`. - -### First overload example - -After fetching some WebAssembly bytecode using fetch, we compile and instantiate the module using the [`WebAssembly.instantiate()`](instantiate) function, importing a JavaScript function into the WebAssembly Module in the process. We then call an [Exported WebAssembly function](https://developer.mozilla.org/en-US/docs/WebAssembly/Exported_functions) that is exported by the `Instance`. - - var importObject = { - imports: { - imported_func: function(arg) { - console.log(arg); - } - } - }; - - fetch('simple.wasm').then(response => - response.arrayBuffer() - ).then(bytes => - WebAssembly.instantiate(bytes, importObject) - ).then(result => - result.instance.exports.exported_func() - ); - -**Note:** You can also find this example at [index.html](https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/index.html) on GitHub ([view it live also](https://mdn.github.io/webassembly-examples/js-api-examples/)). - -### Second overload example - -The following example (see our [index-compile.html](https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/index-compile.html) demo on GitHub, and [view it live](https://mdn.github.io/webassembly-examples/js-api-examples/index-compile.html) also) compiles the loaded simple.wasm byte code using the [`WebAssembly.compileStreaming()`](compilestreaming) method and then sends it to a [worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) using [`postMessage()`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage). - - var worker = new Worker("wasm_worker.js"); - - WebAssembly.compileStreaming(fetch('simple.wasm')) - .then(mod => - worker.postMessage(mod) - ); - -In the worker (see `wasm_worker.js`) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. When the module is received, we create an instance from it using the [`WebAssembly.instantiate()`](instantiate) method and invoke an exported function from inside it. - - var importObject = { - imports: { - imported_func: function(arg) { - console.log(arg); - } - } - }; - - onmessage = function(e) { - console.log('module received from main thread'); - var mod = e.data; - - WebAssembly.instantiate(mod, importObject).then(function(instance) { - instance.exports.exported_func(); - }); - }; - -## Specifications - -
    Specification
    WebAssembly JavaScript Interface (WebAssembly JavaScript Interface) -
    - -#dom-webassembly-instantiate
    - -`instantiate` - -57 - -16 - -52 - -Disabled in the Firefox 52 Extended Support Release (ESR). - -No - -44 - -11 - -57 - -57 - -52 - -Disabled in the Firefox 52 Extended Support Release (ESR). - -43 - -11 - -7.0 - -## See also - -- [WebAssembly](https://developer.mozilla.org/en-US/docs/WebAssembly) overview page -- [WebAssembly concepts](https://developer.mozilla.org/en-US/docs/WebAssembly/Concepts) -- [Using the WebAssembly JavaScript API](https://developer.mozilla.org/en-US/docs/WebAssembly/Using_the_JavaScript_API) - - - -Global_Objects/WebAssembly/instantiate" Global_Objects/WebAssembly/instantiate - ---- ---- - -# WebAssembly.instantiateStreaming() - -The `WebAssembly.instantiateStreaming()` function compiles and instantiates a WebAssembly module directly from a streamed underlying source. This is the most efficient, optimized way to load wasm code. - -## Syntax - - WebAssembly.instantiateStreaming(source, importObject) - -### Parameters - -_source_ -A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) object or a promise that will fulfill with one, representing the underlying source of a .wasm module you want to stream, compile, and instantiate. - -_importObject_ Optional -An object containing the values to be imported into the newly-created `Instance`, such as functions or [`WebAssembly.Memory`](memory) objects. There must be one matching property for each declared import of the compiled module or else a `WebAssembly.LinkError` is thrown. - -### Return value - -A `Promise` that resolves to a `ResultObject` which contains two fields: - -- `module`: A [`WebAssembly.Module`](module) object representing the compiled WebAssembly module. This `Module` can be instantiated again or shared via [postMessage()](https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage). -- `instance`: A [`WebAssembly.Instance`](instance) object that contains all the [Exported WebAssembly functions](https://developer.mozilla.org/en-US/docs/WebAssembly/Exported_functions). - -### Exceptions - -- If either of the parameters are not of the correct type or structure, a [`TypeError`](../typeerror) is thrown. -- If the operation fails, the promise rejects with a [`WebAssembly.CompileError`](compileerror), [`WebAssembly.LinkError`](linkerror), or [`WebAssembly.RuntimeError`](runtimeerror), depending on the cause of the failure. - -## Examples - -### Instantiating streaming - -The following example (see our [instantiate-streaming.html](https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/instantiate-streaming.html) demo on GitHub, and [view it live](https://mdn.github.io/webassembly-examples/js-api-examples/instantiate-streaming.html) also) directly streams a .wasm module from an underlying source then compiles and instantiates it, the promise fulfilling with a `ResultObject`. Because the `instantiateStreaming()` function accepts a promise for a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) object, you can directly pass it a [`WindowOrWorkerGlobalScope.fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch) call, and it will pass the response into the function when it fulfills. - - var importObject = { imports: { imported_func: arg => console.log(arg) } }; - - WebAssembly.instantiateStreaming(fetch('simple.wasm'), importObject) - .then(obj => obj.instance.exports.exported_func()); - -The `ResultObject`'s instance member is then accessed, and the contained exported function invoked. - -**Note:** For this to work, `.wasm` files should be returned with an `application/wasm` MIME type by the server. - -## Specifications - -
    Specification
    WebAssembly Web API (WebAssembly Web API) -
    - -#dom-webassembly-instantiatestreaming
    - -`instantiateStreaming` - -61 - -16 - -58 - -No - -47 - -No - -61 - -61 - -58 - -45 - -No - -8.0 - -## See also - -- [WebAssembly](https://developer.mozilla.org/en-US/docs/WebAssembly) overview page -- [WebAssembly concepts](https://developer.mozilla.org/en-US/docs/WebAssembly/Concepts) -- [Using the WebAssembly JavaScript API](https://developer.mozilla.org/en-US/docs/WebAssembly/Using_the_JavaScript_API) - - - -Global_Objects/WebAssembly/instantiateStreaming" Global_Objects/WebAssembly/instantiateStreaming - ---- ---- - -# Int16Array - -The `Int16Array` typed array represents an array of twos-complement 16-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](dataview) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). - -## Constructor - -[`Int16Array()`](int16array/int16array) -Creates a new `Int16Array` object. - -## Static properties - -[`Int16Array.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) -Returns a number value of the element size. `2` in the case of an `Int16Array`. - -[`Int16Array.name`](typedarray/name) -Returns the string value of the constructor name. In the case of the `Int16Array` type: "`Int16Array`". - -## Static methods - -[`Int16Array.from()`](typedarray/from) -Creates a new `Int16Array` from an array-like or iterable object. See also [`Array.from()`](array/from). - -[`Int16Array.of()`](typedarray/of) -Creates a new `Int16Array` with a variable number of arguments. See also [`Array.of()`](array/of). - -## Instance properties - -[`Int16Array.prototype.buffer`](typedarray/buffer) -Returns the [`ArrayBuffer`](arraybuffer) referenced by the `Int16Array`. Fixed at construction time and thus **read only**. - -[`Int16Array.prototype.byteLength`](typedarray/bytelength) -Returns the length (in bytes) of the `Int16Array` from the start of its [`ArrayBuffer`](arraybuffer). Fixed at construction time and thus **read only.** - -[`Int16Array.prototype.byteOffset`](typedarray/byteoffset) -Returns the offset (in bytes) of the `Int16Array` from the start of its [`ArrayBuffer`](arraybuffer). Fixed at construction time and thus **read only.** - -[`Int16Array.prototype.length`](typedarray/length) -Returns the number of elements held in the `Int16Array`. Fixed at construction time and thus **read only.** - -## Instance methods - -[`Int16Array.prototype.copyWithin()`](typedarray/copywithin) -Copies a sequence of array elements within the array. See also [`Array.prototype.copyWithin()`](array/copywithin). - -[`Int16Array.prototype.entries()`](typedarray/entries) -Returns a new _array iterator_ object that contains the key/value pairs for each index in the array. See also [`Array.prototype.entries()`](array/entries). - -[`Int16Array.prototype.every()`](typedarray/every) -Tests whether all elements in the array pass the test provided by a function. See also [`Array.prototype.every()`](array/every). - -[`Int16Array.prototype.fill()`](typedarray/fill) -Fills all the elements of an array from a start index to an end index with a static value. See also [`Array.prototype.fill()`](array/fill). - -[`Int16Array.prototype.filter()`](typedarray/filter) -Creates a new array with all of the elements of this array for which the provided filtering function returns `true`. See also [`Array.prototype.filter()`](array/filter). - -[`Int16Array.prototype.find()`](typedarray/find) -Returns the found value in the array, if an element in the array satisfies the provided testing function or `undefined` if not found. See also [`Array.prototype.find()`](array/find). - -[`Int16Array.prototype.findIndex()`](typedarray/findindex) -Returns the found index in the array, if an element in the array satisfies the provided testing function or `-1` if not found. See also [`Array.prototype.findIndex()`](array/findindex). - -[`Int16Array.prototype.forEach()`](typedarray/foreach) -Calls a function for each element in the array. See also [`Array.prototype.forEach()`](array/foreach). - -[`Int16Array.prototype.includes()`](typedarray/includes) -Determines whether a typed array includes a certain element, returning `true` or `false` as appropriate. See also [`Array.prototype.includes()`](array/includes). - -[`Int16Array.prototype.indexOf()`](typedarray/indexof) -Returns the first (least) index of an element within the array equal to the specified value, or `-1` if none is found. See also [`Array.prototype.indexOf()`](array/indexof). - -[`Int16Array.prototype.join()`](typedarray/join) -Joins all elements of an array into a string. See also [`Array.prototype.join()`](array/join). - -[`Int16Array.prototype.keys()`](typedarray/keys) -Returns a new _array iterator_ that contains the keys for each index in the array. See also [`Array.prototype.keys()`](array/keys). - -[`Int16Array.prototype.lastIndexOf()`](typedarray/lastindexof) -Returns the last (greatest) index of an element within the array equal to the specified value, or `-1` if none is found. See also [`Array.prototype.lastIndexOf()`](array/lastindexof). - -[`Int16Array.prototype.map()`](typedarray/map) -Creates a new array with the results of calling a provided function on every element in this array. See also [`Array.prototype.map()`](array/map). - -[`Int16Array.prototype.reduce()`](typedarray/reduce) -Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value. See also [`Array.prototype.reduce()`](array/reduce). - -[`Int16Array.prototype.reduceRight()`](typedarray/reduceright) -Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value. See also [`Array.prototype.reduceRight()`](array/reduceright). - -[`Int16Array.prototype.reverse()`](typedarray/reverse) -Reverses the order of the elements of an array — the first becomes the last, and the last becomes the first. See also [`Array.prototype.reverse()`](array/reverse). - -[`Int16Array.prototype.set()`](typedarray/set) -Stores multiple values in the typed array, reading input values from a specified array. - -[`Int16Array.prototype.slice()`](typedarray/slice) -Extracts a section of an array and returns a new array. See also [`Array.prototype.slice()`](array/slice). - -[`Int16Array.prototype.some()`](typedarray/some) -Returns `true` if at least one element in this array satisfies the provided testing function. See also [`Array.prototype.some()`](array/some). - -[`Int16Array.prototype.sort()`](typedarray/sort) -Sorts the elements of an array in place and returns the array. See also [`Array.prototype.sort()`](array/sort). - -[`Int16Array.prototype.subarray()`](typedarray/subarray) -Returns a new `Int16Array` from the given start and end element index. - -[`Int16Array.prototype.values()`](typedarray/values) -Returns a new **array iterator object that contains the values for each index in the array. See also [`Array.prototype.values()`](array/values).** - -**[`Int16Array.prototype.toLocaleString()`](typedarray/tolocalestring)** -**Returns a localized string representing the array and its elements. See also [`Array.prototype.toLocaleString()`](array/tolocalestring).** - -**[`Int16Array.prototype.toString()`](typedarray/tostring)** -**Returns a string representing the array and its elements. See also [`Array.prototype.toString()`](array/tostring).** - -**[`Int16Array.prototype[@@iterator]()`](typedarray/@@iterator)** -**Returns a new _array iterator_ object that contains the values for each index in the array.** - -## Examples - -### Different ways to create an Int16Array - - // From a length - var int16 = new Int16Array(2); - int16[0] = 42; - console.log(int16[0]); // 42 - console.log(int16.length); // 2 - console.log(int16.BYTES_PER_ELEMENT); // 2 - - // From an array - var arr = new Int16Array([21,31]); - console.log(arr[1]); // 31 - - // From another TypedArray - var x = new Int16Array([21, 31]); - var y = new Int16Array(x); - console.log(y[0]); // 21 - - // From an ArrayBuffer - var buffer = new ArrayBuffer(8); - var z = new Int16Array(buffer, 0, 4); - - // From an iterable - var iterable = function*(){ yield* [1,2,3]; }(); - var int16 = new Int16Array(iterable); - // Int16Array[1, 2, 3] - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#table-49
    - -`Int16Array` - -7 - -12 - -4 - -10 - -11.6 - -5.1 - -4 - -18 - -4 - -12 - -4.2 - -1.0 - -`Int16Array` - -7 - -12 - -4 - -10 - -11.6 - -5.1 - -4 - -18 - -4 - -12 - -4.2 - - - -- **[JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)** -- **[`ArrayBuffer`](arraybuffer)** -- **[`DataView`](dataview)** - -Global_Objects/Int16Array" Global_Objects/Int16Array - ---- ---- - -# Int32Array - -The `Int32Array()` typed array constructor creates an array of twos-complement 32-bit signed integers in the platform byte order. If control over byte order is needed, use [`DataView`](dataview) instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). - -## Syntax - - new Int32Array(); // new in ES2017 - new Int32Array(length); - new Int32Array(typedArray); - new Int32Array(object); - - new Int32Array(buffer); - new Int32Array(buffer, byteOffset); - new Int32Array(buffer, byteOffset, length); - -### Parameters - -`length` -When called with a `length` argument, an internal array buffer is created in memory, of size `length` _multiplied by `BYTES_PER_ELEMENT`_ bytes, containing zeros. - -`typedArray` -When called with a `typedArray` argument, which can be an object of any of the typed array types (such as `Int32Array`), the `typedArray` gets copied into a new typed array. Each value in `typedArray` is converted to the corresponding type of the constructor before being copied into the new array. The length of the new typed array will be same as the length of the `typedArray` argument. - -`object` -When called with an `object` argument, a new typed array is created as if by the `TypedArray.from()` method. - -`buffer`, `byteOffset`, `length` -When called with a `buffer`, and optionally a `byteOffset` and a `length` argument, a new typed array view is created that views the specified [`ArrayBuffer`](arraybuffer). The `byteOffset` and `length` parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of `buffer` is viewed; if only `length` is omitted, the remainder of `buffer` is viewed. - -## Examples - -### Different ways to create an Int32Array - - // From a length - var int32 = new Int32Array(2); - int32[0] = 42; - console.log(int32[0]); // 42 - console.log(int32.length); // 2 - console.log(int32.BYTES_PER_ELEMENT); // 4 - - // From an array - var arr = new Int32Array([21,31]); - console.log(arr[1]); // 31 - - // From another TypedArray - var x = new Int32Array([21, 31]); - var y = new Int32Array(x); - console.log(y[0]); // 21 - - // From an ArrayBuffer - var buffer = new ArrayBuffer(16); - var z = new Int32Array(buffer, 0, 4); - - // From an iterable - var iterable = function*(){ yield* [1,2,3]; }(); - var int32 = new Int32Array(iterable); - // Int32Array[1, 2, 3] - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-typedarray-constructors
    - -`Int32Array` - -7 - -12 - -4 - -10 - -11.6 - -5.1 - -4 - -18 - -4 - -12 - -4.2 - -1.0 - -`constructor_without_arguments` - -7 - -12 - -55 - -10 - -11.6 - -5.1 - -≤37 - -18 - -55 - -12 - -5 - -1.0 - -`iterable_allowed` - -39 - -14 - -52 - -No - -26 - -10 - -39 - -39 - -52 - -26 - -10 - -4.0 - -`new_required` - -7 - -14 - -44 - -No - -15 - -5.1 - -≤37 - -18 - -44 - -14 - -5 - -1.0 - -### Compatibility notes - -Starting with ECMAScript 2015, `Int32Array` constructors require to be constructed with a [`new`](../operators/new) operator. Calling a `Int32Array` constructor as a function without `new`, will throw a [`TypeError`](typeerror) from now on. - - var dv = Int32Array([1, 2, 3]); - // TypeError: calling a builtin Int32Array constructor - // without new is forbidden - - var dv = new Int32Array([1, 2, 3]); - -## See also - -- [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays) -- [`ArrayBuffer`](arraybuffer) -- [`DataView`](dataview) - -Global_Objects/Int32Array" Global_Objects/Int32Array - ---- ---- - -# Int8Array - -The `Int8Array` typed array represents an array of twos-complement 8-bit signed integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). - -## Constructor - -[`Int8Array()`](int8array/int8array) -Creates a new `Int8Array` object. - -## Static properties - -[`Int8Array.BYTES_PER_ELEMENT`](typedarray/bytes_per_element) -Returns a number value of the element size. `1` in the case of an `Int8Array`. - -[`Int8Array.name`](typedarray/name) -Returns the string value of the constructor name. In the case of the `Int8Array` type: "`Int8Array`". - -## Static methods - -[`Int8Array.from()`](typedarray/from) -Creates a new `Int8Array` from an array-like or iterable object. See also [`Array.from()`](array/from). - -[`Int8Array.of()`](typedarray/of) -Creates a new `Int8Array` with a variable number of arguments. See also [`Array.of()`](array/of). - -## Instance properties - -[`Int8Array.prototype.buffer`](typedarray/buffer) -Returns the [`ArrayBuffer`](arraybuffer) referenced by the `Int8Array`. Fixed at construction time and thus **read only**. - -[`Int8Array.prototype.byteLength`](typedarray/bytelength) -Returns the length (in bytes) of the `Int8Array` from the start of its [`ArrayBuffer`](arraybuffer). Fixed at construction time and thus **read only.** - -[`Int8Array.prototype.byteOffset`](typedarray/byteoffset) -Returns the offset (in bytes) of the `Int8Array` from the start of its [`ArrayBuffer`](arraybuffer). Fixed at construction time and thus **read only.** - -[`Int8Array.prototype.length`](typedarray/length) -Returns the number of elements held in the `Int8Array`. Fixed at construction time and thus **read only.** - -## Instance methods - -[`Int8Array.prototype.copyWithin()`](typedarray/copywithin) -Copies a sequence of array elements within the array. See also [`Array.prototype.copyWithin()`](array/copywithin). - -[`Int8Array.prototype.entries()`](typedarray/entries) -Returns a new _array iterator_ object that contains the key/value pairs for each index in the array. See also [`Array.prototype.entries()`](array/entries). - -[`Int8Array.prototype.every()`](typedarray/every) -Tests whether all elements in the array pass the test provided by a function. See also [`Array.prototype.every()`](array/every). - -[`Int8Array.prototype.fill()`](typedarray/fill) -Fills all the elements of an array from a start index to an end index with a static value. See also [`Array.prototype.fill()`](array/fill). - -[`Int8Array.prototype.filter()`](typedarray/filter) -Creates a new array with all of the elements of this array for which the provided filtering function returns `true`. See also [`Array.prototype.filter()`](array/filter). - -[`Int8Array.prototype.find()`](typedarray/find) -Returns the found value in the array, if an element in the array satisfies the provided testing function or `undefined` if not found. See also [`Array.prototype.find()`](array/find). - -[`Int8Array.prototype.findIndex()`](typedarray/findindex) -Returns the found index in the array, if an element in the array satisfies the provided testing function or `-1` if not found. See also [`Array.prototype.findIndex()`](array/findindex). - -[`Int8Array.prototype.forEach()`](typedarray/foreach) -Calls a function for each element in the array. See also [`Array.prototype.forEach()`](array/foreach). - -[`Int8Array.prototype.includes()`](typedarray/includes) -Determines whether a typed array includes a certain element, returning `true` or `false` as appropriate. See also [`Array.prototype.includes()`](array/includes). - -[`Int8Array.prototype.indexOf()`](typedarray/indexof) -Returns the first (least) index of an element within the array equal to the specified value, or `-1` if none is found. See also [`Array.prototype.indexOf()`](array/indexof). - -[`Int8Array.prototype.join()`](typedarray/join) -Joins all elements of an array into a string. See also [`Array.prototype.join()`](array/join). - -[`Int8Array.prototype.keys()`](typedarray/keys) -Returns a new _array iterator_ that contains the keys for each index in the array. See also [`Array.prototype.keys()`](array/keys). - -[`Int8Array.prototype.lastIndexOf()`](typedarray/lastindexof) -Returns the last (greatest) index of an element within the array equal to the specified value, or `-1` if none is found. See also [`Array.prototype.lastIndexOf()`](array/lastindexof). - -[`Int8Array.prototype.map()`](typedarray/map) -Creates a new array with the results of calling a provided function on every element in this array. See also [`Array.prototype.map()`](array/map). - -[`Int8Array.prototype.reduce()`](typedarray/reduce) -Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value. See also [`Array.prototype.reduce()`](array/reduce). - -[`Int8Array.prototype.reduceRight()`](typedarray/reduceright) -Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value. See also [`Array.prototype.reduceRight()`](array/reduceright). - -[`Int8Array.prototype.reverse()`](typedarray/reverse) -Reverses the order of the elements of an array — the first becomes the last, and the last becomes the first. See also [`Array.prototype.reverse()`](array/reverse). - -[`Int8Array.prototype.set()`](typedarray/set) -Stores multiple values in the typed array, reading input values from a specified array. - -[`Int8Array.prototype.slice()`](typedarray/slice) -Extracts a section of an array and returns a new array. See also [`Array.prototype.slice()`](array/slice). - -[`Int8Array.prototype.some()`](typedarray/some) -Returns `true` if at least one element in this array satisfies the provided testing function. See also [`Array.prototype.some()`](array/some). - -[`Int8Array.prototype.sort()`](typedarray/sort) -Sorts the elements of an array in place and returns the array. See also [`Array.prototype.sort()`](array/sort). - -[`Int8Array.prototype.subarray()`](typedarray/subarray) -Returns a new `Int8Array` from the given start and end element index. - -[`Int8Array.prototype.values()`](typedarray/values) -Returns a new _array iterator_ object that contains the values for each index in the array. See also [`Array.prototype.values()`](array/values). - -[`Int8Array.prototype.toLocaleString()`](typedarray/tolocalestring) -Returns a localized string representing the array and its elements. See also [`Array.prototype.toLocaleString()`](array/tolocalestring). - -[`Int8Array.prototype.toString()`](typedarray/tostring) -Returns a string representing the array and its elements. See also [`Array.prototype.toString()`](array/tostring). - -[`Int8Array.prototype[@@iterator]()`](typedarray/@@iterator) -Returns a new _array iterator_ object that contains the values for each index in the array. - -## Examples - -### Different ways to create an Int8Array - - // From a length - var int8 = new Int8Array(2); - int8[0] = 42; - console.log(int8[0]); // 42 - console.log(int8.length); // 2 - console.log(int8.BYTES_PER_ELEMENT); // 1 - - // From an array - var arr = new Int8Array([21,31]); - console.log(arr[1]); // 31 - - // From another TypedArray - var x = new Int8Array([21, 31]); - var y = new Int8Array(x); - console.log(y[0]); // 21 - - // From an ArrayBuffer - var buffer = new ArrayBuffer(8); - var z = new Int8Array(buffer, 1, 4); - - // From an iterable - var iterable = function*(){ yield* [1,2,3]; }(); - var int8 = new Int8Array(iterable); - // Int8Array[1, 2, 3] - -## Specifications - -
    Specification
    ECMAScript (ECMA-262) -
    - -The definition of 'TypedArray constructors' in that specification.
    - -`Int8Array` - -7 - -12 - -4 - -10 - -11.6 - -5.1 - -4 - -18 - -4 - -12 - -4.2 - -1.0 - -`Int8Array` - -7 - -12 - -4 - -10 - -11.6 - -5.1 - -4 - -18 - -4 - -12 - -4.2 - - - -- [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays) -- [`ArrayBuffer`](arraybuffer) -- [`DataView`](dataview) - -Global_Objects/Int8Array" Global_Objects/Int8Array - ---- ---- - -# InternalError - -**Non-standard** - -This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. - -The `InternalError` indicates an error that occurred internally in the JavaScript engine. - -Example cases are mostly when something is too large, e.g.: - -- "too many switch cases", -- "too many parentheses in regular expression", -- "array initializer too large", -- "too much recursion". - -## Constructor - -[`InternalError()`](internalerror/internalerror) -Creates a new `InternalError` object. - -## Instance properties - -[`InternalError.prototype.message`](error/message) -Error message. Inherited from [`Error`](error). - -[`InternalError.prototype.name`](error/name) -Error name. Inherited from [`Error`](error). - -[`InternalError.prototype.fileName`](error/filename) -Path to file that raised this error. Inherited from [`Error`](error). - -[`InternalError.prototype.lineNumber`](error/linenumber) -Line number in file that raised this error. Inherited from [`Error`](error). - -[`InternalError.prototype.columnNumber`](error/columnnumber) -Column number in line that raised this error. Inherited from [`Error`](error). - -[`InternalError.prototype.stack`](error/stack) -Stack trace. Inherited from [`Error`](error). - -## Examples - -### Too much recursion - -This recursive function runs 10 times, as per the exit condition. - - function loop(x) { - if (x >= 10) // "x >= 10" is the exit condition - return; - // do stuff - loop(x + 1); // the recursive call - } - loop(0); - -Setting this condition to an extremely high value, won't work: - - function loop(x) { - if (x >= 1000000000000) - return; - // do stuff - loop(x + 1); - } - loop(0); - - // InternalError: too much recursion - -For more information, see [InternalError: too much recursion.](../errors/too_much_recursion) - -## Specifications - -Not part of any standard. - -`InternalError` - -No - -No - -1 - -No - -No - -No - -No - -No - -4 - -No - -No - -No - -`InternalError` - -No - -No - -1 - -No - -No - -No - -No - -No - -4 - -No - -No - -No - -## See also - -- [`Error`](error) -- [InternalError: too much recursion](../errors/too_much_recursion) - -Global_Objects/InternalError" Global_Objects/InternalError - ---- ---- - -# Intl - -The `Intl` object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. The `Intl` object provides access to several constructors as well as functionality common to the internationalization constructors and other language sensitive functions. - -## Constructor properties - -[`Intl.Collator()`](intl/collator/collator) -Constructor for collators, which are objects that enable language-sensitive string comparison. - -[`Intl.DateTimeFormat()`](intl/datetimeformat/datetimeformat) -Constructor for objects that enable language-sensitive date and time formatting. - -[`Intl.DisplayNames()`](intl/displaynames/displaynames) -Constructor for objects that enable the consistent translation of language, region and script display names. - -[`Intl.ListFormat()`](intl/listformat/listformat) -Constructor for objects that enable language-sensitive list formatting. - -[`Intl.Locale()`](intl/locale/locale) -Constructor for objects that represents a Unicode locale identifier. - -[`Intl.NumberFormat()`](intl/numberformat/numberformat) -Constructor for objects that enable language-sensitive number formatting. - -[`Intl.PluralRules()`](intl/pluralrules/pluralrules) -Constructor for objects that enable plural-sensitive formatting and language-specific rules for plurals. - -[`Intl.RelativeTimeFormat()`](intl/relativetimeformat/relativetimeformat) -Constructor for objects that enable language-sensitive relative time formatting. - -## Static methods - -[`Intl.getCanonicalLocales()`](intl/getcanonicallocales) -Returns canonical locale names. - -## Locale identification and negotiation - -The internationalization constructors as well as several language sensitive methods of other constructors (listed under [See also](#see_also)) use a common pattern for identifying locales and determining the one they will actually use: they all accept `locales` and `options` arguments, and negotiate the requested locale(s) against the locales they support using an algorithm specified in the `options.localeMatcher` property. - -### locales argument - -The `locales` argument is used to determine the locale used in a given operation. The JavaScript implementation examines `locales`, and then computes a locale it understands that comes closest to satisfying the expressed preference. `locales` may be: - -- `undefined` (or omitted): The implementation's default locale will be used. -- A locale: A locale identifier or an `Intl.Locale` object that wraps a locale identifier. -- A list of locales: Any other value, that will be converted into an object and then treated as an array of locales. - -In the latter two cases, the actual locale used is the best-supported locale determined by [locale negotiation](#locale_negotiation). - -A locale identifier is a string that consists of: - -1. a language subtag, -2. (optionally) a script subtag, -3. (optionally) a region (or country) subtag, -4. (optionally) one or more variant subtags (all of which must be unique), -5. (optionally) one or more BCP 47 extension sequences, and -6. (optionally) a private-use extension sequence - -...with all present subtags and sequences separated by hyphens. Locale identifiers are case-insensitive ASCII. However, it's conventional to use title case (first letter capitalized, successive letters lower case) for script subtags, upper case for region subtags, and lower case for everything else. For example: - -- "`hi`": Hindi (language) -- "`de-AT`": German (language) as used in Austria (region) -- "`zh-Hans-CN`": Chinese (language) written in simplified characters (script) as used in China (region) -- "`en-emodeng`": English (language) in the "Early modern English" dialect (variant) - -Subtags identifying languages, scripts, regions (including countries), and (rarely used) variants are registered in the [IANA Language Subtag Registry](https://www.iana.org/assignments/language-subtag-registry). This registry is periodically updated over time, and implementations may not always be up to date, so don't rely too much on subtags being universally supported. - -BCP 47 extension sequences consist of a single digit or letter (other than `"x"`) and one or more two- to eight-letter or digit subtags separated by hyphens. Only one sequence is permitted for each digit or letter: "`de-a-foo-a-foo`" is invalid. BCP 47 extension subtags are defined in the [Unicode CLDR Project](https://github.com/unicode-org/cldr/tree/master/common/bcp47). Currently only two extensions have defined semantics: - -- The `"u"` (Unicode) extension can be used to request additional customization of [`Intl/Collator`](intl/collator), [`Intl/NumberFormat`](intl/numberformat), or [`Intl/DateTimeFormat`](intl/datetimeformat) objects. Examples: - - "`de-DE-u-co-phonebk`": Use the phonebook variant of the German sort order, which interprets umlauted vowels as corresponding character pairs: ä → ae, ö → oe, ü → ue. - - "`th-TH-u-nu-thai`": Use Thai digits (๐, ๑, ๒, ๓, ๔, ๕, ๖, ๗, ๘, ๙) in number formatting. - - "`ja-JP-u-ca-japanese`": Use the Japanese calendar in date and time formatting, so that 2013 is expressed as the year 25 of the Heisei period, or 平成 25. - - "`en-GB-u-ca-islamic`": use British English with the Islamic (Hijri) calendar, where the Gregorian date 14 October, 2017 is the Hijri date 24 Muharram, 1439. -- The `"t"` (transformed) extension indicates transformed content: for example, text that was translated from another locale. No `Intl` functionality currently considers the `"t"` extension. However, this extension sometimes contains a nested locale (with no extensions): for example, the transformed extension in "`de-t-en`" contains the locale identifier for English. If a nested locale is present, it must be a valid locale identifier. For example, because "`en-emodeng-emodeng`" is invalid (because it contains a duplicate `emodeng` variant subtag), "`de-t-en-emodeng-emodeng`" is also invalid. - -Finally, a private-use extension sequence using the letter `"x"` may appear, followed by one or more one- to eight-letter or digit subtags separated by hyphens. This allows applications to encode information for their own private use, that will be ignored by all `Intl` operations. - -### Locale negotiation - -The list of locales specified by the `locales` argument, after Unicode extensions have been removed from them, is interpreted as a prioritized request from the application. The runtime compares it against the locales it has available and picks the best one available. Two matching algorithms exist: the "`lookup`" matcher follows the Lookup algorithm specified in [BCP 47](https://datatracker.ietf.org/doc/html/rfc4647#section-3.4); the "`best fit`" matcher lets the runtime provide a locale that's at least, but possibly more, suited for the request than the result of the Lookup algorithm. If the application doesn't provide a `locales` argument, or the runtime doesn't have a locale that matches the request, then the runtime's default locale is used. The matcher can be selected using a property of the `options` argument (see below). - -If the selected locale identifier had a Unicode extension sequence, that extension is now used to customize the constructed object or the behavior of the function. Each constructor or function supports only a subset of the keys defined for the Unicode extension, and the supported values often depend on the locale identifier. For example, the "`co`" key (collation) is only supported by [`Intl/Collator`](intl/collator), and its "`phonebk`" value is only supported for German. - -### options argument - -The `options` argument must be an object with properties that vary between constructors and functions. If the `options` argument is not provided or is undefined, default values are used for all properties. - -One property is supported by all language sensitive constructors and functions: The `localeMatcher` property, whose value must be a string "`lookup`" or "`best fit`" and which selects one of the locale matching algorithms described above. - -## Examples - -### Formatting dates and numbers - -You can use `Intl` to format dates and numbers in a form that's conventional for a specific language and region: - - const count = 26254.39; - const date = new Date("2012-05-24"); - - function log(locale) { - console.log( - `${new Intl.DateTimeFormat(locale).format(date)}${new Intl.NumberFormat(locale).format(count)}` - ); - } - - log("en-US"); - // expected output: 5/24/2012 26,254.39 - - log("de-DE"); - // expected output: 24.5.2012 26.254,39 - -## Specifications - -
    Specification
    ECMAScript Internationalization API Specification (ECMAScript Internationalization API) -
    - -#intl-object
    - -`Collator` - -24 - -12 - -29 - -11 - -15 - -10 - -4.4 - -25 - -56 - -14 - -10 - -1.5 - -`DateTimeFormat` - -24 - -12 - -29 - -11 - -15 - -10 - -4.4 - -25 - -56 - -14 - -10 - -1.5 - -`DisplayNames` - -81 - -81 - -86 - -No - -68 - -14.1 - -81 - -81 - -86 - -58 - -14.5 - -No - -`Intl` - -24 - -12 - -29 - -11 - -15 - -10 - -4.4 - -25 - -56 - -14 - -10 - -1.5 - -`getCanonicalLocales` - -54 - -16 - -48 - -No - -No - -11 - -No - -No - -56 - -No - -11 - -No - -`@@toStringTag` - -86 - -86 - -83 - -No - -72 - -14 - -86 - -86 - -83 - -No - -14 - -No - -`ListFormat` - -72 - -79 - -78 - -No - -60 - -14.1 - -72 - -72 - -79 - -51 - -14.5 - -No - -`Locale` - -74 - -79 - -75 - -No - -62 - -14 - -74 - -74 - -79 - -53 - -14 - -11.0 - -`NumberFormat` - -24 - -12 - -29 - -11 - -15 - -10 - -4.4 - -25 - -56 - -14 - -10 - -1.5 - -`PluralRules` - -63 - -18 - -58 - -No - -50 - -13 - -63 - -63 - -58 - -46 - -13 - -8.0 - -`RelativeTimeFormat` - -71 - -79 - -65 - -No - -58 - -14 - -71 - -71 - -65 - -50 - -14 - -10.0 - -## See also - -- Introduction: [The ECMAScript Internationalization API](https://norbertlindenberg.com/2012/12/ecmascript-internationalization-api/index.html) -- Constructors - - [`Intl.Collator`](intl/collator) - - [`Intl.DateTimeFormat`](intl/datetimeformat) - - [`Intl.ListFormat`](intl/listformat) - - [`Intl.NumberFormat`](intl/numberformat) - - [`Intl.PluralRules`](intl/pluralrules) - - [`Intl.RelativeTimeFormat`](intl/relativetimeformat) - - [`Intl.Locale`](intl/locale) -- Methods - - [`String.prototype.localeCompare()`](string/localecompare) - - [`Number.prototype.toLocaleString()`](number/tolocalestring) - - [`Date.prototype.toLocaleString()`](date/tolocalestring) - - [`Date.prototype.toLocaleDateString()`](date/tolocaledatestring) - - [`Date.prototype.toLocaleTimeString()`](date/tolocaletimestring) - -Global_Objects/Intl" Global_Objects/Intl - ---- ---- - -# RangeError: invalid array length - -The JavaScript exception "Invalid array length" occurs when specifying an array length that is either negative or exceeds the maximum supported by the platform (i.e. when creating an [`Array`](../global_objects/array) or [`ArrayBuffer`](../global_objects/arraybuffer), or when setting the [`Array.length`](../global_objects/array/length) property). - -The maximum allowed array length depends on the platform, browser and browser version. For [`Array`](../global_objects/array) the maximum length is 2GB-1 (2^32-1). For [`ArrayBuffer`](../global_objects/arraybuffer) the maximum is 2GB-1 on 32-bit systems (2^32-1). From Firefox version 89 the maximum value of [`ArrayBuffer`](../global_objects/arraybuffer) is 8GB on 64-bit systems (2^33). - -**Note:** `Array` and `ArrayBuffer` are independent data structures (the implementation of one does not affect the other). - -## Message - - RangeError: invalid array length (Firefox) - RangeError: Invalid array length (Chromium-based) - RangeError: Array buffer allocation failed (Chromium-based) - -## Error type - -[`RangeError`](../global_objects/rangeerror) - -## What went wrong? - -An invalid array length might appear in these situations: - -- Creating an [`Array`](../global_objects/array) or [`ArrayBuffer`](../global_objects/arraybuffer) with a negative length, or setting a negative value for the [`Array.length`](../global_objects/array/length) property. -- Creating an [`Array`](../global_objects/array) or setting the [`Array.length`](../global_objects/array/length) property greater than 2GB-1 (2^32-1). -- Creating an [`ArrayBuffer`](../global_objects/arraybuffer) that is bigger than 2GB-1 (2^32-1) on a 32-bit system or 8GB (2^33) on a 64-bit system. -- Before Firefox 89: Creating an [`ArrayBuffer`](../global_objects/arraybuffer) that is bigger than 2GB-1 (2^32-1). - -If you are creating an `Array`, using the constructor, you probably want to use the literal notation instead, as the first argument is interpreted as the length of the `Array`. - -Otherwise, you might want to clamp the length before setting the length property, or using it as argument of the constructor. - -## Examples - -### Invalid cases - - new Array(Math.pow(2, 40)) - new Array(-1) - new ArrayBuffer(Math.pow(2, 32)) //32-bit system - new ArrayBuffer(-1) - - let a = []; - a.length = a.length - 1; // set -1 to the length property - - let b = new Array(Math.pow(2, 32) - 1); - b.length = b.length + 1; // set 2^32 to the length property - -### Valid cases - - [ Math.pow(2, 40) ] // [ 1099511627776 ] - [ -1 ] // [ -1 ] - new ArrayBuffer(Math.pow(2, 32) - 1) - new ArrayBuffer(Math.pow(2, 33)) // 64-bit systems after Firefox 89 - new ArrayBuffer(0) - - let a = []; - a.length = Math.max(0, a.length - 1); - - let b = new Array(Math.pow(2, 32) - 1); - b.length = Math.min(0xffffffff, b.length + 1); - - // 0xffffffff is the hexadecimal notation for 2^32 - 1 - // which can also be written as (-1 >>> 0) - -## See also - -- [`Array`](../global_objects/array) -- [`Array.length`](../global_objects/array/length) -- [`ArrayBuffer`](../global_objects/arraybuffer) - -Errors/Invalid_array_length" Errors/Invalid_array_length - ---- ---- - -# ReferenceError: invalid assignment left-hand side - -The JavaScript exception "invalid assignment left-hand side" occurs when there was an unexpected assignment somewhere. For example, a single "`=`" sign was used instead of "`==`" or "`===`". - -## Message - - ReferenceError: invalid assignment left-hand side - -## Error type - -[`ReferenceError`](../global_objects/referenceerror). - -## What went wrong? - -There was an unexpected assignment somewhere. This might be due to a mismatch of a [assignment operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#assignment_operators) and a [comparison operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators), for example. While a single "`=`" sign assigns a value to a variable, the "`==`" or "`===`" operators compare a value. - -## Examples - -### Typical invalid assignments - - if (Math.PI = 3 || Math.PI = 4) { - console.log('no way!'); - } - // ReferenceError: invalid assignment left-hand side - - var str = 'Hello, ' - += 'is it me ' - += 'you\'re looking for?'; - // ReferenceError: invalid assignment left-hand side - -In the `if` statement, you want to use a comparison operator ("=="), and for the string concatenation, the plus ("+") operator is needed. - - if (Math.PI == 3 || Math.PI == 4) { - console.log('no way!'); - } - - var str = 'Hello, ' - + 'from the ' - + 'other side!'; - -## See also - -- [Assignment operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#assignment_operators) -- [Comparison operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators) - -Errors/Invalid_assignment_left-hand_side" Errors/Invalid_assignment_left-hand_side - ---- ---- - -# TypeError: invalid assignment to const "x" - -The JavaScript exception "invalid assignment to const" occurs when it was attempted to alter a constant value. JavaScript `const` declarations can't be re-assigned or redeclared. - -## Message - - TypeError: invalid assignment to const "x" (Firefox) - TypeError: Assignment to constant variable. (Chrome) - TypeError: Assignment to const (Edge) - TypeError: Redeclaration of const 'x' (IE) - -## Error type - -[`TypeError`](../global_objects/typeerror) - -## What went wrong? - -A constant is a value that cannot be altered by the program during normal execution. It cannot change through re-assignment, and it can't be redeclared. In JavaScript, constants are declared using the `const` keyword. - -## Examples - -### Invalid redeclaration - -Assigning a value to the same constant name in the same block-scope will throw. - - const COLUMNS = 80; - - // ... - - COLUMNS = 120; // TypeError: invalid assignment to const `COLUMNS' - -### Fixing the error - -There are multiple options to fix this error. Check what was intended to be achieved with the constant in question. - -#### Rename - -If you meant to declare another constant, pick another name and re-name. This constant name is already taken in this scope. - - const COLUMNS = 80; - const WIDE_COLUMNS = 120; - -#### `const`, `let` or `var`? - -Do not use const if you weren't meaning to declare a constant. Maybe you meant to declare a block-scoped variable with `let` or global variable with `var`. - - let columns = 80; - - // ... - - let columns = 120; - -#### Scoping - -Check if you are in the correct scope. Should this constant appear in this scope or was it meant to appear in a function, for example? - - const COLUMNS = 80; - - function setupBigScreenEnvironment() { - const COLUMNS = 120; - } - -### `const` and immutability - -The `const` declaration creates a read-only reference to a value. It does **not** mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in case the content is an object, this means the object itself can still be altered. This means that you can't mutate the value stored in a variable: - - const obj = {foo: 'bar'}; - obj = {foo: 'baz'}; // TypeError: invalid assignment to const `obj' - -But you can mutate the properties in a variable: - - obj.foo = 'baz'; - obj; // Object { foo: "baz" } - -## See also - -- `const` -- `let` -- `var` - -Errors/Invalid_const_assignment" Errors/Invalid_const_assignment - ---- ---- - -# RangeError: invalid date - -The JavaScript exception "invalid date" occurs when a string leading to an invalid date has been provided to [`Date`](../global_objects/date) or [`Date.parse()`](../global_objects/date/parse). - -## Message - - RangeError: invalid date (Edge) - RangeError: invalid date (Firefox) - RangeError: invalid time value (Chrome) - RangeError: Provided date is not in valid range (Chrome) - -## Error type - -[`RangeError`](../global_objects/rangeerror) - -## What went wrong? - -A string leading to an invalid date has been provided to [`Date`](../global_objects/date) or [`Date.parse()`](../global_objects/date/parse). - -## Examples - -### Invalid cases - -Unrecognizable strings or dates containing illegal element values in ISO formatted strings usually return [`NaN`](../global_objects/nan). However, depending on the implementation, non-conforming ISO format strings, may also throw `RangeError: invalid date`, like the following cases in Firefox: - - new Date('foo-bar 2014'); - new Date('2014-25-23').toISOString(); - new Date('foo-bar 2014').toString(); - -This, however, returns [`NaN`](../global_objects/nan) in Firefox: - - Date.parse('foo-bar 2014'); // NaN - -For more details, see the [`Date.parse()`](../global_objects/date/parse) documentation. - -### Valid cases - - new Date('05 October 2011 14:48 UTC'); - new Date(1317826080); // Unix Time Stamp for 05 October 2011 14:48:00 UTC - -## See also - -- [`Date`](../global_objects/date) -- [`Date.prototype.parse()`](../global_objects/date/parse) -- [`Date.prototype.toISOString()`](../global_objects/date/toisostring) - -Errors/Invalid_date" Errors/Invalid_date - ---- ---- - -# SyntaxError: for-in loop head declarations may not have initializers - -The JavaScript [strict mode](../strict_mode)-only exception "for-in loop head declarations may not have initializers" occurs when the head of a [for...in](../statements/for...in) contains an initializer expression, such as |`for (var i = 0 in obj)`|. This is not allowed in for-of loops in strict mode. - -## Message - - SyntaxError: for-in loop head declarations cannot have an initializer (Edge) - SyntaxError: for-in loop head declarations may not have initializers (Firefox) - SyntaxError: for-in loop variable declaration may not have an initializer. (Chrome) - -## Error type - -[`SyntaxError`](../global_objects/syntaxerror) in [strict mode](../strict_mode) only. - -## What went wrong? - -The head of a [for...in](../statements/for...in) loop contains an initializer expression. That is, a variable is declared and assigned a value |`for (var i = 0 in obj)`|. In non-strict mode, this head declaration is silently ignored and behaves like `|for (var i in obj)|`. In [strict mode](../strict_mode), however, a `SyntaxError` is thrown. - -## Examples - -This example throws a `SyntaxError`: - - "use strict"; - - var obj = {a: 1, b: 2, c: 3 }; - - for (var i = 0 in obj) { - console.log(obj[i]); - } - - // SyntaxError: for-in loop head declarations may not have initializers - -### Valid for-in loop - -You can remove the initializer (`i = 0`) in the head of the for-in loop. - - "use strict"; - - var obj = {a: 1, b: 2, c: 3 }; - - for (var i in obj) { - console.log(obj[i]); - } - -### Array iteration - -The for...in loop [shouldn't be used for Array iteration](../statements/for...in#array_iteration_and_for...in). Did you intend to use a `for` loop instead of a `for-in` loop to iterate an [`Array`](../global_objects/array)? The `for` loop allows you to set an initializer then as well: - - var arr = [ "a", "b", "c" ] - - for (var i = 2; i < arr.length; i++) { - console.log(arr[i]); - } - - // "c" - -## See also - -- `for...in` -- `for...of` - also disallows an initializer in both strict and non-strict mode. -- `for` - preferred for array iteration, allows to define an initializer. - -Errors/Invalid_for-in_initializer" Errors/Invalid_for-in_initializer - ---- ---- - -# SyntaxError: a declaration in the head of a for-of loop can't have an initializer - -The JavaScript exception "a declaration in the head of a for-of loop can't have an initializer" occurs when the head of a [for...of](../statements/for...of) loop contains an initializer expression such as |`for (var i = 0 of iterable)`|. This is not allowed in for-of loops. - -## Message - - SyntaxError: for-of loop head declarations cannot have an initializer (Edge) - SyntaxError: a declaration in the head of a for-of loop can't have an initializer (Firefox) - SyntaxError: for-of loop variable declaration may not have an initializer. (Chrome) - -## Error type - -[`SyntaxError`](../global_objects/syntaxerror) - -## What went wrong? - -The head of a [for...of](../statements/for...of) loop contains an initializer expression. That is, a variable is declared and assigned a value |`for (var i = 0 of iterable)`|. This is not allowed in for-of loops. You might want a `for` loop that does allow an initializer. - -## Examples - -### Invalid `for-of` loop - - let iterable = [10, 20, 30]; - - for (let value = 50 of iterable) { - console.log(value); - } - - // SyntaxError: a declaration in the head of a for-of loop can't - // have an initializer - -### Valid `for-of` loop - -You need to remove the initializer (`value = 50`) in the head of the `for-of` loop. Maybe you intended to make 50 an offset value, in that case you could add it to the loop body, for example. - - let iterable = [10, 20, 30]; - - for (let value of iterable) { - value += 50; - console.log(value); - } - // 60 - // 70 - // 80 - -## See also - -- `for...of` -- `for...in` - disallows an initializer in strict mode as well ([SyntaxError: for-in loop head declarations may not have initializers](invalid_for-in_initializer)) -- `for` - allows to define an initializer when iterating. - -Errors/Invalid_for-of_initializer" Errors/Invalid_for-of_initializer - ---- ---- - -# TypeError: invalid 'instanceof' operand 'x' - -The JavaScript exception "invalid 'instanceof' operand" occurs when the right hand side operands of the [`instanceof` operator](../operators/instanceof) isn't used with a constructor object, i.e. an object which has a `prototype` property and is callable. - -## Message - - TypeError: invalid 'instanceof' operand "x" (Firefox) - TypeError: "x" is not a function (Firefox) - TypeError: Right-hand side of 'instanceof' is not an object (Chrome) - TypeError: Right-hand side of 'instanceof' is not callable (Chrome) - -## Error type - -[`TypeError`](../global_objects/typeerror) - -## What went wrong? - -The [`instanceof` operator](../operators/instanceof) expects the right hand side operands to be a constructor object, i.e. an object which has a `prototype` property and is callable. - -## Examples - -### instanceof vs typeof - - "test" instanceof ""; // TypeError: invalid 'instanceof' operand "" - 42 instanceof 0; // TypeError: invalid 'instanceof' operand 0 - - function Foo() {} - var f = Foo(); // Foo() is called and returns undefined - var x = new Foo(); - - x instanceof f; // TypeError: invalid 'instanceof' operand f - x instanceof x; // TypeError: x is not a function - -To fix these errors, you will either need to replace the [`instanceof` operator](../operators/instanceof) with the [`typeof` operator](../operators/typeof), or to make sure you use the function name, instead of the result of its evaluation. - - typeof "test" == "string"; // true - typeof 42 == "number" // true - - function Foo() {} - var f = Foo; // Do not call Foo. - var x = new Foo(); - - x instanceof f; // true - x instanceof Foo; // true - -## See also - -- [`instanceof` operator](../operators/instanceof) -- [`typeof` operator](../operators/typeof) - -Errors/invalid_right_hand_side_instanceof_operand" Errors/invalid_right_hand_side_instanceof_operand - ---- ---- - -# Object.is() - -The `Object.is()` method determines whether two values are [the same value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness). - -## Syntax - - Object.is(value1, value2); - -### Parameters - -`value1` -The first value to compare. - -`value2` -The second value to compare. - -### Return value - -A [`Boolean`](../boolean) indicating whether or not the two arguments are the same value. - -## Description - -`Object.is()` determines whether two values are [the same value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness). Two values are the same if one of the following holds: - -- both [`undefined`](../undefined) -- both [`null`](../null) -- both `true` or both `false` -- both strings of the same length with the same characters in the same order -- both the same object (meaning both values reference the same object in memory) -- both numbers and - - both `+0` - - both `-0` - - both [`NaN`](../nan) - - or both non-zero and both not [`NaN`](../nan) and both have the same value - -This is _not_ the same as being equal according to the [`==`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#equality) operator. The `==` operator applies various coercions to both sides (if they are not the same Type) before testing for equality (resulting in such behavior as `"" == false` being `true`), but `Object.is` doesn't coerce either value. - -This is also _not_ the same as being equal according to the [`===`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#identity) operator. The only difference between `Object.is()` and `===` is in their treatment of signed zeroes and NaNs. For example, the `===` operator (and the `==` operator) treats the number values `-0` and `+0` as equal. Also, the `===` operator treats [`Number.NaN`](../number/nan) and [`NaN`](../nan) as not equal. - -## Examples - -### Using Object.is - - // Case 1: Evaluation result is the same as using === - Object.is(25, 25); // true - Object.is('foo', 'foo'); // true - Object.is('foo', 'bar'); // false - Object.is(null, null); // true - Object.is(undefined, undefined); // true - Object.is(window, window); // true - Object.is([], []); // false - var foo = { a: 1 }; - var bar = { a: 1 }; - Object.is(foo, foo); // true - Object.is(foo, bar); // false - - // Case 2: Signed zero - Object.is(0, -0); // false - Object.is(+0, -0); // false - Object.is(-0, -0); // true - Object.is(0n, -0n); // true - - // Case 3: NaN - Object.is(NaN, 0/0); // true - Object.is(NaN, Number.NaN) // true - -## Polyfill - - if (!Object.is) { - Object.defineProperty(Object, "is", { - value: function (x, y) { - // SameValue algorithm - if (x === y) { - // return true if x and y are not 0, OR - // if x and y are both 0 of the same sign. - // This checks for cases 1 and 2 above. - return x !== 0 || 1 / x === 1 / y; - } else { - // return true if both x AND y evaluate to NaN. - // The only possibility for a variable to not be strictly equal to itself - // is when that variable evaluates to NaN (example: Number.NaN, 0/0, NaN). - // This checks for case 3. - return x !== x && y !== y; - } - } - }); - } - -## Specifications - -
    Specification
    ECMAScript (ECMA-262) -
    - -The definition of 'Object.is' in that specification.
    - -`is` - -30 - -12 - -22 - -No - -17 - -9 - -≤37 - -30 - -22 - -18 - -9 - -2.0 - -## See also - -- [Equality comparisons and sameness](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness) — a comparison of all three built-in sameness facilities - - - -Global_Objects/Object/is" Global_Objects/Object/is - ---- ---- - -# TypeError: 'x' is not iterable - -The JavaScript exception "is not iterable" occurs when the value which is given as the right hand-side of [for…of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement) or as argument of a function such as [`Promise.all`](../global_objects/promise/all) or [`TypedArray.from`](../global_objects/typedarray/from), is not an [iterable object](../iteration_protocols). - -## Message - - TypeError: 'x' is not iterable (Firefox, Chrome) - TypeError: 'x' is not a function or its return value is not iterable (Chrome) - -## Error type - -[`TypeError`](../global_objects/typeerror) - -## What went wrong? - -The value which is given as the right hand-side of [for…of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement) or as argument of a function such as [`Promise.all`](../global_objects/promise/all) or [`TypedArray.from`](../global_objects/typedarray/from), is not an [iterable object](../iteration_protocols). An iterable can be a built-in iterable type such as [`Array`](../global_objects/array), [`String`](../global_objects/string) or [`Map`](../global_objects/map), a generator result, or an object implementing the [iterable protocol](../iteration_protocols#the_iterable_protocol). - -## Examples - -### Iterating over Object properties - -In JavaScript, [`Object`](../global_objects/object)s are not iterable unless they implement the [iterable protocol](../iteration_protocols#the_iterable_protocol). Therefore, you cannot use [for…of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement) to iterate over the properties of an object. - - var obj = { 'France': 'Paris', 'England': 'London' }; - for (let p of obj) { // TypeError: obj is not iterable - // … - } - -Instead you have to use [`Object.keys`](../global_objects/object/keys) or [`Object.entries`](../global_objects/object/entries), to iterate over the properties or entries of an object. - - var obj = { 'France': 'Paris', 'England': 'London' }; - // Iterate over the property names: - for (let country of Object.keys(obj)) { - var capital = obj[country]; - console.log(country, capital); - } - - for (const [country, capital] of Object.entries(obj)) - console.log(country, capital); - -Another option for this use case might be to use a [`Map`](../global_objects/map): - - var map = new Map; - map.set('France', 'Paris'); - map.set('England', 'London'); - // Iterate over the property names: - for (let country of map.keys()) { - let capital = map[country]; - console.log(country, capital); - } - - for (let capital of map.values()) - console.log(capital); - - for (const [country, capital] of map.entries()) - console.log(country, capital); - -### Iterating over a generator - -[Generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#generators) are functions you call to produce an iterable object. - - function* generate(a, b) { - yield a; - yield b; - } - - for (let x of generate) // TypeError: generate is not iterable - console.log(x); - -When they are not called, the [`Function`](../global_objects/function) object corresponding to the generator is callable, but not iterable. Calling a generator produces an iterable object which will iterate over the values yielded during the execution of the generator. - - function* generate(a, b) { - yield a; - yield b; - } - - for (let x of generate(1,2)) - console.log(x); - -### Iterating over a custom iterable - -Custom iterables can be created by implementing the [`Symbol.iterator`](../global_objects/symbol/iterator) method. You must be certain that your iterator method returns an object which is an iterator, which is to say it must have a next method. - - const myEmptyIterable = { - [Symbol.iterator]() { - return [] // [] is iterable, but it is not an iterator -- it has no next method. - } - } - - Array.from(myEmptyIterable); // TypeError: myEmptyIterable is not iterable - -Here is a correct implementation: - - const myEmptyIterable = { - [Symbol.iterator]() { - return [][Symbol.iterator]() - } - } - - Array.from(myEmptyIterable); // [] - -## See also - -- [iterable protocol](../iteration_protocols#the_iterable_protocol) -- [`Object.keys`](../global_objects/object/keys) -- [`Object.entries`](../global_objects/object/entries) -- [`Map`](../global_objects/map) -- [generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#generators) -- [for…of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement) - -Errors/is_not_iterable" Errors/is_not_iterable - ---- ---- - -# Array.isArray() - -The `Array.isArray()` method determines whether the passed value is an [`Array`](../array). - - Array.isArray([1, 2, 3]); // true - Array.isArray({foo: 123}); // false - Array.isArray('foobar'); // false - Array.isArray(undefined); // false - -## Syntax - - Array.isArray(value) - -### Parameters - -`value` -The value to be checked. - -### Return value - -`true` if the value is an [`Array`](../array); otherwise, `false`. - -## Description - -If the value is an [`Array`](../array), `true` is returned; otherwise, `false` is. - -See the article ["Determining with absolute accuracy whether or not a JavaScript object is an array"](https://web.mit.edu/jwalden/www/isArray.html) for more details. Given a [`TypedArray`](../typedarray) instance, `false` is always returned. - -## Examples - -### Using Array.isArray - - // all following calls return true - Array.isArray([]); - Array.isArray([1]); - Array.isArray(new Array()); - Array.isArray(new Array('a', 'b', 'c', 'd')); - Array.isArray(new Array(3)); - // Little known fact: Array.prototype itself is an array: - Array.isArray(Array.prototype); - - // all following calls return false - Array.isArray(); - Array.isArray({}); - Array.isArray(null); - Array.isArray(undefined); - Array.isArray(17); - Array.isArray('Array'); - Array.isArray(true); - Array.isArray(false); - Array.isArray(new Uint8Array(32)); - Array.isArray({ __proto__: Array.prototype }); - -### `instanceof` vs `isArray` - -When checking for `Array` instance, `Array.isArray` is preferred over `instanceof` because it works through `iframes`. - - var iframe = document.createElement('iframe'); - document.body.appendChild(iframe); - xArray = window.frames[window.frames.length-1].Array; - var arr = new xArray(1,2,3); // [1,2,3] - - // Correctly checking for Array - Array.isArray(arr); // true - // Considered harmful, because doesn't work through iframes - arr instanceof Array; // false - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-array.isarray
    - -`isArray` - -5 - -12 - -4 - -9 - -10.5 - -5 - -1 - -18 - -4 - -14 - -5 - - - -- [A polyfill](https://github.com/behnammodi/polyfill/blob/master/array.polyfill.js) -- [`Array`](../array) - -Global_Objects/Array/isArray" Global_Objects/Array/isArray - ---- ---- - -# Symbol.isConcatSpreadable - -The `Symbol.isConcatSpreadable` well-known symbol is used to configure if an object should be flattened to its array elements when using the [`Array.prototype.concat()`](../array/concat) method. - -## Description - -The `@@isConcatSpreadable` symbol (`Symbol.isConcatSpreadable`) can be defined as an own or inherited property and its value is a boolean. It can control behavior for arrays and array-like objects: - -- For array objects, the default behavior is to spread (flatten) elements. `Symbol.isConcatSpreadable` can avoid flattening in these cases. -- For array-like objects, the default behavior is no spreading or flattening. `Symbol.isConcatSpreadable` can force flattening in these cases. - -Property attributes of `Symbol.isConcatSpreadable` - -Writable - -no - -Enumerable - -no - -Configurable - -no - -## Examples - -### Arrays - -By default, [`Array.prototype.concat()`](../array/concat) spreads (flattens) arrays into its result: - - let alpha = ['a', 'b', 'c'], - let numeric = [1, 2, 3] - - let alphaNumeric = alpha.concat(numeric) - - console.log(alphaNumeric) // Result: ['a', 'b', 'c', 1, 2, 3] - -When setting `Symbol.isConcatSpreadable` to `false`, you can disable the default behavior: - - let alpha = ['a', 'b', 'c'], - let numeric = [1, 2, 3] - - numeric[Symbol.isConcatSpreadable] = false - let alphaNumeric = alpha.concat(numeric) - - console.log(alphaNumeric) // Result: ['a', 'b', 'c', [1, 2, 3] ] - -### Array-like objects - -For array-like objects, the default is to not spread. `Symbol.isConcatSpreadable` needs to be set to `true` in order to get a flattened array: - - let x = [1, 2, 3] - - let fakeArray = { - [Symbol.isConcatSpreadable]: true, - length: 2, - 0: 'hello', - 1: 'world' - } - - x.concat(fakeArray) // [1, 2, 3, "hello", "world"] - -**Note:** The `length` property is used to control the number of object properties to be added. In the above example, `length:2` indicates two properties has to be added. - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-symbol.isconcatspreadable
    - -`isConcatSpreadable` - -48 - -15 - -48 - -No - -35 - -10 - -48 - -48 - -48 - -35 - -10 - -5.0 - -## See also - -- [`Array.prototype.concat()`](../array/concat) - - - -Global_Objects/Symbol/isConcatSpreadable" Global_Objects/Symbol/isConcatSpreadable - ---- ---- - -# Reflect.isExtensible() - -The static `Reflect.isExtensible()` method determines if an object is extensible (whether it can have new properties added to it). It is similar to [`Object.isExtensible()`](../object/isextensible), but with some [differences](#difference_to_object.isextensible). - -## Syntax - - Reflect.isExtensible(target) - -### Parameters - -`target` -The target object which to check if it is extensible. - -### Return value - -A [`Boolean`](../boolean) indicating whether or not the target is extensible. - -### Exceptions - -A [`TypeError`](../typeerror), if `target` is not an [`Object`](../object). - -## Description - -The `Reflect.isExtensible` method allows you determine if an object is extensible (whether it can have new properties added to it). It is the same method as [`Object.isExtensible()`](../object/isextensible). - -## Examples - -### Using Reflect.isExtensible() - -See also [`Object.isExtensible()`](../object/isextensible). - - // New objects are extensible. - let empty = {} - Reflect.isExtensible(empty) // === true - - // ...but that can be changed. - Reflect.preventExtensions(empty) - Reflect.isExtensible(empty) // === false - - // Sealed objects are by definition non-extensible. - let sealed = Object.seal({}) - Reflect.isExtensible(sealed) // === false - - // Frozen objects are also by definition non-extensible. - let frozen = Object.freeze({}) - Reflect.isExtensible(frozen) // === false - -### Difference to Object.isExtensible() - -If the `target` argument to this method is not an object (a primitive), then it will cause a [`TypeError`](../typeerror). With [`Object.isExtensible()`](../object/isextensible), a non-object first argument will be coerced to an object at first. - - Reflect.isExtensible(1) - // TypeError: 1 is not an object - - Object.isExtensible(1) - // false - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-reflect.isextensible
    - -`isExtensible` - -49 - -12 - -42 - -No - -36 - -10 - -49 - -49 - -42 - -36 - -10 - -5.0 - -## See also - -- [`Reflect`](../reflect) -- [`Object.isExtensible()`](../object/isextensible) - - - -Global_Objects/Reflect/isExtensible" Global_Objects/Reflect/isExtensible - ---- ---- - -# Number.isFinite() - -The `Number.isFinite()` method determines whether the passed value is a finite number — that is, it checks that the type of a given value is [`Number`](../number), and the number is neither positive [`Infinity`](../infinity), negative `Infinity`, nor [`NaN`](../nan). - -## Syntax - - Number.isFinite(value) - -### Parameters - -`value` -The value to be tested for finiteness. - -### Return value - -A [`Boolean`](../boolean) indicating whether or not the given value is a finite number. - -## Description - -In comparison to the global [`isFinite()`](../isfinite) function, this method doesn't first convert the parameter to a number. This means only values of the type number _and_ are finite return `true`. - -## Examples - -### Using isFinite - - Number.isFinite(Infinity); // false - Number.isFinite(NaN); // false - Number.isFinite(-Infinity); // false - - Number.isFinite(0); // true - Number.isFinite(2e64); // true - - Number.isFinite('0'); // false, would've been true with - // global isFinite('0') - Number.isFinite(null); // false, would've been true with - // global isFinite(null) - -## Polyfill - - if (Number.isFinite === undefined) Number.isFinite = function(value) { - return typeof value === 'number' && isFinite(value); - } - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-number.isfinite
    - -`isFinite` - -19 - -12 - -16 - -No - -15 - -9 - -≤37 - -25 - -16 - -14 - -9 - -1.5 - -## See also - -- The [`Number`](../number) object it belongs to. -- The global function [`isFinite`](../isfinite). - - - -Global_Objects/Number/isFinite" Global_Objects/Number/isFinite - ---- ---- - -# Object.isFrozen() - -The `Object.isFrozen()` determines if an object is [frozen](freeze). - -## Syntax - - Object.isFrozen(obj) - -### Parameters - -`obj` -The object which should be checked. - -### Return value - -A [`Boolean`](../boolean) indicating whether or not the given object is frozen. - -## Description - -An object is frozen if and only if it is not [extensible](isextensible), all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable. - -## Examples - -### Using Object.isFrozen - - // A new object is extensible, so it is not frozen. - Object.isFrozen({}); // === false - - // An empty object which is not extensible - // is vacuously frozen. - var vacuouslyFrozen = Object.preventExtensions({}); - Object.isFrozen(vacuouslyFrozen); // === true - - // A new object with one property is also extensible, - // ergo not frozen. - var oneProp = { p: 42 }; - Object.isFrozen(oneProp); // === false - - // Preventing extensions to the object still doesn't - // make it frozen, because the property is still - // configurable (and writable). - Object.preventExtensions(oneProp); - Object.isFrozen(oneProp); // === false - - // ...but then deleting that property makes the object - // vacuously frozen. - delete oneProp.p; - Object.isFrozen(oneProp); // === true - - // A non-extensible object with a non-writable - // but still configurable property is not frozen. - var nonWritable = { e: 'plep' }; - Object.preventExtensions(nonWritable); - Object.defineProperty(nonWritable, 'e', { - writable: false - }); // make non-writable - Object.isFrozen(nonWritable); // === false - - // Changing that property to non-configurable - // then makes the object frozen. - Object.defineProperty(nonWritable, 'e', { - configurable: false - }); // make non-configurable - Object.isFrozen(nonWritable); // === true - - // A non-extensible object with a non-configurable - // but still writable property also isn't frozen. - var nonConfigurable = { release: 'the kraken!' }; - Object.preventExtensions(nonConfigurable); - Object.defineProperty(nonConfigurable, 'release', { - configurable: false - }); - Object.isFrozen(nonConfigurable); // === false - - // Changing that property to non-writable - // then makes the object frozen. - Object.defineProperty(nonConfigurable, 'release', { - writable: false - }); - Object.isFrozen(nonConfigurable); // === true - - // A non-extensible object with a configurable - // accessor property isn't frozen. - var accessor = { get food() { return 'yum'; } }; - Object.preventExtensions(accessor); - Object.isFrozen(accessor); // === false - - // ...but make that property non-configurable - // and it becomes frozen. - Object.defineProperty(accessor, 'food', { - configurable: false - }); - Object.isFrozen(accessor); // === true - - // But the easiest way for an object to be frozen - // is if Object.freeze has been called on it. - var frozen = { 1: 81 }; - Object.isFrozen(frozen); // === false - Object.freeze(frozen); - Object.isFrozen(frozen); // === true - - // By definition, a frozen object is non-extensible. - Object.isExtensible(frozen); // === false - - // Also by definition, a frozen object is sealed. - Object.isSealed(frozen); // === true - -### Non-object coercion - -In ES5, if the argument to this method is not an object (a primitive), then it will cause a [`TypeError`](../typeerror). In ES2015, a non-object argument will be treated as if it was a frozen ordinary object, return `true`. - - Object.isFrozen(1); - // TypeError: 1 is not an object (ES5 code) - - Object.isFrozen(1); - // true (ES2015 code) - -## Specifications - -
    Specification
    ECMAScript (ECMA-262) -
    - -The definition of 'Object.isFrozen' in that specification.
    - -`isFrozen` - -6 - -12 - -4 - -9 - -12 - -5.1 - -1 - -18 - -4 - -12 - -6 - - - -- [`Object.freeze()`](freeze) -- [`Object.preventExtensions()`](preventextensions) -- [`Object.isExtensible()`](isextensible) -- [`Object.seal()`](seal) -- [`Object.isSealed()`](issealed) - - - -Global_Objects/Object/isFrozen" Global_Objects/Object/isFrozen - ---- ---- - -# Number.isInteger() - -The `Number.isInteger()` method determines whether the passed value is an integer. - -## Syntax - - Number.isInteger(value) - -### Parameters - -`value` -The value to be tested for being an integer. - -### Return value - -A [`Boolean`](../boolean) indicating whether or not the given value is an integer. - -## Description - -If the target value is an integer, return `true`, otherwise return `false`. If the value is [`NaN`](../nan) or [`Infinity`](../infinity), return `false`. The method will also return `true` for floating point numbers that can be represented as integer. - -## Examples - -### Using isInteger - - Number.isInteger(0); // true - Number.isInteger(1); // true - Number.isInteger(-100000); // true - Number.isInteger(99999999999999999999999); // true - - Number.isInteger(0.1); // false - Number.isInteger(Math.PI); // false - - Number.isInteger(NaN); // false - Number.isInteger(Infinity); // false - Number.isInteger(-Infinity); // false - Number.isInteger('10'); // false - Number.isInteger(true); // false - Number.isInteger(false); // false - Number.isInteger([1]); // false - - Number.isInteger(5.0); // true - Number.isInteger(5.000000000000001); // false - Number.isInteger(5.0000000000000001); // true - -## Polyfill - - Number.isInteger = Number.isInteger || function(value) { - return typeof value === 'number' && - isFinite(value) && - Math.floor(value) === value; - }; - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-number.isinteger
    - -`isInteger` - -34 - -12 - -16 - -No - -21 - -9 - -≤37 - -34 - -16 - -21 - -9 - -2.0 - -## See also - -- The [`Number`](../number) object it belongs to. - - - -Global_Objects/Number/isInteger" Global_Objects/Number/isInteger - ---- ---- - -# Atomics.isLockFree() - -The static ` Atomics``.isLockFree() ` method is used to determine whether to use locks or atomic operations. It returns `true`, if the given size is one of the [BYTES_PER_ELEMENT](../typedarray/bytes_per_element) property of integer TypedArray types. - -## Syntax - - Atomics.isLockFree(size) - -### Parameters - -`size` -The size in bytes to check. - -### Return value - -A [`Boolean`](../boolean) indicating whether the operation is lock free. - -## Examples - -### Using isLockFree - - Atomics.isLockFree(1); // true - Atomics.isLockFree(2); // true - Atomics.isLockFree(3); // false - Atomics.isLockFree(4); // true - Atomics.isLockFree(5); // false - Atomics.isLockFree(6); // false - Atomics.isLockFree(7); // false - Atomics.isLockFree(8); // true - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-atomics.islockfree
    - -`isLockFree` - -68 - -60-63 - -Chrome disabled `SharedArrayBuffer` on January 5, 2018 to help reduce the efficacy of [speculative side-channel attacks](https://www.chromium.org/Home/chromium-security/ssca). This was a temporary removal while mitigations were put in place. - -79 - -16-17 - -Support was removed to mitigate [speculative execution side-channel attacks (Windows blog)](https://blogs.windows.com/msedgedev/2018/01/03/speculative-execution-mitigations-microsoft-edge-internet-explorer). - -78 - -57 - -Support was disabled by default to mitigate [speculative execution side-channel attacks (Mozilla Security Blog)](https://blog.mozilla.org/security/2018/01/03/mitigations-landing-new-class-timing-attack/). - -55-57 - -46-55 - -No - -No - -10.1-11.1 - -60-63 - -Chrome disabled `SharedArrayBuffer` on January 5, 2018 to help reduce the efficacy of [speculative side-channel attacks](https://www.chromium.org/Home/chromium-security/ssca). This is intended as a temporary measure until other mitigations are in place. - -60-63 - -Chrome disabled `SharedArrayBuffer` on January 5, 2018 to help reduce the efficacy of [speculative side-channel attacks](https://www.chromium.org/Home/chromium-security/ssca). This is intended as a temporary measure until other mitigations are in place. - -57 - -Support was disabled by default to mitigate [speculative execution side-channel attacks (Mozilla Security Blog)](https://blog.mozilla.org/security/2018/01/03/mitigations-landing-new-class-timing-attack/). - -55-57 - -46-55 - -No - -10.3-11.3 - -No - -Chrome disabled `SharedArrayBuffer` on January 5, 2018 to help reduce the efficacy of [speculative side-channel attacks](https://www.chromium.org/Home/chromium-security/ssca). This is intended as a temporary measure until other mitigations are in place. - -## See also - -- [`Atomics`](../atomics) - -Global_Objects/Atomics/isLockFree" Global_Objects/Atomics/isLockFree - ---- ---- - -# isNaN() - -The `isNaN()` function determines whether a value is [`NaN`](nan) or not. Because coercion inside the `isNaN` function can be [surprising](#confusing_special-case_behavior), you may alternatively want to use [`Number.isNaN()`](number/isnan). - -## Syntax - - isNaN(value) - -### Parameters - -`value` -The value to be tested. - -### Return value - -`true` if the given value is [`NaN`](nan); otherwise, `false`. - -## Description - -### The necessity of an isNaN function - -Unlike all other possible values in JavaScript, it is not possible to use the equality operators (== and ===) to compare a value against [`NaN`](nan) to determine whether the value _is_ `NaN` or not, because both `NaN == NaN` and `NaN === NaN` evaluate to `false`. Hence, the necessity of an `isNaN` function. - -### Origin of NaN values - -`NaN` values are generated when arithmetic operations result in _undefined_ or _unrepresentable_ values. Such values do not necessarily represent overflow conditions. A `NaN` also results from attempted coercion to numeric values of non-numeric values for which no primitive numeric value is available. - -For example, dividing zero by zero results in a `NaN` — but dividing other numbers by zero does not. - -### Confusing special-case behavior - -Since the very earliest versions of the `isNaN` function specification, its behavior for non-numeric arguments has been confusing. When the argument to the `isNaN` function is not of type [Number](https://es5.github.com/#x8.5), the value is first coerced to a Number. The resulting value is then tested to determine whether it is [`NaN`](nan). Thus for non-numbers that when coerced to numeric type result in a valid non-NaN numeric value (notably the empty string and boolean primitives, which when coerced give numeric values zero or one), the "false" returned value may be unexpected; the empty string, for example, is surely "not a number." The confusion stems from the fact that the term, "not a number", has a specific meaning for numbers represented as IEEE-754 floating-point values. The function should be interpreted as answering the question, "is this value, when coerced to a numeric value, an IEEE-754 'Not A Number' value?" - -ECMAScript 2015 contains the [`Number.isNaN()`](number/isnan) function. `Number.isNaN(x)` is a reliable way to test whether `x` is `NaN` or not. Even with `Number.isNaN`, however, the meaning of `NaN` remains the precise numeric meaning and not, "not a number". Alternatively, in the absence of `Number.isNaN`, the expression `(x != x)` is a more reliable way to test whether variable `x` is `NaN` or not, as the result is not subject to the false positives that make `isNaN` unreliable. - -A polyfill for `isNaN` would be (the polyfill leverages the unique never-equal-to-itself characteristic of `NaN`): - - const isNaN = function(value) { - const n = Number(value); - return n !== n; - }; - -## Examples - - isNaN(NaN); // true - isNaN(undefined); // true - isNaN({}); // true - - isNaN(true); // false - isNaN(null); // false - isNaN(37); // false - - // strings - isNaN('37'); // false: "37" is converted to the number 37 which is not NaN - isNaN('37.37'); // false: "37.37" is converted to the number 37.37 which is not NaN - isNaN("37,5"); // true - isNaN('123ABC'); // true: parseInt("123ABC") is 123 but Number("123ABC") is NaN - isNaN(''); // false: the empty string is converted to 0 which is not NaN - isNaN(' '); // false: a string with spaces is converted to 0 which is not NaN - - // dates - isNaN(new Date()); // false - isNaN(new Date().toString()); // true - - // This is a false positive and the reason why isNaN is not entirely reliable - isNaN('blabla'); // true: "blabla" is converted to a number. - // Parsing this as a number fails and returns NaN - -### Useful special-case behavior - -There is a more usage oriented way to think of `isNaN()`: If `isNaN(x)` returns `false`, you can use `x` in an arithmetic expression not making the expression return `NaN`. If it returns `true`, `x` will make every arithmetic expression return `NaN`. This means that in JavaScript, `isNaN(x) == true` is equivalent to `x - 0` returning `NaN` (though in JavaScript `x - 0 == NaN` always returns false, so you can't test for it). Actually, `isNaN(x)`, `isNaN(x - 0)`, `isNaN(Number(x))`, `Number.isNaN(x - 0)`, and `Number.isNaN(Number(x))` always return the same and in JavaScript `isNaN(x)` is just the shortest possible form to express each of these terms. - -You can use this, for example, to test whether an argument to a function is arithmetically processable (usable "like" a number), or if it's not and you have to provide a default value or something else. This way you can have a function that makes use of the full versatility JavaScript provides by implicitly converting values depending on context. - -## Specifications - -
    Specification
    ECMAScript (ECMA-262) -
    - -The definition of 'isNaN' in that specification.
    - -`isNaN` - -1 - -12 - -1 - -3 - -3 - -1 - -1 - -18 - -4 - -10.1 - -1 - - - -- [`NaN`](nan) -- [`Number.isNaN()`](number/isnan) - -Global_Objects/isNaN" Global_Objects/isNaN - ---- ---- - -# Object.prototype.isPrototypeOf() - -The `isPrototypeOf()` method checks if an object exists in another object's prototype chain. - -**Note:** `isPrototypeOf()` differs from the [`instanceof`](../../operators/instanceof) operator. In the expression "`object instanceof AFunction`", the `object` prototype chain is checked against `AFunction.prototype`, not against `AFunction` itself. - -## Syntax - - isPrototypeOf(object) - -### Parameters - -`object` -The object whose prototype chain will be searched. - -### Return value - -A [`Boolean`](../boolean) indicating whether the calling object lies in the prototype chain of the specified object. - -### Errors thrown - -[`TypeError`](../typeerror) -A [`TypeError`](../typeerror) is thrown if `prototypeObj` is undefined or null. - -## Description - -The `isPrototypeOf()` method allows you to check whether or not an object exists within another object's prototype chain. - -## Examples - -### Using isPrototypeOf - -This example demonstrates that `Baz.prototype`, `Bar.prototype`, `Foo.prototype` and `Object.prototype` exist in the prototype chain for object `baz`: - - function Foo() {} - function Bar() {} - function Baz() {} - - Bar.prototype = Object.create(Foo.prototype); - Baz.prototype = Object.create(Bar.prototype); - - const foo = new Foo(); - const bar = new Bar(); - const baz = new Baz(); - - // prototype chains: - // foo: Foo <- Object - // bar: Bar <- Foo <- Object - // baz: Baz <- Bar <- Foo <- Object - console.log(Baz.prototype.isPrototypeOf(baz)); // true - console.log(Baz.prototype.isPrototypeOf(bar)); // false - console.log(Baz.prototype.isPrototypeOf(foo)); // false - console.log(Bar.prototype.isPrototypeOf(baz)); // true - console.log(Bar.prototype.isPrototypeOf(foo)); // false - console.log(Foo.prototype.isPrototypeOf(baz)); // true - console.log(Foo.prototype.isPrototypeOf(bar)); // true - console.log(Object.prototype.isPrototypeOf(baz)); // true - -The `isPrototypeOf()` method — along with the [`instanceof`](../../operators/instanceof) operator — comes in particularly handy if you have code that can only function when dealing with objects descended from a specific prototype chain; e.g., to guarantee that certain methods or properties will be present on that object. - -For example, to execute some code that's only safe to run if a `baz` object has `Foo.prototype` in its prototype chain, you can do this: - - if (Foo.prototype.isPrototypeOf(baz)) { - // do something safe - } - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-object.prototype.isprototypeof
    - -`isPrototypeOf` - -1 - -12 - -1 - -9 - -4 - -3 - -1 - -18 - -4 - -10.1 - -1 - - - -- [`instanceof`](../../operators/instanceof) -- [`Object.getPrototypeOf()`](getprototypeof) -- [`Object.setPrototypeOf()`](setprototypeof) -- [`Object/proto`](proto) - - - -Global_Objects/Object/isPrototypeOf" Global_Objects/Object/isPrototypeOf - ---- ---- - -# Number.isSafeInteger() - -The `Number.isSafeInteger()` method determines whether the provided value is a number that is a safe integer. - -A safe integer is an integer that - -- can be exactly represented as an IEEE-754 double precision number, and -- whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation. - -For example, `253 - 1` is a safe integer: it can be exactly represented, and no other integer rounds to it under any IEEE-754 rounding mode. In contrast, `253` is _not_ a safe integer: it can be exactly represented in IEEE-754, but the integer `253 + 1` can't be directly represented in IEEE-754 but instead rounds to `253` under round-to-nearest and round-to-zero rounding. The safe integers consist of all integers from `-(253 - 1)` inclusive to `253 - 1` inclusive (± `9007199254740991` or ± 9,007,199,254,740,991). - -Handling values larger or smaller than ~9 quadrillion with full precision requires using an [arbitrary precision arithmetic library](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic). See [What Every Programmer Needs to Know about Floating Point Arithmetic](https://floating-point-gui.de/) for more information on floating point representations of numbers. - -For larger integers, consider using the [`BigInt`](../bigint) type. - -## Syntax - - Number.isSafeInteger(testValue) - -### Parameters - -`testValue` -The value to be tested for being a safe integer. - -### Return value - -A [`Boolean`](../boolean) indicating whether or not the given value is a number that is a safe integer. - -## Polyfill - - Number.isSafeInteger = Number.isSafeInteger || function (value) { - return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER; - }; - -## Examples - -### Using isSafeInteger - - Number.isSafeInteger(3); // true - Number.isSafeInteger(Math.pow(2, 53)); // false - Number.isSafeInteger(Math.pow(2, 53) - 1); // true - Number.isSafeInteger(NaN); // false - Number.isSafeInteger(Infinity); // false - Number.isSafeInteger('3'); // false - Number.isSafeInteger(3.1); // false - Number.isSafeInteger(3.0); // true - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-number.issafeinteger
    - -`isSafeInteger` - -34 - -12 - -32 - -No - -21 - -10 - -≤37 - -34 - -32 - -21 - -10 - -2.0 - -## See also - -- The [`Number`](../number) object it belongs to. -- [`Number.MIN_SAFE_INTEGER`](min_safe_integer) -- [`Number.MAX_SAFE_INTEGER`](max_safe_integer) -- [`BigInt`](../bigint) - - - -Global_Objects/Number/isSafeInteger" Global_Objects/Number/isSafeInteger - ---- ---- - -# Object.isSealed() - -The `Object.isSealed()` method determines if an object is sealed. - -## Syntax - - Object.isSealed(obj) - -### Parameters - -`obj` -The object which should be checked. - -### Return value - -A [`Boolean`](../boolean) indicating whether or not the given object is sealed. - -## Description - -Returns `true` if the object is sealed, otherwise `false`. An object is sealed if it is not [extensible](isextensible) and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). - -## Examples - -### Using Object.isSealed - - // Objects aren't sealed by default. - var empty = {}; - Object.isSealed(empty); // === false - - // If you make an empty object non-extensible, - // it is vacuously sealed. - Object.preventExtensions(empty); - Object.isSealed(empty); // === true - - // The same is not true of a non-empty object, - // unless its properties are all non-configurable. - var hasProp = { fee: 'fie foe fum' }; - Object.preventExtensions(hasProp); - Object.isSealed(hasProp); // === false - - // But make them all non-configurable - // and the object becomes sealed. - Object.defineProperty(hasProp, 'fee', { - configurable: false - }); - Object.isSealed(hasProp); // === true - - // The easiest way to seal an object, of course, - // is Object.seal. - var sealed = {}; - Object.seal(sealed); - Object.isSealed(sealed); // === true - - // A sealed object is, by definition, non-extensible. - Object.isExtensible(sealed); // === false - - // A sealed object might be frozen, - // but it doesn't have to be. - Object.isFrozen(sealed); // === true - // (all properties also non-writable) - - var s2 = Object.seal({ p: 3 }); - Object.isFrozen(s2); // === false - // ('p' is still writable) - - var s3 = Object.seal({ get p() { return 0; } }); - Object.isFrozen(s3); // === true - // (only configurability matters for accessor properties) - -### Non-object coercion - -In ES5, if the argument to this method is not an object (a primitive), then it will cause a [`TypeError`](../typeerror). In ES2015, a non-object argument will be treated as if it was a sealed ordinary object, return `true`. - - Object.isSealed(1); - // TypeError: 1 is not an object (ES5 code) - - Object.isSealed(1); - // true (ES2015 code) - -## Specifications - -
    Specification
    ECMAScript (ECMA-262) -
    - -The definition of 'Object.isSealed' in that specification.
    - -`isSealed` - -6 - -12 - -4 - -9 - -12 - -5.1 - -1 - -18 - -4 - -12 - -6 - - - -- [`Object.seal()`](seal) -- [`Object.preventExtensions()`](preventextensions) -- [`Object.isExtensible()`](isextensible) -- [`Object.freeze()`](freeze) -- [`Object.isFrozen()`](isfrozen) - - - -Global_Objects/Object/isSealed" Global_Objects/Object/isSealed - ---- ---- - -# ArrayBuffer.isView() - -The `ArrayBuffer.isView()` method determines whether the passed value is one of the `ArrayBuffer` views, such as [typed array objects](../typedarray) or a [`DataView`](../dataview). - -## Syntax - - ArrayBuffer.isView(value) - -### Parameters - -`value` -The value to be checked. - -### Return value - -`true` if the given argument is one of the [`ArrayBuffer`](../arraybuffer) views; otherwise, `false`. - -## Examples - -### Using isView - - ArrayBuffer.isView(); // false - ArrayBuffer.isView([]); // false - ArrayBuffer.isView({}); // false - ArrayBuffer.isView(null); // false - ArrayBuffer.isView(undefined); // false - ArrayBuffer.isView(new ArrayBuffer(10)); // false - - ArrayBuffer.isView(new Uint8Array()); // true - ArrayBuffer.isView(new Float32Array()); // true - ArrayBuffer.isView(new Int8Array(10).subarray(0, 3)); // true - - const buffer = new ArrayBuffer(2); - const dv = new DataView(buffer); - ArrayBuffer.isView(dv); // true - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-arraybuffer.isview
    - -`isView` - -32 - -12 - -29 - -11 - -19 - -7 - -≤37 - -32 - -29 - -19 - -7 - -2.0 - -## See also - -- [JavaScript typed arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays) - -Global_Objects/ArrayBuffer/isView" Global_Objects/ArrayBuffer/isView - ---- ---- - -# String.prototype.italics() - -**Deprecated** - -This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time. - -The `italics()` method creates an [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/i) HTML element that causes a string to be italic. - -## Syntax - - italics() - -### Return value - -A string containing a [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/i) HTML element. - -## Description - -The `italics()` method embeds a string in an `` element: "`str`". - -## Examples - -### Using italics() - -The following example uses string methods to change the formatting of a string: - - var worldString = 'Hello, world'; - console.log(worldString.blink()); // Hello, world - console.log(worldString.bold()); // Hello, world - console.log(worldString.italics()); // Hello, world - console.log(worldString.strike()); // Hello, world - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-string.prototype.italics
    - -`italics` - -1 - -12 - -1 - -3 - -3 - -1 - -1 - -18 - -4 - -10.1 - -1 - - - -- [`String.prototype.blink()`](blink) -- [`String.prototype.bold()`](bold) -- [`String.prototype.strike()`](strike) - - - -Global_Objects/String/italics" Global_Objects/String/italics - ---- ---- - -# Iteration protocols - -As a couple of additions to ECMAScript 2015, **Iteration protocols** aren't new built-ins or syntax, but _protocols_. These protocols can be implemented by any object by following some conventions. - -There are two protocols: The [iterable protocol](#the_iterable_protocol) and the [iterator protocol](#the_iterator_protocol). - -## The iterable protocol - -**The iterable protocol** allows JavaScript objects to define or customize their iteration behavior, such as what values are looped over in a [`for...of`](statements/for...of) construct. Some built-in types are [built-in iterables](#built-in_iterables) with a default iteration behavior, such as [`Array`](global_objects/array) or [`Map`](global_objects/map), while other types (such as [`Object`](global_objects/object)) are not. - -In order to be **iterable**, an object must implement the `@@iterator` method, meaning that the object (or one of the objects up its [prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)) must have a property with a `@@iterator` key which is available via constant [`Symbol.iterator`](global_objects/symbol/iterator): - -
    PropertyValue
    [Symbol.iterator]A zero-argument function that returns an object, conforming to the iterator protocol.
    - -Whenever an object needs to be iterated (such as at the beginning of a [`for...of`](statements/for...of) loop), its `@@iterator` method is called with no arguments, and the returned **iterator** is used to obtain the values to be iterated. - -Note that when this zero-argument function is called, it is invoked as a method on the iterable object. Therefore inside of the function, the `this` keyword can be used to access the properties of the iterable object, to decide what to provide during the iteration. - -This function can be an ordinary function, or it can be a generator function, so that when invoked, an iterator object is returned. Inside of this generator function, each entry can be provided by using `yield`. - -## The iterator protocol - -**The iterator protocol** defines a standard way to produce a sequence of values (either finite or infinite), and potentially a return value when all values have been generated. - -An object is an iterator when it implements a `next()` method with the following semantics: - -
    PropertyValue
    next()

    A zero-argument function that returns an object with at least the following two properties:

    done (boolean)

    Has the value false if the iterator was able to produce the next value in the sequence. (This is equivalent to not specifying the done property altogether.)

    Has the value true if the iterator has completed its sequence. In this case, value optionally specifies the return value of the iterator.

    value
    Any JavaScript value returned by the iterator. Can be omitted when done is true.

    The next() method must always return an object with appropriate properties including done and value. If a non-object value gets returned (such as false or undefined), a TypeError ("iterator.next() returned a non-object value") will be thrown.

    - -**Note:** It is not possible to know reflectively whether a particular object implements the iterator protocol. However, it is easy to create an object that satisfies _both_ the iterator and iterable protocols (as shown in the example below). - -Doing so allows an iterator to be consumed by the various syntaxes expecting iterables. Thus, it is seldom useful to implement the Iterator Protocol without also implementing Iterable. - - // Satisfies both the Iterator Protocol and Iterable - const myIterator = { - next: function() { - // ... - }, - [Symbol.iterator]: function() { return this; } - }; - -However, when possible, it's better for `iterable[Symbol.iterator]` to return different iterators that always start from the beginning, like `Set.prototype[@@iterator]()` does. - -## Examples using the iteration protocols - -A [`String`](global_objects/string) is an example of a built-in iterable object: - - const someString = 'hi'; - console.log(typeof someString[Symbol.iterator]); // "function" - -`String`'s [default iterator](global_objects/string/@@iterator) returns the string's code points one by one: - - const iterator = someString[Symbol.iterator](); - console.log(iterator + ''); // "[object String Iterator]" - - console.log(iterator.next()); // { value: "h", done: false } - console.log(iterator.next()); // { value: "i", done: false } - console.log(iterator.next()); // { value: undefined, done: true } - -Some built-in constructs—such as the [spread syntax](operators/spread_syntax)—use the same iteration protocol under the hood: - - console.log([...someString]); // ["h", "i"] - -You can redefine the iteration behavior by supplying our own `@@iterator`: - - // need to construct a String object explicitly to avoid auto-boxing - const someString = new String('hi'); - - someString[Symbol.iterator] = function () { - return { - // this is the iterator object, returning a single element (the string "bye") - next: function () { - return this._first ? { - value: 'bye', - done: (this._first = false) - } : { - done: true - } - }, - _first: true - }; - }; - -Notice how redefining `@@iterator` affects the behavior of built-in constructs that use the iteration protocol: - - console.log([...someString]); // ["bye"] - console.log(someString + ''); // "hi" - -## Iterable examples - -### Built-in iterables - -[`String`](global_objects/string), [`Array`](global_objects/array), [`TypedArray`](global_objects/typedarray), [`Map`](global_objects/map), and [`Set`](global_objects/set) are all built-in iterables, because each of their prototype objects implements an `@@iterator` method. - -### User-defined iterables - -You can make your own iterables like this: - - const myIterable = {}; - myIterable[Symbol.iterator] = function* () { - yield 1; - yield 2; - yield 3; - }; - console.log([...myIterable]); // [1, 2, 3] - -### Built-in APIs accepting iterables - -There are many APIs that accept iterables. Some examples include: - -- [`new Map([iterable])`](global_objects/map) -- [`new WeakMap([iterable])`](global_objects/weakmap) -- [`new Set([iterable])`](global_objects/set) -- [`new WeakSet([iterable])`](global_objects/weakset) - - - - new Map([[1, 'a'], [2, 'b'], [3, 'c']]).get(2); // "b" - - const myObj = {}; - - new WeakMap([ - [{}, 'a'], - [myObj, 'b'], - [{}, 'c'] - ]).get(myObj); // "b" - - new Set([1, 2, 3]).has(3); // true - new Set('123').has('2'); // true - - new WeakSet(function* () { - yield {} - yield myObj - yield {} - }()).has(myObj); // true - -#### See also - -- [`Promise.all(iterable)`](global_objects/promise/all) -- [`Promise.race(iterable)`](global_objects/promise/race) -- [`Array.from(iterable)`](global_objects/array/from) - -### Syntaxes expecting iterables - -Some statements and expressions expect iterables, for example the [`for...of`](statements/for...of) loops, the [spread operator](operators/spread_syntax)), [`yield*`](operators/yield*), and [`destructuring assignment`](operators/destructuring_assignment): - - for (const value of ['a', 'b', 'c']) { - console.log(value); - } - // "a" - // "b" - // "c" - - console.log([...'abc']); // ["a", "b", "c"] - - function* gen() { - yield* ['a', 'b', 'c']; - } - - console.log(gen().next()); // { value: "a", done: false } - - [a, b, c] = new Set(['a', 'b', 'c']); - console.log(a); // "a" - -### Non-well-formed iterables - -If an iterable's `@@iterator` method doesn't return an iterator object, then it's considered a _non-well-formed_ iterable. - -Using one is likely to result in runtime errors or buggy behavior: - - const nonWellFormedIterable = {}; - nonWellFormedIterable[Symbol.iterator] = () => 1; - [...nonWellFormedIterable]; // TypeError: [] is not a function - -## Iterator examples - -### Simple iterator - - function makeIterator(array) { - let nextIndex = 0 - return { - next: function() { - return nextIndex < array.length ? { - value: array[nextIndex++], - done: false - } : { - done: true - }; - } - }; - } - - const it = makeIterator(['yo', 'ya']); - - console.log(it.next().value); // 'yo' - console.log(it.next().value); // 'ya' - console.log(it.next().done); // true - -### Infinite iterator - - function idMaker() { - let index = 0; - return { - next: function() { - return { - value: index++, - done: false - }; - } - }; - } - - const it = idMaker(); - - console.log(it.next().value); // '0' - console.log(it.next().value); // '1' - console.log(it.next().value); // '2' - // ... - -### With a generator - - function* makeSimpleGenerator(array) { - let nextIndex = 0; - while (nextIndex < array.length) { - yield array[nextIndex++]; - } - } - - const gen = makeSimpleGenerator(['yo', 'ya']); - - console.log(gen.next().value); // 'yo' - console.log(gen.next().value); // 'ya' - console.log(gen.next().done); // true - - function* idMaker() { - let index = 0; - while (true) { - yield index++; - } - } - - const it = idMaker() - - console.log(it.next().value); // '0' - console.log(it.next().value); // '1' - console.log(it.next().value); // '2' - // ... - -### With ES2015 class - - class SimpleClass { - constructor(data) { - this.data = data; - } - - [Symbol.iterator]() { - // Use a new index for each iterator. This makes multiple - // iterations over the iterable safe for non-trivial cases, - // such as use of break or nested looping over the same iterable. - let index = 0; - - return { - next: () => { - if (index < this.data.length) { - return {value: this.data[index++], done: false} - } else { - return {done: true} - } - } - } - } - } - - const simple = new SimpleClass([1,2,3,4,5]); - - for (const val of simple) { - console.log(val); // '1' '2' '3' '4' '5' - } - -## Is a generator object an iterator or an iterable? - -A [generator object](global_objects/generator) is _both_ iterator and iterable: - - const aGeneratorObject = function* () { - yield 1; - yield 2; - yield 3; - }(); - - console.log(typeof aGeneratorObject.next); - // "function", because it has a next method, so it's an iterator - - console.log(typeof aGeneratorObject[Symbol.iterator]); - // "function", because it has an @@iterator method, so it's an iterable - - console.log(aGeneratorObject[Symbol.iterator]() === aGeneratorObject); - // true, because its @@iterator method returns itself (an iterator), so it's an well-formed iterable - - console.log([...aGeneratorObject]); - // [1, 2, 3] - - console.log(Symbol.iterator in aGeneratorObject) - // true, because @@iterator method is a property of aGeneratorObject - -## See also - -- [the `function*` documentation](statements/function*) -- [Iteration in the ECMAScript specification](https://tc39.es/ecma262/#sec-iteration) - -Iteration_protocols" Iteration_protocols - ---- ---- - -# Symbol.iterator - -The well-known `Symbol.iterator` symbol specifies the default iterator for an object. Used by [`for...of`](../../statements/for...of). - -## Description - -Whenever an object needs to be iterated (such as at the beginning of a `for..of` loop), its `@@iterator` method is called with no arguments, and the returned **iterator** is used to obtain the values to be iterated. - -Some built-in types have a default iteration behavior, while other types (such as [`Object`](../object)) do not. The built-in types with a `@@iterator` method are: - -- [`Array.prototype[@@iterator]()`](../array/@@iterator) -- [`TypedArray.prototype[@@iterator]()`](../typedarray/@@iterator) -- [`String.prototype[@@iterator]()`](../string/@@iterator) -- [`Map.prototype[@@iterator]()`](../map/@@iterator) -- [`Set.prototype[@@iterator]()`](../set/@@iterator) - -See also [Iteration protocols](../../iteration_protocols) for more information. - -Property attributes of `Symbol.iterator` - -Writable - -no - -Enumerable - -no - -Configurable - -no - -## Examples - -### User-defined iterables - -We can make our own iterables like this: - - var myIterable = {} - myIterable[Symbol.iterator] = function* () { - yield 1; - yield 2; - yield 3; - }; - [...myIterable] // [1, 2, 3] - -Or iterables can be defined directly inside a class or object using a [computed property](../../operators/object_initializer#computed_property_names): - - class Foo { - *[Symbol.iterator] () { - yield 1; - yield 2; - yield 3; - } - } - - const someObj = { - *[Symbol.iterator] () { - yield 'a'; - yield 'b'; - } - } - - console.log(...new Foo); // 1, 2, 3 - console.log(...someObj); // 'a', 'b' - -### Non-well-formed iterables - -If an iterable's `@@iterator` method does not return an iterator object, then it is a non-well-formed iterable. Using it as such is likely to result in runtime exceptions or buggy behavior: - - var nonWellFormedIterable = {} - nonWellFormedIterable[Symbol.iterator] = () => 1 - [...nonWellFormedIterable] // TypeError: [] is not a function - -## Specifications - -
    Specification
    ECMAScript (ECMA-262) -
    - -The definition of 'Symbol.iterator' in that specification.
    - -`iterator` - -43 - -12 - -36 - -No - -30 - -10 - -43 - -43 - -36 - -30 - -10 - -4.0 - -## See also - -- [Iteration protocols](../../iteration_protocols) -- [`Array.prototype[@@iterator]()`](../array/@@iterator) -- [`TypedArray.prototype[@@iterator]()`](../typedarray/@@iterator) -- [`String.prototype[@@iterator]()`](../string/@@iterator) -- [`Map.prototype[@@iterator]()`](../map/@@iterator) -- [`Set.prototype[@@iterator]()`](../set/@@iterator) - - - -Global_Objects/Symbol/iterator" Global_Objects/Symbol/iterator - ---- ---- - -# Array.prototype.join() - -The `join()` method creates and returns a new string by concatenating all of the elements in an array (or an [array-like object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects)), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator. - -## Syntax - - join() - join(separator) - -### Parameters - -`separator` Optional -Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (","). If `separator` is an empty string, all elements are joined without any characters in between them. - -### Return value - -A string with all array elements joined. If `arr.length` is `0`, the empty string is returned. - -## Description - -The string conversions of all array elements are joined into one string. - -**Warning:** If an element is `undefined`, `null` or an empty array `[]`, it is converted to an empty string. - -## Examples - -### Joining an array four different ways - -The following example creates an array, `a`, with three elements, then joins the array four times: using the default separator, then a comma and a space, then a plus and an empty string. - - var a = ['Wind', 'Water', 'Fire']; - a.join(); // 'Wind,Water,Fire' - a.join(', '); // 'Wind, Water, Fire' - a.join(' + '); // 'Wind + Water + Fire' - a.join(''); // 'WindWaterFire' - -### Joining an array-like object - -The following example joins array-like object (`arguments`), by calling [`Function.prototype.call`](../function/call) on `Array.prototype.join`. - - function f(a, b, c) { - var s = Array.prototype.join.call(arguments); - console.log(s); // '1,a,true' - } - f(1, 'a', true); - //expected output: "1,a,true" - -## Specifications - -
    Specification
    ECMAScript (ECMA-262) -
    - -The definition of 'Array.prototype.join' in that specification.
    - -`join` - -1 - -12 - -1 - -5.5 - -4 - -1 - -1 - -18 - -4 - -10.1 - -1 - - - -- [`String.prototype.split()`](../string/split) -- [`Array.prototype.toString()`](tostring) -- [`TypedArray.prototype.join()`](../typedarray/join) - -Global_Objects/Array/join" Global_Objects/Array/join - ---- ---- - -# JSON - -The `JSON` object contains methods for parsing [JavaScript Object Notation](https://json.org/) ([JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON)) and converting values to JSON. It can't be called or constructed, and aside from its two method properties, it has no interesting functionality of its own. - -## Description - -### JavaScript and JSON differences - -JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and [`null`](null). It is based upon JavaScript syntax but is distinct from it: some JavaScript is _not_ JSON. - -**Objects and Arrays** -Property names must be double-quoted strings; [trailing commas](../trailing_commas) are forbidden. - -**Numbers** -Leading zeros are prohibited. A decimal point must be followed by at least one digit. `NaN` and `Infinity` are unsupported. - -**Any JSON text is a valid JavaScript expression...** -...But only in JavaScript engines that have implemented the [proposal to make all JSON text valid ECMA-262](https://github.com/tc39/proposal-json-superset). In engines that haven't implemented the proposal, U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are allowed in string literals and property keys in JSON; but their use in these features in JavaScript string literals is a [`SyntaxError`](syntaxerror). - -Consider this example where [`JSON.parse()`](json/parse) parses the string as JSON and [`Global_Objects/eval`](eval) executes the string as JavaScript: - - let code = '"\u2028\u2029"' - JSON.parse(code) // evaluates to "\u2028\u2029" in all engines - eval(code) // throws a SyntaxError in old engines - -Other differences include allowing only double-quoted strings and having no provisions for [`undefined`](undefined) or comments. For those who wish to use a more human-friendly configuration format based on JSON, there is [JSON5](https://json5.org/), used by the Babel compiler, and the more commonly used [YAML](https://en.wikipedia.org/wiki/YAML). - -### Full JSON syntax - -The full JSON syntax is as follows: - - JSON = null - or true or false - or JSONNumber - or JSONString - or JSONObject - or JSONArray - - JSONNumber = - PositiveNumber - or PositiveNumber - PositiveNumber = DecimalNumber - or DecimalNumber . Digits - or DecimalNumber . Digits ExponentPart - or DecimalNumber ExponentPart - DecimalNumber = 0 - or OneToNine Digits - ExponentPart = e Exponent - or E Exponent - Exponent = Digits - or + Digits - or - Digits - Digits = Digit - or Digits Digit - Digit = 0 through 9 - OneToNine = 1 through 9 - - JSONString = "" - or " StringCharacters " - StringCharacters = StringCharacter - or StringCharacters StringCharacter - StringCharacter = any character - except " or \ or U+0000 through U+001F - or EscapeSequence - EscapeSequence = \" or \/ or \\ or \b or \f or \n or \r or \t - or \u HexDigit HexDigit HexDigit HexDigit - HexDigit = 0 through 9 - or A through F - or a through f - - JSONObject = { } - or { Members } - Members = JSONString : JSON - or Members , JSONString : JSON - - JSONArray = [ ] - or [ ArrayElements ] - ArrayElements = JSON - or ArrayElements , JSON - -Insignificant [whitespace](https://developer.mozilla.org/en-US/docs/Glossary/Whitespace) may be present anywhere except within a `JSONNumber` (numbers must contain no whitespace) or `JSONString` (where it is interpreted as the corresponding character in the string, or would cause an error). The tab character ([U+0009](https://unicode-table.com/en/0009/)), carriage return ([U+000D](https://unicode-table.com/en/000D/)), line feed ([U+000A](https://unicode-table.com/en/000A/)), and space ([U+0020](https://unicode-table.com/en/0020/)) characters are the only valid whitespace characters. - -## Static methods - -[`JSON.parse(text[, reviver])`](json/parse) -Parse the string `text` as JSON, optionally transform the produced value and its properties, and return the value. Any violations of the JSON syntax, including those pertaining to the differences between JavaScript and JSON, cause a [`SyntaxError`](syntaxerror) to be thrown. The `reviver` option allows for interpreting what the `replacer` has used to stand in for other datatypes. - -[`JSON.stringify(value[, replacer[, space]])`](json/stringify) -Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner. By default, all instances of [`undefined`](undefined) are replaced with [`null`](null), and other unsupported native data types are censored. The `replacer` option allows for specifying other behavior. - -## Examples - -### Example JSON - - { - "browsers": { - "firefox": { - "name": "Firefox", - "pref_url": "about:config", - "releases": { - "1": { - "release_date": "2004-11-09", - "status": "retired", - "engine": "Gecko", - "engine_version": "1.7" - } - } - } - } - } - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-json-object
    - -`JSON` - -3 - -12 - -3.5 - -8 - -10.5 - -4 - -≤37 - -18 - -4 - -11 - -4 - -1.0 - -`json_superset` - -66 - -79 - -62 - -No - -53 - -12 - -66 - -66 - -62 - -47 - -12 - -9.0 - -`parse` - -3 - -12 - -3.5 - -8 - -10.5 - -4 - -≤37 - -18 - -4 - -11 - -4 - -1.0 - -`stringify` - -3 - -12 - -3.5 - -8 - -10.5 - -4 - -≤37 - -18 - -4 - -11 - -4 - - - -- [`Date.prototype.toJSON()`](date/tojson) -- [JSON Diff](http://www.jsondiff.com/) checker -- [JSON Beautifier/editor](https://jsonbeautifier.org/) -- [JSON Parser](http://jsonparser.org/) -- [JSON Validator](https://tools.learningcontainer.com/json-validator/) - -Global_Objects/JSON" Global_Objects/JSON - ---- ---- - -# SyntaxError: JSON.parse: bad parsing - -The JavaScript exceptions thrown by [`JSON.parse()`](../global_objects/json/parse) occur when string failed to be parsed as JSON. - -## Message - - SyntaxError: JSON.parse: unterminated string literal - SyntaxError: JSON.parse: bad control character in string literal - SyntaxError: JSON.parse: bad character in string literal - SyntaxError: JSON.parse: bad Unicode escape - SyntaxError: JSON.parse: bad escape character - SyntaxError: JSON.parse: unterminated string - SyntaxError: JSON.parse: no number after minus sign - SyntaxError: JSON.parse: unexpected non-digit - SyntaxError: JSON.parse: missing digits after decimal point - SyntaxError: JSON.parse: unterminated fractional number - SyntaxError: JSON.parse: missing digits after exponent indicator - SyntaxError: JSON.parse: missing digits after exponent sign - SyntaxError: JSON.parse: exponent part is missing a number - SyntaxError: JSON.parse: unexpected end of data - SyntaxError: JSON.parse: unexpected keyword - SyntaxError: JSON.parse: unexpected character - SyntaxError: JSON.parse: end of data while reading object contents - SyntaxError: JSON.parse: expected property name or '}' - SyntaxError: JSON.parse: end of data when ',' or ']' was expected - SyntaxError: JSON.parse: expected ',' or ']' after array element - SyntaxError: JSON.parse: end of data when property name was expected - SyntaxError: JSON.parse: expected double-quoted property name - SyntaxError: JSON.parse: end of data after property name when ':' was expected - SyntaxError: JSON.parse: expected ':' after property name in object - SyntaxError: JSON.parse: end of data after property value in object - SyntaxError: JSON.parse: expected ',' or '}' after property value in object - SyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal - SyntaxError: JSON.parse: property names must be double-quoted strings - SyntaxError: JSON.parse: expected property name or '}' - SyntaxError: JSON.parse: unexpected character - SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data - SyntaxError: JSON.parse Error: Invalid character at position {0} (Edge) - -## Error type - -[`SyntaxError`](../global_objects/syntaxerror) - -## What went wrong? - -[`JSON.parse()`](../global_objects/json/parse) parses a string as JSON. This string has to be valid JSON and will throw this error if incorrect syntax was encountered. - -## Examples - -### `JSON.parse()` does not allow trailing commas - -Both lines will throw a SyntaxError: - - JSON.parse('[1, 2, 3, 4,]'); - JSON.parse('{"foo": 1,}'); - // SyntaxError JSON.parse: unexpected character - // at line 1 column 14 of the JSON data - -Omit the trailing commas to parse the JSON correctly: - - JSON.parse('[1, 2, 3, 4]'); - JSON.parse('{"foo": 1}'); - -### Property names must be double-quoted strings - -You cannot use single-quotes around properties, like 'foo'. - - JSON.parse("{'foo': 1}"); - // SyntaxError: JSON.parse: expected property name or '}' - // at line 1 column 2 of the JSON data - -Instead write "foo": - - JSON.parse('{"foo": 1}'); - -### Leading zeros and decimal points - -You cannot use leading zeros, like 01, and decimal points must be followed by at least one digit. - - JSON.parse('{"foo": 01}'); - // SyntaxError: JSON.parse: expected ',' or '}' after property value - // in object at line 1 column 2 of the JSON data - - JSON.parse('{"foo": 1.}'); - // SyntaxError: JSON.parse: unterminated fractional number - // at line 1 column 2 of the JSON data - -Instead write just 1 without a zero and use at least one digit after a decimal point: - - JSON.parse('{"foo": 1}'); - JSON.parse('{"foo": 1.0}'); - -## See also - -- [`JSON`](../global_objects/json) -- [`JSON.parse()`](../global_objects/json/parse) -- [`JSON.stringify()`](../global_objects/json/stringify) - -Errors/JSON_bad_parse" Errors/JSON_bad_parse - ---- ---- - -# Symbol.keyFor() - -The `Symbol.keyFor(sym)` method retrieves a shared symbol key from the global symbol registry for the given symbol. - -## Syntax - - Symbol.keyFor(sym); - -### Parameters - -`sym` -Symbol, required. The symbol to find a key for. - -### Return value - -A string representing the key for the given symbol if one is found on the global registry; otherwise, [`undefined`](../undefined). - -## Examples - -### Using keyFor() - - var globalSym = Symbol.for('foo'); // create a new global symbol - Symbol.keyFor(globalSym); // "foo" - - var localSym = Symbol(); - Symbol.keyFor(localSym); // undefined - - // well-known symbols are not symbols registered - // in the global symbol registry - Symbol.keyFor(Symbol.iterator) // undefined - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-symbol.keyfor
    - -`keyFor` - -40 - -12 - -36 - -No - -27 - -9 - -40 - -40 - -36 - -27 - -9 - -4.0 - -## See also - -- [`Symbol.for()`](for) - - - -Global_Objects/Symbol/keyFor" Global_Objects/Symbol/keyFor - ---- ---- - -# Object.keys() - -The `Object.keys()` method returns an array of a given object's own enumerable property **names**, iterated in the same order that a normal loop would. - -## Syntax - - Object.keys(obj) - -### Parameters - -`obj` -The object of which the enumerable's own properties are to be returned. - -### Return value - -An array of strings that represent all the enumerable properties of the given object. - -## Description - -`Object.keys()` returns an array whose elements are strings corresponding to the enumerable properties found directly upon `object`. The ordering of the properties is the same as that given by looping over the properties of the object manually. - -## Examples - -### Using Object.keys - - // simple array - const arr = ['a', 'b', 'c']; - console.log(Object.keys(arr)); // console: ['0', '1', '2'] - - // array-like object - const obj = { 0: 'a', 1: 'b', 2: 'c' }; - console.log(Object.keys(obj)); // console: ['0', '1', '2'] - - // array-like object with random key ordering - const anObj = { 100: 'a', 2: 'b', 7: 'c' }; - console.log(Object.keys(anObj)); // console: ['2', '7', '100'] - - // getFoo is a property which isn't enumerable - const myObj = Object.create({}, { - getFoo: { - value: function () { return this.foo; } - } - }); - myObj.foo = 1; - console.log(Object.keys(myObj)); // console: ['foo'] - -If you want _all_ properties—including non-enumerables—see [`Object.getOwnPropertyNames()`](getownpropertynames). - -### Non-object coercion - -In ES5, if the argument to this method is not an object (a primitive), then it will cause a [`TypeError`](../typeerror). - -From ES2015 onwards, a non-object argument will be coerced to an object. - - // In ES5 - Object.keys('foo'); // TypeError: "foo" is not an object - - // In ES2015+ - Object.keys('foo'); // ["0", "1", "2"] - -## Polyfill - -To add compatible `Object.keys` support in older environments that do not natively support it, copy the following snippet: - - // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys - if (!Object.keys) { - Object.keys = (function() { - 'use strict'; - var hasOwnProperty = Object.prototype.hasOwnProperty, - hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'), - dontEnums = [ - 'toString', - 'toLocaleString', - 'valueOf', - 'hasOwnProperty', - 'isPrototypeOf', - 'propertyIsEnumerable', - 'constructor' - ], - dontEnumsLength = dontEnums.length; - - return function(obj) { - if (typeof obj !== 'function' && (typeof obj !== 'object' || obj === null)) { - throw new TypeError('Object.keys called on non-object'); - } - - var result = [], prop, i; - - for (prop in obj) { - if (hasOwnProperty.call(obj, prop)) { - result.push(prop); - } - } - - if (hasDontEnumBug) { - for (i = 0; i < dontEnumsLength; i++) { - if (hasOwnProperty.call(obj, dontEnums[i])) { - result.push(dontEnums[i]); - } - } - } - return result; - }; - }()); - } - -Please note that the above code includes non-enumerable keys in IE7 (and maybe IE8), when passing in an object from a different window. - -For a simple Browser Polyfill, see [Javascript - Object.keys Browser Compatibility](https://tokenposts.blogspot.com.au/2012/04/javascript-objectkeys-browser.html). - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-object.keys
    - -`keys` - -5 - -12 - -4 - -9 - -12 - -5 - -1 - -18 - -4 - -12 - -5 - - - -- [Enumerability and ownership of properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) -- [`Object.prototype.propertyIsEnumerable()`](propertyisenumerable) -- [`Object.create()`](create) -- [`Object.getOwnPropertyNames()`](getownpropertynames) -- [`Object.values()`](values) -- [`Object.entries()`](entries) - - - -Global_Objects/Object/keys" Global_Objects/Object/keys - ---- ---- - -# label - -The **labeled statement** can be used with [`break`](break) or [`continue`](continue) statements. It is prefixing a statement with an identifier which you can refer to. - -## Syntax - - label : - statement - -`label` -Any JavaScript identifier that is not a reserved word. - -`statement` -A JavaScript statement. `break` can be used with any labeled statement, and `continue` can be used with looping labeled statements. - -## Description - -You can use a label to identify a loop, and then use the `break` or `continue` statements to indicate whether a program should interrupt the loop or continue its execution. - -Note that JavaScript has _no_ `goto` statement, you can only use labels with `break` or `continue`. - -In [strict mode](../strict_mode) code, you can't use "`let`" as a label name. It will throw a [`SyntaxError`](../global_objects/syntaxerror) (let is a reserved identifier). - -## Examples - -### Using a labeled continue with for loops - - var i, j; - - loop1: - for (i = 0; i < 3; i++) { //The first for statement is labeled "loop1" - loop2: - for (j = 0; j < 3; j++) { //The second for statement is labeled "loop2" - if (i === 1 && j === 1) { - continue loop1; - } - console.log('i = ' + i + ', j = ' + j); - } - } - - // Output is: - // "i = 0, j = 0" - // "i = 0, j = 1" - // "i = 0, j = 2" - // "i = 1, j = 0" - // "i = 2, j = 0" - // "i = 2, j = 1" - // "i = 2, j = 2" - // Notice how it skips both "i = 1, j = 1" and "i = 1, j = 2" - -### Using a labeled continue statement - -Given an array of items and an array of tests, this example counts the number of items that passes all the tests. - - var itemsPassed = 0; - var i, j; - - top: - for (i = 0; i < items.length; i++) { - for (j = 0; j < tests.length; j++) { - if (!tests[j].pass(items[i])) { - continue top; - } - } - - itemsPassed++; - } - -### Using a labeled break with for loops - - var i, j; - - loop1: - for (i = 0; i < 3; i++) { //The first for statement is labeled "loop1" - loop2: - for (j = 0; j < 3; j++) { //The second for statement is labeled "loop2" - if (i === 1 && j === 1) { - break loop1; - } - console.log('i = ' + i + ', j = ' + j); - } - } - - // Output is: - // "i = 0, j = 0" - // "i = 0, j = 1" - // "i = 0, j = 2" - // "i = 1, j = 0" - // Notice the difference with the previous continue example - -### Using a labeled break statement - -Given an array of items and an array of tests, this example determines whether all items pass all tests. - - var allPass = true; - var i, j; - - top: - for (i = 0; i < items.length; i++) { - for (j = 0; j < tests.length; j++) { - if (!tests[j].pass(items[i])) { - allPass = false; - break top; - } - } - } - -### Using a labeled block with break - -You can use labels within simple blocks, but only `break` statements can make use of non-loop labels. - - foo: { - console.log('face'); - break foo; - console.log('this will not be executed'); - } - console.log('swap'); - - // this will log: - - // "face" - // "swap" - -### Labeled function declarations - -Starting with ECMAScript 2015, labeled function declarations are now standardized for non-strict code in the [web compatibility annex of the specification](https://www.ecma-international.org/ecma-262/6.0/#sec-labelled-function-declarations). - - L: function F() {} - -In [strict mode](../strict_mode) code, however, this will throw a [`SyntaxError`](../global_objects/syntaxerror): - - 'use strict'; - L: function F() {} - // SyntaxError: functions cannot be labelled - -[Generator functions](function*) can neither be labeled in strict code, nor in non-strict code: - - L: function* F() {} - // SyntaxError: generator functions cannot be labelled - -## Specifications - -
    Specification
    ECMAScript (ECMA-262) -
    - -The definition of 'Labelled statement' in that specification.
    - -`label` - -1 - -12 - -1 - -4 - -4 - -1 - -1 - -18 - -4 - -10.1 - -1 - - - -- [`break`](break) -- [`continue`](continue) - - - -Statements/label" Statements/label - ---- ---- - -# Intl.Locale.prototype.language - -The `Intl.Locale.prototype.language` property is an accessor property that returns the language associated with the locale. - -## Description - -Language is one of the core features of a locale. The Unicode specification treats the language identifier of a locale as the language and the region together (to make a distinction between dialects and variations, e.g. British English vs. American English). The `language` property of a [`Locale`](../locale) returns strictly the locale's language subtag. - -## Examples - -### Setting the language in the locale identifer string argument - -In order to be a valid Unicode locale identifier, a string must start with the language subtag. The main argument to the [`Locale`](locale) constructor must be a valid Unicode locale identifier, so whenever the constructor is used, it must be passed an identifier with a language subtag. - - let langStr = new Intl.Locale("en-Latn-US"); - - console.log(langStr.language); // Prints "en" - -### Overriding language via the configuration object - -While the language subtag must be specified, the [`Locale`](../locale) constructor takes a configuration object, which can override the language subtag. - - let langObj = new Intl.Locale("en-Latn-US", {language: "es"}); - - console.log(langObj.language); // Prints "es" - -## Specifications - -
    Specification
    ECMAScript Internationalization API Specification (ECMAScript Internationalization API) -
    - -#sec-Intl.Locale.prototype.language
    - -`language` - -74 - -79 - -75 - -No - -62 - -14 - -74 - -74 - -79 - -53 - -14 - -1 - -- [`Intl.Locale`](../locale) -- [Unicode language subtag specification](https://www.unicode.org/reports/tr35/#unicode_language_subtag_validity) - -Global_Objects/Intl/Locale/language" Global_Objects/Intl/Locale/language - ---- ---- - -# RegExp: lastIndex - -`lastIndex` is a read/write integer property of [`RegExp`](../regexp) instances that specifies the index at which to start the next match. - -Note that `lastIndex` is not a property of the [`RegExp`](../regexp) prototype but is instead only exposed from [`RegExp`](../regexp) instances. - -Property attributes of `RegExp: lastIndex` - -Writable - -yes - -Enumerable - -no - -Configurable - -no - -## Description - -This property is set only if the regular expression instance used the `g` flag to indicate a global search, or the `y` flag to indicate a sticky search. The following rules apply: - -- If `lastIndex` is greater than the length of the string, [`test()`](test) and [`exec()`](exec) fail, then `lastIndex` is set to 0. -- If `lastIndex` is equal to or less than the length of the string and if the regular expression matches the empty string, then the regular expression matches input starting from `lastIndex`. -- If `lastIndex` is equal to the length of the string and if the regular expression does not match the empty string, then the regular expression mismatches input, and `lastIndex` is reset to 0. -- Otherwise, `lastIndex` is set to the next position following the most recent match. - -## Examples - -### Using lastIndex - -Consider the following sequence of statements: - - var re = /(hi)?/g; - -Matches the empty string. - - console.log(re.exec('hi')); - console.log(re.lastIndex); - -Returns `["hi", "hi"]` with `lastIndex` equal to 2. - - console.log(re.exec('hi')); - console.log(re.lastIndex); - -Returns `["", undefined]`, an empty array whose zeroth element is the match string. In this case, the empty string because `lastIndex` was 2 (and still is 2) and `hi` has length 2. - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-properties-of-regexp-instances
    - -`lastIndex` - -1 - -12 - -1 - -5.5 - -5 - -1 - -1 - -18 - -4 - -10.1 - -1 - - - -- [`RegExp.prototype.dotAll`](dotall) -- [`RegExp.prototype.global`](global) -- [`RegExp.prototype.hasIndices`](hasindices) -- [`RegExp.prototype.ignoreCase`](ignorecase) -- [`RegExp.prototype.multiline`](multiline) -- [`RegExp.prototype.source`](source) -- [`RegExp.prototype.sticky`](sticky) -- [`RegExp.prototype.unicode`](unicode) - - - -Global_Objects/RegExp/lastIndex" Global_Objects/RegExp/lastIndex - ---- ---- - -# Array.prototype.lastIndexOf() - -The `lastIndexOf()` method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at `fromIndex`. - -## Syntax - - lastIndexOf(searchElement) - lastIndexOf(searchElement, fromIndex) - -### Parameters - -`searchElement` -Element to locate in the array. - -`fromIndex` Optional -The index at which to start searching backwards. Defaults to the array's length minus one (`arr.length - 1`), i.e. the whole array will be searched. If the index is greater than or equal to the length of the array, the whole array will be searched. If negative, it is taken as the offset from the end of the array. Note that even when the index is negative, the array is still searched from back to front. If the calculated index is less than 0, -1 is returned, i.e. the array will not be searched. - -### Return value - -The last index of the element in the array; **-1** if not found. - -## Description - -`lastIndexOf` compares `searchElement` to elements of the Array using [strict equality](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators#using_the_equality_operators) (the same method used by the ===, or triple-equals, operator). - -## Examples - -### Using `lastIndexOf` - -The following example uses `lastIndexOf` to locate values in an array. - - var numbers = [2, 5, 9, 2]; - numbers.lastIndexOf(2); // 3 - numbers.lastIndexOf(7); // -1 - numbers.lastIndexOf(2, 3); // 3 - numbers.lastIndexOf(2, 2); // 0 - numbers.lastIndexOf(2, -2); // 0 - numbers.lastIndexOf(2, -1); // 3 - -### Finding all the occurrences of an element - -The following example uses `lastIndexOf` to find all the indices of an element in a given array, using [`push`](push) to add them to another array as they are found. - - var indices = []; - var array = ['a', 'b', 'a', 'c', 'a', 'd']; - var element = 'a'; - var idx = array.lastIndexOf(element); - while (idx != -1) { - indices.push(idx); - idx = (idx > 0 ? array.lastIndexOf(element, idx - 1) : -1); - } - - console.log(indices); - // [4, 2, 0] - -Note that we have to handle the case `idx == 0` separately here because the element will always be found regardless of the `fromIndex` parameter if it is the first element of the array. This is different from the [`indexOf`](indexof) method. - -## Polyfill - -`lastIndexOf` was added to the ECMA-262 standard in the 5th edition; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of `lastIndexOf` in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming [`Object`](../object), [`TypeError`](../typeerror), [`Number`](../number), [`Math.floor`](../math/floor), [`Math.abs`](../math/abs), and [`Math.min`](../math/min) have their original values. - - // Production steps of ECMA-262, Edition 5, 15.4.4.15 - // Reference: https://es5.github.io/#x15.4.4.15 - if (!Array.prototype.lastIndexOf) { - Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) { - 'use strict'; - - if (this === void 0 || this === null) { - throw new TypeError(); - } - - var n, k, - t = Object(this), - len = t.length >>> 0; - if (len === 0) { - return -1; - } - - n = len - 1; - if (arguments.length > 1) { - n = Number(arguments[1]); - if (n != n) { - n = 0; - } - else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) { - n = (n > 0 || -1) * Math.floor(Math.abs(n)); - } - } - - for (k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n); k >= 0; k--) { - if (k in t && t[k] === searchElement) { - return k; - } - } - return -1; - }; - } - -Again, note that this implementation aims for absolute compatibility with `lastIndexOf` in Firefox and the SpiderMonkey JavaScript engine, including in several cases which are arguably edge cases. If you intend to use this in real-world applications, you may be able to calculate `from` with less complicated code if you ignore those cases. - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-array.prototype.lastindexof
    - -`lastIndexOf` - -1 - -12 - -1.5 - -9 - -9.5 - -3 - -≤37 - -18 - -4 - -10.1 - -1 - - - -- [`Array.prototype.indexOf()`](indexof) -- [`TypedArray.prototype.lastIndexOf()`](../typedarray/lastindexof) - -Global_Objects/Array/lastIndexOf" Global_Objects/Array/lastIndexOf - ---- ---- - -# Left shift (<<) - -The `<<` shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right. - -## Syntax - - a << b - -## Description - -This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right. - -For example, `9 << 2` yields 36: - - . 9 (base 10): 00000000000000000000000000001001 (base 2) - -------------------------------- - 9 << 2 (base 10): 00000000000000000000000000100100 (base 2) = 36 (base 10) - -Bitwise shifting any number `x` to the left by `y` bits yields `x * 2 ** y`. -So e.g.: `9 << 3` translates to: `9 * (2 ** 3) = 9 * (8) = 72`. - -## Examples - -### Using left shift - - 9 << 3; // 72 - - // 9 * (2 ** 3) = 9 * (8) = 72 - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-left-shift-operator
    - -`Left_shift` - -1 - -12 - -1 - -3 - -3 - -1 - -1 - -18 - -4 - -10.1 - -1 - - - -- [Bitwise operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#bitwise) -- [Left shift assignment operator](left_shift_assignment) - - - -Operators/Left_shift" Operators/Left_shift - ---- ---- - -# Left shift assignment (<<=) - -The left shift assignment operator (`<<=`) moves the specified amount of bits to the left and assigns the result to the variable. - -## Syntax - - Operator: x <<= y - Meaning: x = x << y - -## Examples - -### Using left shift assignment - - let a = 5; - // 00000000000000000000000000000101 - - a <<= 2; // 20 - // 00000000000000000000000000010100 - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-assignment-operators
    - -`Left_shift_assignment` - -1 - -12 - -1 - -3 - -3 - -1 - -1 - -18 - -4 - -10.1 - -1 - - - -- [Assignment operators in the JS guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#assignment) -- [Left shift operator](left_shift) - - - -Operators/Left_shift_assignment" Operators/Left_shift_assignment - ---- ---- - -# Array.prototype.length - -The `length` property of an object which is an instance of type `Array` sets or returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. - -## Description - -The value of the `length` property is an integer with a positive sign and a value less than 2 to the 32nd power (232). - - var namelistA = new Array(4294967296); //2 to the 32nd power = 4294967296 - var namelistC = new Array(-100) //negative sign - - console.log(namelistA.length); //RangeError: Invalid array length - console.log(namelistC.length); //RangeError: Invalid array length - - var namelistB = []; - namelistB.length = Math.pow(2,32)-1; //set array length less than 2 to the 32nd power - console.log(namelistB.length); - - //4294967295 - -You can set the `length` property to truncate an array at any time. When you extend an array by changing its `length` property, the number of actual elements increases; for example, if you set `length` to 3 when it is currently 2, the array now contains 3 elements, which causes the third element to be a non-iterable empty slot. - - const arr = [1, 2]; - console.log(arr); - // [ 1, 2 ] - - arr.length = 5; // set array length to 5 while currently 2. - console.log(arr); - // [ 1, 2, <3 empty items> ] - - arr.forEach(element => console.log(element)); - // 1 - // 2 - -As you can see, the `length` property does not necessarily indicate the number of defined values in the array. See also [Relationship between `length` and numerical properties](../array#relationship_between_length_and_numerical_properties). - -Property attributes of `Array.prototype.length` - -Writable - -yes - -Enumerable - -no - -Configurable - -no - -- `Writable`: If this attribute set to `false`, the value of the property cannot be changed. -- `Configurable`: If this attribute set to `false`, any attempts to delete the property or change its attributes (`Writable`, `Configurable`, or `Enumerable`) will fail. -- `Enumerable`: If this attribute set to `true`, the property will be iterated over during [for](../../statements/for) or [for..in](../../statements/for...in) loops. - -## Examples - -### Iterating over an array - -In the following example, the array `numbers` is iterated through by looking at the `length` property. The value in each element is then doubled. - - var numbers = [1, 2, 3, 4, 5]; - var length = numbers.length; - for (var i = 0; i < length; i++) { - numbers[i] *= 2; - } - // numbers is now [2, 4, 6, 8, 10] - -### Shortening an array - -The following example shortens the array `numbers` to a length of 3 if the current length is greater than 3. - - var numbers = [1, 2, 3, 4, 5]; - - if (numbers.length > 3) { - numbers.length = 3; - } - - console.log(numbers); // [1, 2, 3] - console.log(numbers.length); // 3 - -### Create empty array of fixed length - - var numbers = []; - numbers.length = 3; - console.log(numbers); // [undefined, undefined, undefined] - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-properties-of-array-instances-length
    - -`length` - -1 - -12 - -1 - -4 - -4 - -1 - -≤37 - -18 - -4 - -10.1 - -1 - - - -- [`Array`](../array) -- [RangeError: invalid array length](../../errors/invalid_array_length) - -Global_Objects/Array/length" Global_Objects/Array/length - ---- ---- - -# Less than (<) - -The less than operator (`<`) returns `true` if the left operand is less than the right operand, and `false` otherwise. - -## Syntax - - x < y - -## Description - -The operands are compared using the [Abstract Relational Comparison](https://tc39.es/ecma262/#sec-abstract-relational-comparison) algorithm, which is roughly summarised below: - -- First, objects are converted to primitives using `Symbol.ToPrimitive` with the `hint` parameter be `'number'`. -- If both values are strings, they are compared as strings, based on the values of the Unicode code points they contain. -- Otherwise JavaScript attempts to convert non-numeric types to numeric values: - - Boolean values `true` and `false` are converted to 1 and 0 respectively. - - `null` is converted to 0. - - `undefined` is converted to `NaN`. - - Strings are converted based on the values they contain, and are converted as `NaN` if they do not contain numeric values. -- If either value is `NaN`, the operator returns `false`. -- Otherwise the values are compared as numeric values. - -## Examples - -### String to string comparison - - console.log("a" < "b"); // true - console.log("a" < "a"); // false - console.log("a" < "3"); // false - -### String to number comparison - - console.log("5" < 3); // false - console.log("3" < 3); // false - console.log("3" < 5); // true - - console.log("hello" < 5); // false - console.log(5 < "hello"); // false - - console.log("5" < 3n); // false - console.log("3" < 5n); // true - -### Number to Number comparison - - console.log(5 < 3); // false - console.log(3 < 3); // false - console.log(3 < 5); // true - -### Number to BigInt comparison - - console.log(5n < 3); // false - console.log(3 < 5n); // true - -### Comparing Boolean, null, undefined, NaN - - console.log(true < false); // false - console.log(false < true); // true - - console.log(0 < true); // true - console.log(true < 1); // false - - console.log(null < 0); // false - console.log(null < 1); // true - - console.log(undefined < 3); // false - console.log(3 < undefined); // false - - console.log(3 < NaN); // false - console.log(NaN < 3); // false - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-relational-operators
    - -`Less_than` - -1 - -12 - -1 - -3 - -3 - -1 - -1 - -18 - -4 - -10.1 - -1 - - - -- [Greater than operator](greater_than) -- [Greater than or equal operator](greater_than_or_equal) -- [Less than or equal operator](less_than_or_equal) - - - -Operators/Less_than" Operators/Less_than - ---- ---- - -# Less than or equal (<=) - -The less than or equal operator (`<=`) returns `true` if the left operand is less than or equal to the right operand, and `false` otherwise. - -## Syntax - - x <= y - -## Description - -The operands are compared using the [Abstract Relational Comparison](https://tc39.es/ecma262/#sec-abstract-relational-comparison) algorithm. See the documentation for the [Less than](less_than) operator for a summary of this algorithm. - -## Examples - -### String to string comparison - - console.log("a" <= "b"); // true - console.log("a" <= "a"); // true - console.log("a" <= "3"); // false - -### String to number comparison - - console.log("5" <= 3); // false - console.log("3" <= 3); // true - console.log("3" <= 5); // true - - console.log("hello" <= 5); // false - console.log(5 <= "hello"); // false - -### Number to Number comparison - - console.log(5 <= 3); // false - console.log(3 <= 3); // true - console.log(3 <= 5); // true - -### Number to BigInt comparison - - console.log(5n <= 3); // false - console.log(3 <= 3n); // true - console.log(3 <= 5n); // true - -### Comparing Boolean, null, undefined, NaN - - console.log(true <= false); // false - console.log(true <= true); // true - console.log(false <= true); // true - - console.log(true <= 0); // false - console.log(true <= 1); // true - - console.log(null <= 0); // true - console.log(1 <= null); // false - - console.log(undefined <= 3); // false - console.log(3 <= undefined); // false - - console.log(3 <= NaN); // false - console.log(NaN <= 3); // false - -## Specifications - -
    Specification
    ECMAScript (ECMA-262) -
    - -The definition of 'Relational operators' in that specification.
    - -`Less_than_or_equal` - -1 - -12 - -1 - -3 - -3 - -1 - -1 - -18 - -4 - -10.1 - -1 - - - -- [Greater than operator](greater_than) -- [Greater than or equal operator](greater_than_or_equal) -- [Less than operator](less_than) - - - -Operators/Less_than_or_equal" Operators/Less_than_or_equal - ---- ---- - -# let - -The `let` statement declares a block-scoped local variable, optionally initializing it to a value. - -## Syntax - - let name1 [= value1] [, name2 [= value2]] [, ..., nameN [= valueN]; - -### Parameters - -`nameN` -The names of the variable or variables to declare. Each must be a legal JavaScript identifier. - -` value``N ` Optional -For each variable declared, you may optionally specify its initial value to any legal JavaScript expression. - -Alternatively, the [Destructuring Assignment](../operators/destructuring_assignment) syntax can also be used to declare variables. - - let { bar } = foo; // where foo = { bar:10, baz:12 }; - /* This creates a variable with the name 'bar', which has a value of 10 */ - -## Description - -`let` allows you to declare variables that are limited to the scope of a [block](block) statement, or expression on which it is used, unlike the [`var`](var) keyword, which declares a variable globally, or locally to an entire function regardless of block scope. The other difference between [`var`](var) and `let` is that the latter is initialized to a value only when a [parser evaluates it (see below)](#temporal_dead_zone). - -Just like [`const`](const#description) the `let` does _not_ create properties of the [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) object when declared globally (in the top-most scope). - -An explanation of why the name "**let**" was chosen can be found [here](https://stackoverflow.com/questions/37916940/why-was-the-name-let-chosen-for-block-scoped-variable-declarations-in-javascri). - -**Note:** Many issues with `let` variables can be avoided by declaring them at the top of the scope in which they are used (doing so may impact readibility). - -## Examples - -### Scoping rules - -Variables declared by `let` have their scope in the block for which they are declared, as well as in any contained sub-blocks. In this way, `let` works very much like `var`. The main difference is that the scope of a `var` variable is the entire enclosing function: - - function varTest() { - var x = 1; - { - var x = 2; // same variable! - console.log(x); // 2 - } - console.log(x); // 2 - } - - function letTest() { - let x = 1; - { - let x = 2; // different variable - console.log(x); // 2 - } - console.log(x); // 1 - } - -At the top level of programs and functions, `let`, unlike `var`, does not create a property on the global object. For example: - - var x = 'global'; - let y = 'global'; - console.log(this.x); // "global" - console.log(this.y); // undefined - -### Emulating private members - -In dealing with [constructors](https://developer.mozilla.org/en-US/docs/Glossary/Constructor) it is possible to use the `let` bindings to share one or more private members without using [closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures): - - var Thing; - - { - let privateScope = new WeakMap(); - let counter = 0; - - Thing = function() { - this.someProperty = 'foo'; - - privateScope.set(this, { - hidden: ++counter, - }); - }; - - Thing.prototype.showPublic = function() { - return this.someProperty; - }; - - Thing.prototype.showPrivate = function() { - return privateScope.get(this).hidden; - }; - } - - console.log(typeof privateScope); - // "undefined" - - var thing = new Thing(); - - console.log(thing); - // Thing {someProperty: "foo"} - - thing.showPublic(); - // "foo" - - thing.showPrivate(); - // 1 - -The same privacy pattern with closures over local variables can be created with `var`, but those need a function scope (typically an [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) in the module pattern) instead of just a block scope like in the example above. - -### Redeclarations - -Redeclaring the same variable within the same function or block scope raises a [`SyntaxError`](../global_objects/syntaxerror). - - if (x) { - let foo; - let foo; // SyntaxError thrown. - } - -You may encounter errors in [`switch`](switch) statements because there is only one block. - - let x = 1; - switch(x) { - case 0: - let foo; - break; - - case 1: - let foo; // SyntaxError for redeclaration. - break; - } - -However, it's important to point out that a block nested inside a case clause will create a new block scoped lexical environment, which will not produce the redeclaration errors shown above. - - let x = 1; - - switch(x) { - case 0: { - let foo; - break; - } - case 1: { - let foo; - break; - } - } - -### Temporal dead zone (TDZ) - -`let` variables cannot be read/written until they have been fully initialized, which happens when they are declared (if no initial value is specified on declaration, the variable is initialized with a value of `undefined`). Accessing the variable before the initialization results in a [`ReferenceError`](../global_objects/referenceerror). - -**Note:** This differs from [`var`](var#var_hoisting) variables, which will return a value of `undefined` if they are accessed before they are declared. - -The variable is said to be in a "temporal dead zone" (TDZ) from the start of the block until the initialization has completed. - - { // TDZ starts at beginning of scope - console.log(bar); // undefined - console.log(foo); // ReferenceError - var bar = 1; - let foo = 2; // End of TDZ (for foo) - } - -The term "temporal" is used because the zone depends on the order of execution (time) rather than the order in which the code is written (position). For example, the code below works because, even though the function that uses the `let` variable appears before the variable is declared, the function is _called_ outside the TDZ. - - { - // TDZ starts at beginning of scope - const func = () => console.log(letVar); // OK - - // Within the TDZ letVar access throws `ReferenceError` - - let letVar = 3; // End of TDZ (for letVar) - func(); // Called outside TDZ! - } - -#### The TDZ and `typeof` - -Using the `typeof` operator for a `let` variable in its TDZ will throw a [`ReferenceError`](../global_objects/referenceerror): - - // results in a 'ReferenceError' - console.log(typeof i); - let i = 10; - -This differs from using `typeof` for undeclared variables, and variables that hold a value of `undefined`: - - // prints out 'undefined' - console.log(typeof undeclaredVariable); - -#### TDZ combined with lexical scoping - -The following code results in a `ReferenceError` at the line shown: - - function test(){ - var foo = 33; - if(foo) { - let foo = (foo + 55); // ReferenceError - } - } - test(); - -The `if` block is evaluated because the outer `var foo` has a value. However due to lexical scoping this value is not available inside the block: the identifier `foo` _inside_ the `if` block is the `let foo`. The expression `(foo + 55)` throws a `ReferenceError` because initialization of `let foo` has not completed — it is still in the temporal dead zone. - -This phenomenon can be confusing in a situation like the following. The instruction `let n of n.a` is already inside the private scope of the for loop's block. So, the identifier `n.a` is resolved to the property '`a`' of the '`n`' object located in the first part of the instruction itself (`let n`). - -This is still in the temporal dead zone as its declaration statement has not been reached and terminated. - - function go(n) { - // n here is defined! - console.log(n); // Object {a: [1,2,3]} - - for (let n of n.a) { // ReferenceError - console.log(n); - } - } - - go({a: [1, 2, 3]}); - -### Other situations - -When used inside a block, `let` limits the variable's scope to that block. Note the difference between `var`, whose scope is inside the function where it is declared. - - var a = 1; - var b = 2; - - if (a === 1) { - var a = 11; // the scope is global - let b = 22; // the scope is inside the if-block - - console.log(a); // 11 - console.log(b); // 22 - } - - console.log(a); // 11 - console.log(b); // 2 - -However, this combination of `var` and `let` declaration below is a [`SyntaxError`](../global_objects/syntaxerror) due to `var` being hoisted to the top of the block. This results in an implicit re-declaration of the variable. - - let x = 1; - - { - var x = 2; // SyntaxError for re-declaration - } - -## Specifications - -
    Specification
    ECMAScript Language Specification (ECMAScript) -
    - -#sec-let-and-const-declarations
    - -`let` - -49 - -48-49 - -Support outside of [strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode). - -41-49 - -[Strict mode](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Strict_mode) is required. - -14 - -12-14 - -In Edge 12 and 13, `let` within a `for` loop initializer does not create a separate variable for each loop iteration as defined by ES2015. Instead, it behaves as though the loop were wrapped in a scoping block with the `let` immediately before the loop. - -44 - -\["Prior to Firefox 44, `let` is only available to code blocks in HTML wrapped in a ` - -The same concept applies to promises. If we modify the above example a little bit, we get this: - - - - - -If we change this so that the ` - - - - - - -In the above example, the inner text of the ` - - - - - -## See also - -- [` - - -The same concept applies to promises. If we modify the above example a little bit, we get this: - - - - - -If we change this so that the ` - - - - - - -In the above example, the inner text of the ` - - - - - -## See also - -- [`"}' $listing - - # awk '{print "
  • "}; - - # {print " ",$1,"
  •  "}' \ $listing - - echo "" - - echo "" - - echo "" - - echo "" - - } - - cmd $listing --sort=extension >>$html - ---- - -### 26. Filter Corrupted Git Repo For Troublesome File: - -### Description: - -> _Notes:_ - -code: - - git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch assets/_index.html' HEAD - ---- - -### 27. OVERWRITE LOCAL CHANGES: - -### Description: - -Important: If you have any local changes, they will be lost. With or without — hard option, any local commits that haven't been pushed will be lost.\[\*\] If you have any files that are not tracked by Git (e.g. uploaded user content), these files will not be affected. - -> _Notes: First, run a fetch to update all origin/ refs to latest:_ - -code: - - git fetch --all - # Backup your current branch: - - git branch backup-master - # Then, you have two options: - - git reset --hard origin/master - # OR If you are on some other branch: - - git reset --hard origin/ - # Explanation: - # git fetch downloads the latest from remote without trying to merge or rebase anything. - - # Then the git reset resets the master branch to what you just fetched. The --hard option changes all the files in your working tree to match the files in origin/master - git fetch --all - git reset --hard origin/master - ---- - -### 28. Remove Submodules: - -### Description: To remove a submodule you need to: - -> _Notes:_ - -> _Delete the relevant section from the .gitmodules file. Stage the .gitmodules changes git add .gitmodules Delete the relevant section from .git/config. Run git rm — cached path_to_submodule (no trailing slash). Run rm -rf .git/modules/path_to_submodule (no trailing slash). Commit git commit -m "Removed submodule " Delete the now untracked submodule files rm -rf path_to_submodule_ - -code: - - git submodule deinit - ---- - -### 29. GET GISTS - -### Description: - -> _Notes:_ - -code: - - sudo apt install wget - - wget -q -O - https://api.github.com/users/bgoonz/gists | grep raw_url | awk -F\" '{print $4}' | xargs -n3 wget - - wget -q -O - https://api.github.com/users/amitness/gists | grep raw_url | awk -F\" '{print $4}' | xargs -n3 wget - - wget -q -O - https://api.github.com/users/drodsou/gists | grep raw_url | awk -F\" '{print $4}' | xargs -n1 wget - - wget -q -O - https://api.github.com/users/thomasmb/gists | grep raw_url | awk -F\" '{print $4}' | xargs -n1 wget - ---- - -### 30. Remove Remote OriginL - -### Description: - -> _Notes:_ - -code: - - git remote remove origin - ---- - -### 31. just clone .git folder: - -### Description: - -> _Notes:_ - -code: - - git clone --bare --branch=master --single-branch https://github.com/bgoonz/My-Web-Dev-Archive.git - ---- - -### 32. Undo recent pull request: - -### Description: - -> _Notes:_ - -code: - - git reset --hard master@{"10 minutes ago"} - ---- - -### 33. Lebab - -### Description: ES5 → ES6 - -> _Notes:_ - -code: - - # Safe: - - lebab --replace ./ --transform arrow - lebab --replace ./ --transform arrow-return - lebab --replace ./ --transform for-of - lebab --replace ./ --transform for-each - lebab --replace ./ --transform arg-rest - lebab --replace ./ --transform arg-spread - lebab --replace ./ --transform obj-method - lebab --replace ./ --transform obj-shorthand - lebab --replace ./ --transform multi-var - - # ALL: - - lebab --replace ./ --transform obj-method - lebab --replace ./ --transform class - lebab --replace ./ --transform arrow - lebab --replace ./ --transform let - lebab --replace ./ --transform arg-spread - lebab --replace ./ --transform arg-rest - lebab --replace ./ --transform for-each - lebab --replace ./ --transform for-of - lebab --replace ./ --transform commonjs - lebab --replace ./ --transform exponent - lebab --replace ./ --transform multi-var - lebab --replace ./ --transform template - lebab --replace ./ --transform default-param - lebab --replace ./ --transform destruct-param - lebab --replace ./ --transform includes - lebab --replace ./ --transform obj-method - lebab --replace ./ --transform class - lebab --replace ./ --transform arrow - lebab --replace ./ --transform arg-spread - lebab --replace ./ --transform arg-rest - lebab --replace ./ --transform for-each - lebab --replace ./ --transform for-of - lebab --replace ./ --transform commonjs - lebab --replace ./ --transform exponent - lebab --replace ./ --transform multi-var - lebab --replace ./ --transform template - lebab --replace ./ --transform default-param - lebab --replace ./ --transform destruct-param - lebab --replace ./ --transform includes - ---- - -### 34. Troubleshoot Ubuntu Input/Output Error - -### Description: Open Powershell as Administrator… - -> _Notes:_ - -code: - - wsl.exe --shutdown - - Get-Service LxssManager | Restart-Service - ---- - -### 35. Export Medium as Markdown - -### Description: - -> _Notes:_ - -code: - - npm i mediumexporter -g - - mediumexporter https://medium.com/codex/fundamental-data-structures-in-javascript-8f9f709c15b4 >ds.md - ---- - -### 36. Delete files in violation of a given size range (100MB for git) - -### Description: - -> _Notes:_ - -code: - - find . -size +75M -a -print -a -exec rm -f {} \; - - find . -size +98M -a -print -a -exec rm -f {} \; - ---- - -### 37. download all links of given file type - -### Description: - -> _Notes:_ - -code: - - wget -r -A.pdf https://overapi.com/git - ---- - -### 38. Kill all node processes - -### Description: - -> _Notes:_ - -code: - - killall -s KILL node - ---- - -### 39. Remove string from file names recursively - -### Description: In the example below I am using this command to remove the string "-master" from all file names in the working directory and all of it's sub directories. - -code: - - find -type f -exec sed -i 's///g' {} + - - find . -type f -exec rename 's/-master//g' {} + - -> _Notes: The same could be done for folder names by changing the_ -type f _flag (for file) to a_ -type d _flag (for directory)_ - - find -type d -exec sed -i 's///g' {} + - - find . -type d -exec rename 's/-master//g' {} + - ---- - -### 40. Remove spaces from file and folder names recursively - -### Description: replaces spaces in file and folder names with an `_` underscore - -> _Notes: need to run_ `sudo apt install rename` _to use this command_ - -code: - - find . -name "* *" -type d | rename 's/ /_/g' - find . -name "* *" -type f | rename 's/ /_/g' - -By Bryan Guner on [August 24, 2021](https://medium.com/p/3c7869fdae53). - -Canonical link - - August 31, 2021. -``` diff --git a/notes/articles/medium/markdown/Notes-I-Wish-I-Had-When-I-Started-Learning-Python.md b/notes/articles/medium/markdown/Notes-I-Wish-I-Had-When-I-Started-Learning-Python.md deleted file mode 100644 index 34567d0ee5..0000000000 --- a/notes/articles/medium/markdown/Notes-I-Wish-I-Had-When-I-Started-Learning-Python.md +++ /dev/null @@ -1,1400 +0,0 @@ -# Notes I Wish I Had When I Started Learning Python - -Plus resources for learning data structures and algorithms in python at the bottom of this article! - ---- - -### Notes I Wish I Had When I Started Learning Python - -#### Plus resources for learning data structures and algorithms in python at the bottom of this article! - -
    - -### Basics - -- **PEP8** : Python Enhancement Proposals, style-guide for Python. -- `print` is the equivalent of `console.log`. -- `#` is used to make comments in your code. - - - - def foo(): - """ - The foo function does many amazing things that you - should not question. Just accept that it exists and - use it with caution. - """ - secretThing() - -- Python has a built in help function that let's you see a description of the source code without having to navigate to it. - ---- - -### Numbers - -- Python has three types of numbers: -- **Integer** -- Positive and Negative Counting Numbers. -- No Decimal Point -- Created by a literal non-decimal pt number or with the `int()` constructor. - - - - print(3) # => 3 print(int(19)) # => 19 print(int()) # => 0 - -- Boolean is a subtype of integer in Python. -- **Floating Point Number** -- Decimal Numbers. - - - - print(2.24) # => 2.24 print(2.) # => 2.0 print(float()) # => 0.0 print(27e-5) # => 0.00027 - -#### **Complex Numbers** - -- Consist of a real part and imaginary part. -- The `i` is switched to a `j` in programming. - - - - print(7j) # => 7j print(5.1+7.7j)) # => 5.1+7.7j print(complex(3, 5)) # => 3+5j print(complex(17)) # => 17+0j print(complex()) # => 0j - -#### **Type Casting** : The process of converting one number to another. - - # Using Float - print(17) # => 17 - print(float(17)) # => 17.0 - - # Using Int - print(17.0) # => 17.0 - print(int(17.0)) # => 17 - - # Using Str - print(str(17.0) + ' and ' + str(17)) # => 17.0 and 17 - -- The arithmetic operators are the same between JS and Python, with two additions: -- "\*\*" : Double asterisk for exponent. -- "//" : Integer Division. -- There are no spaces between math operations in Python. -- Integer Division gives the other part of the number from Module; it is a way to do round down numbers replacing `Math.floor()` in JS. -- There are no `++` and `--` in Python, the only shorthand operators are: - -
    - ---- - -### Strings - -- Python uses both single and double quotes. -- You can escape strings like so `'Jodi asked, "What\'s up, Sam?"'` -- Multiline strings use triple quotes. - - - - print('''My instructions are very long so to make them - more readable in the code I am putting them on - more than one line. I can even include "quotes" - of any kind because they won't get confused with - the end of the string!''') - -- Use the `len()` function to get the length of a string. - - - - print(len("Spaghetti")) # => 9 - -- Python uses `zero-based indexing` -- Python allows negative indexing (thank god!) - - - - print("Spaghetti"[-1]) # => i print("Spaghetti"[-4]) # => e - -- Python let's you use ranges - - - - print("Spaghetti"[1:4]) # => pag print("Spaghetti"[4:-1]) # => hett print("Spaghetti"[4:4]) # => (empty string) - -- The end range is exclusive just like `slice` in JS. - - - - # Shortcut to get from the beginning of a string to a certain index. - print("Spaghetti"[:4]) # => Spag - print("Spaghetti"[:-1]) # => Spaghett - - # Shortcut to get from a certain index to the end of a string. - print("Spaghetti"[1:]) # => paghetti - print("Spaghetti"[-4:]) # => etti - -- The `index` string function is the equiv. of `indexOf()` in JS - - - - print("Spaghetti".index("h")) # => 4 - print("Spaghetti".index("t")) # => 6 - -- The `count` function finds out how many times a substring appears in a string. - - - - print("Spaghetti".count("h")) # => 1 - print("Spaghetti".count("t")) # => 2 - print("Spaghetti".count("s")) # => 0 - print('''We choose to go to the moon in this decade and do the other things, - not because they are easy, but because they are hard, because that goal will - serve to organize and measure the best of our energies and skills, because that - challenge is one that we are willing to accept, one we are unwilling to - postpone, and one which we intend to win, and the others, too. - '''.count('the ')) # => 4 - -- You can use `+` to concatenate strings, just like in JS. -- You can also use "\*" to repeat strings or multiply strings. -- Use the `format()` function to use placeholders in a string to input values later on. - - - - first_name = "Billy" - last_name = "Bob" - print('Your name is {0} {1}'.format(first_name, last_name)) # => Your name is Billy Bob - -- Shorthand way to use format function is: - `print(f'Your name is {first_name} {last_name}')` -- Some useful string methods. -- Note that in JS `join` is used on an Array, in Python it is used on String. - -
    - There are also many handy testing methods. - -
    - ---- - -### Variables and Expressions - -- **Duck-Typing** : Programming Style which avoids checking an object's type to figure out what it can do. -- Duck Typing is the fundamental approach of Python. -- Assignment of a value automatically declares. - - - - a = 7 - b = 'Marbles' - print(a) # => 7 - print(b) # => Marbles - -- You can chain variable assignments to give multiple var names the same value. -- Use with caution as this is highly unreadable - - - - count = max = min = 0 - print(count) # => 0 - print(max) # => 0 - print(min) # => 0 - -- The value and type of a variable can be re-assigned at any time. - - - - a = 17 - print(a) # => 17 - a = 'seventeen' - print(a) # => seventeen - -- `NaN` does not exist in Python, but you can 'create' it like so: - `print(float("nan"))` -- Python replaces `null` with `none`. -- `none` is an object and can be directly assigned to a variable. -- Using none is a convenient way to check to see why an action may not be operating correctly in your program. - ---- - -### Boolean Data Type - -- One of the biggest benefits of Python is that it reads more like English than JS does. - -
    # Logical AND - print(True and True) # => True - print(True and False) # => False - print(False and False) # => False - - # Logical OR - print(True or True) # => True - print(True or False) # => True - print(False or False) # => False - - # Logical NOT - print(not True) # => False - print(not False and True) # => True - print(not True or False) # => False - -- By default, Python considers an object to be true UNLESS it is one of the following: -- Constant `None` or `False` -- Zero of any numeric type. -- Empty Sequence or Collection. -- `True` and `False` must be capitalized - ---- - -### Comparison Operators - -- Python uses all the same equality operators as JS. -- In Python, equality operators are processed from left to right. -- Logical operators are processed in this order: - -1. **NOT** -2. **AND** -3. **OR** - -- Just like in JS, you can use `parentheses` to change the inherent order of operations. -- **Short Circuit** : Stopping a program when a `true` or `false` has been reached. - -
    - ---- - -### Identity vs Equality - - print (2 == '2') # => False - print (2 is '2') # => False - - print ("2" == '2') # => True - print ("2" is '2') # => True - - # There is a distinction between the number types. - print (2 == 2.0) # => True - print (2 is 2.0) # => False - -- In the Python community it is better to use `is` and `is not` over `==` or `!=` - ---- - -### If Statements - - if name == 'Monica': - print('Hi, Monica.') - - if name == 'Monica': - print('Hi, Monica.') - else: - print('Hello, stranger.') - - if name == 'Monica': - print('Hi, Monica.') - elif age < 12: - print('You are not Monica, kiddo.') - elif age > 2000: - print('Unlike you, Monica is not an undead, immortal vampire.') - elif age > 100: - print('You are not Monica, grannie.') - -- Remember the order of `elif` statements matter. - ---- - -### While Statements - - spam = 0 - while spam < 5: - print('Hello, world.') - spam = spam + 1 - -- `Break` statement also exists in Python. - - - - spam = 0 - while True: - print('Hello, world.') - spam = spam + 1 - if spam >= 5: - break - -- As are `continue` statements - - - - spam = 0 - while True: - print('Hello, world.') - spam = spam + 1 - if spam < 5: - continue - break - ---- - -### Try/Except Statements - -- Python equivalent to `try/catch` - - - - a = 321 - try: - print(len(a)) - except: - print('Silently handle error here') - - # Optionally include a correction to the issue - a = str(a) - print(len(a) - - a = '321' - try: - print(len(a)) - except: - print('Silently handle error here') - - # Optionally include a correction to the issue - a = str(a) - print(len(a)) - -- You can name an error to give the output more specificity. - - - - a = 100 - b = 0 - try: - c = a / b - except ZeroDivisionError: - c = None - print(c) - -- You can also use the `pass` commmand to by pass a certain error. - - - - a = 100 - b = 0 - try: - print(a / b) - except ZeroDivisionError: - pass - -- The `pass` method won't allow you to bypass every single error so you can chain an exception series like so: - - - - a = 100 - # b = "5" - try: - print(a / b) - except ZeroDivisionError: - pass - except (TypeError, NameError): - print("ERROR!") - -- You can use an `else` statement to end a chain of `except` statements. - - - - # tuple of file names - files = ('one.txt', 'two.txt', 'three.txt') - - # simple loop - for filename in files: - try: - # open the file in read mode - f = open(filename, 'r') - except OSError: - # handle the case where file does not exist or permission is denied - print('cannot open file', filename) - else: - # do stuff with the file object (f) - print(filename, 'opened successfully') - print('found', len(f.readlines()), 'lines') - f.close() - -- `finally` is used at the end to clean up all actions under any circumstance. - - - - def divide(x, y): - try: - result = x / y - except ZeroDivisionError: - print("Cannot divide by zero") - else: - print("Result is", result) - finally: - print("Finally...") - -- Using duck typing to check to see if some value is able to use a certain method. - - - - # Try a number - nothing will print out - a = 321 - if hasattr(a, '__len__'): - print(len(a)) - - # Try a string - the length will print out (4 in this case) - b = "5555" - if hasattr(b, '__len__'): - print(len(b)) - ---- - -### Pass - -- Pass Keyword is required to write the JS equivalent of : - - - - if (true) { - } - - while (true) {} - - if True: - pass - - while True: - pass - ---- - -### Functions - -- **Function** definition includes: -- The `def` keyword -- The name of the function -- A list of parameters enclosed in parentheses. -- A colon at the end of the line. -- One tab indentation for the code to run. - - - - def printCopyright(): - print("Copyright 2020. Me, myself and I. All rights reserved.") - -- You can use default parameters just like in JS - - - - def greeting(name, saying="Hello"): - print(saying, name) - - greeting("Monica") - # Hello Monica - - greeting("Barry", "Hey") - # Hey Barry - -- Keep in mind, default parameters must always come after regular parameters. - - - - # THIS IS BAD CODE AND WILL NOT RUN - def increment(delta=1, value): - return delta + value - -- You can specify arguments by name without destructuring in Python. - - - - def greeting(name, saying="Hello"): - print(saying, name) - - # name has no default value, so just provide the value - # saying has a default value, so use a keyword argument - greeting("Monica", saying="Hi") - -- The `lambda` keyword is used to create anonymous functions and are supposed to be `one-liners`. - -`toUpper = lambda s: s.upper()` - ---- - -### Notes - -### Formatted Strings - -- Remember that in Python `join()` is called on a string with an array/list passed in as the argument. - - - - shopping_list = ['bread','milk','eggs'] - print(','.join(shopping_list)) - -- Python has a very powerful formatting engine. -- `format()` is also applied directly to strings. - - - - # Comma Thousands Separator - print('{:,}'.format(1234567890)) - '1,234,567,890' - - # Date and Time - d = datetime.datetime(2020, 7, 4, 12, 15, 58) - print('{:%Y-%m-%d %H:%M:%S}'.format(d)) - '2020-07-04 12:15:58' - - # Percentage - points = 190 - total = 220 - print('Correct answers: {:.2%}'.format(points/total)) - Correct answers: 86.36% - - # Data Tables - width=8 - print(' decimal hex binary') - print('-'*27) - for num in range(1,16): - for base in 'dXb': - print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ') - print() - ---- - -### Getting Input from the Command Line - -- Python runs synchronously, all programs and processes will stop when listening for a user input. -- The `input` function shows a prompt to a user and waits for them to type 'ENTER'. - ---- - -### Scripts vs Programs - -- **Programming Script** : A set of code that runs in a linear fashion. -- The largest difference between scripts and programs is the level of complexity and purpose. Programs typically have many UI's. -- Python can be used to display html, css, and JS. -- We will be using Python as an API (Application Programming Interface) - ---- - -### Structured Data - -- **Sequence** : The most basic data structure in Python where the index determines the order. -- List -- Tuple -- Range - -**Collections** : Unordered data structures, hashable values. - -- Dictionaries -- Sets -- **Iterable** : Generic name for a sequence or collection; any object that can be iterated through. -- Can be mutable or immutable. - ---- - -### Built In Data Types - -- **Lists** are the python equivalent of arrays. - - - - empty_list = [] - departments = ['HR','Development','Sales','Finance','IT','Customer Support'] - - # You can instantiate - specials = list() - - # Test if a value is in a list. - print(1 in [1, 2, 3]) #> True - print(4 in [1, 2, 3]) #> False - -- **Tuples** : Very similar to lists, but they are `immutable` - - - - # Instantiated with parentheses - time_blocks = ('AM','PM') - - # Sometimes instantiated without - colors = 'red','blue','green' - numbers = 1, 2, 3 - - # Tuple() built in can be used to convert other data into a tuple - tuple('abc') # returns ('a', 'b', 'c') - tuple([1,2,3]) # returns (1, 2, 3) - -- Think of tuples as constant variables. -- **Ranges** : A list of numbers which can't be changed; often used with `for` loops. -- Declared using one to three parameters. - -1. **Start** : opt. default 0, first \# in sequence. -2. **Stop** : `required` next number past the last number in the sequence. -3. **Step** : opt. default 1, difference between each number in the sequence. - - - - range(5) # [0, 1, 2, 3, 4] - range(1,5) # [1, 2, 3, 4] - range(0, 25, 5) # [0, 5, 10, 15, 20] - range(0) # [ ] - - for let (i = 0; i < 5; i++) - for let (i = 1; i < 5; i++) - for let (i = 0; i < 25; i+=5) - for let(i = 0; i = 0; i++) - -- Keep in mind that `stop` is not included in the range. -- `Dictionaries` : Mappable collection where a hashable value is used as a key to ref. an object stored in the dictionary. -- Mutable. - - - - a = {'one':1, 'two':2, 'three':3} - b = dict(one=1, two=2, three=3) - c = dict([('two', 2), ('one', 1), ('three', 3)]) - -> _a, b, and c are all equal_ - -- Declared with curly braces of the built in `dict()` -- Benefit of dictionaries in Python is that it doesn't matter how it is defined, if the keys and values are the same the dictionaries are considered equal. -- Use the `in` operator to see if a key exists in a dictionary. - -#### **Sets** : Unordered collection of distinct objects; objects that **need** to be hashable. - -- Always be unique, duplicate items are auto dropped from the set. -- **Common Uses**: -- Removing Duplicates -- Membership Testing -- Mathematical Operators: Intersection, Union, Difference, Symmetric Difference. -- Standard Set is mutable, Python has a immutable version called `frozenset`. -- Sets created by putting comma seperated values inside braces: - - - - school_bag = {'book','paper','pencil','pencil','book','book','book','eraser'} - print(school_bag) - - # Also can use set constructor to automatically put it into a set. - letters = set('abracadabra') - print(letters) - ---- - -### Built-In Functions - -**Functions using iterables** - -- **filter(function, iterable)** : creates new iterable of the same type which includes each item for which the function returns true. -- **map(function, iterable)** : creates new iterable of the same type which includes the result of calling the function on every item of the iterable. -- **sorted(iterable, key=None, reverse=False)** : creates a new sorted list from the items in the iterable. -- Output is always a `list` -- `key`: opt function which coverts and item to a value to be compared. -- `reverse`: optional boolean. -- **enumerate(iterable, start=0)** : starts with a sequence and converts it to a series of tuples - - - - quarters = ['First', 'Second', 'Third', 'Fourth'] - print(enumerate(quarters)) - print(enumerate(quarters, start=1)) - - # (0, 'First'), (1, 'Second'), (2, 'Third'), (3, 'Fourth') - # (1, 'First'), (2, 'Second'), (3, 'Third'), (4, 'Fourth') - -- **zip(\*iterables)** : creates a zip object filled with tuples that combine 1 to 1 the items in each provided iterable. - -**Functions that analyze iterables** - -- **len(iterable)** : returns the count of the number of items. -- **max(\*args, key=None)** : returns the largest of two or more arguments. -- **max(iterable, key=None)** : returns the largest item in the iterable. -- `key` optional function which converts an item to a value to be compared. -- **min** works the same way as `max` -- **sum(iterable)** : used with a list of numbers to generate the total. -- There is a faster way to concatenate an array of strings into one string, so do not use sum for that. -- **any(iterable)** : returns True if any items in the iterable are true. -- **all(iterable)** : returns True is all items in the iterable are true. - -**Working with dictionaries** - -- **dir(dictionary)** : returns the list of keys in the dictionary. - -**Working with sets** - -- **Union** : The pipe | operator or `union(*sets)` function can be used to produce a new set which is a combination of all elements in the provided set. - - - - a = {1, 2, 3} - b = {2, 4, 6} - print(a | b) # => {1, 2, 3, 4, 6} - -- **Intersection** : The & operator ca be used to produce a new set of only the elements that appear in all sets. - - - - a = {1, 2, 3} - b = {2, 4, 6} - print(a & b) # => {2} - -- **Difference** : The — operator can be used to produce a new set of only the elements that appear in the first set and NOT the others. -- **Symmetric Difference** : The ^ operator can be used to produce a new set of only the elements that appear in exactly one set and not in both. - - - - a = {1, 2, 3} - b = {2, 4, 6} - print(a - b) # => {1, 3} - print(b - a) # => {4, 6} - print(a ^ b) # => {1, 3, 4, 6} - ---- - -### For Statements - -- In python, there is only one for loop. -- Always Includes: -- The `for` keyword -- A variable name -- The `in` keyword -- An iterable of some kid -- A colon -- On the next line, an indented block of code called the `for` clause. -- You can use `break` and `continue` statements inside for loops as well. -- You can use the range function as the iterable for the `for` loop. - - - - print('My name is') - for i in range(5): - print('Carlita Cinco (' + str(i) + ')') - - total = 0 - for num in range(101): - total += num - print(total) - -- Looping over a list in Python - - - - for c in ['a', 'b', 'c']: - print(c) - - lst = [0, 1, 2, 3] - for i in lst: - print(i) - -- Common technique is to use the len() on a pre-defined list with a for loop to iterate over the indices of the list. - - - - supplies = ['pens', 'staplers', 'flame-throwers', 'binders'] - for i in range(len(supplies)): - print('Index ' + str(i) + ' in supplies is: ' + supplies[i]) - -- You can loop and destructure at the same time. - - - - l = [[1, 2], [3, 4], [5, 6]] - for a, b in l: - print(a, ', ', b) - - # Prints 1, 2 - # Prints 3, 4 - # Prints 5, 6 - -- You can use `values()` and `keys()` to loop over dictionaries. - - - - spam = {'color': 'red', 'age': 42} - for v in spam.values(): - print(v) - - # Prints red - # Prints 42 - - for k in spam.keys(): - print(k) - - # Prints color - # Prints age - -- For loops can also iterate over both keys and values. - - - - # Getting tuples - for i in spam.items(): - print(i) - - # Prints ('color', 'red') - # Prints ('age', 42) - - # Destructuring to values - for k, v in spam.items(): - print('Key: ' + k + ' Value: ' + str(v)) - - # Prints Key: age Value: 42 - # Prints Key: color Value: red - -- Looping over string - - - - for c in "abcdefg": - print(c) - ---- - -### More On Functions - -- **Variable-length positional arguments** : (\*args) - - - - def add(a, b, *args): - total = a + b; - for n in args: - total += n - return total - - add(1, 2) # Returns 3 - - add(2, 3, 4, 5) # Returns 14 - -- **keyword arguments** : (\*kwargs) - - - - def print_names_and_countries(greeting, **kwargs): - for k, v in kwargs.items(): - print(greeting, k, "from", v) - - print_names_and_countries("Hi", - Monica="Sweden", - Charles="British Virgin Islands", - Carlo="Portugal") - # Prints - # Hi Monica from Sweden - # Hi Charles from British Virgin Islands - # Hi Carlo from Portugal - -- When you order arguments within a function or function call, the args need to occur in a particular order: - -1. formal positional args. -2. \*args -3. keyword args with default values -4. \*\*kwargs - - - - def example(arg_1, arg_2, *args, **kwargs): - pass - - def example2(arg_1, arg_2, *args, kw_1="shark", kw_2="blowfish", **kwargs): - pass - ---- - -### Importing in Python - -- Modules are similar to packages in Node.js -- Come in different types: Built-In, Third-Party, Custom. -- All loaded using `import` statements. - -**Terms** - -- **module** : Python code in a separate file. -- **package** : Path to a directory that contains modules. -- \***\*init**.py\*\* : Default file for a package. -- **submodule** : Another file in a module's folder. -- **function** : Function in a module. -- A module can be any file but it is usually created by placing a special file `__init__.py` into a folder. -- Try to avoid importing with wildcards in Python. -- Use multiple lines for clarity when importing. - - - - from urllib.request import ( - HTTPDefaultErrorHandler as ErrorHandler, - HTTPRedirectHandler as RedirectHandler, - Request, - pathname2url, - url2pathname, - urlopen, - ) - ---- - -### Watching Out for Python 2 - -- Python 3 removed `<>` and only uses `!=` -- `format()` was introduced with P3 -- All strings in P3 are unicode and encoded. -- `md5` was removed. -- `ConfigParser` was renamed to `configparser` -- `sets` were killed in favor of `set()` class. -- `print` was a statement in P2, but is a function in P3. - ---- - -### Classes In Python - -- Classes are a way of combining information and behavior. -- Classes are blueprints to make objects. - - - - class AngryBird { - constructor() { - this.x = 0; - this.y = 0; - } - } - - class AngryBird: - def __init__(self): - """ - Construct a new AngryBird by setting its position to (0, 0). - """ - self.x = 0 - self.y = 0 - -- Both JS and PY use the `class` keyword to declare classes. -- `constructor` == `__init__` -- `this` == `self` - - - - bird = AngryBird() - print(bird.x, bird.y) #> 0 0 - - class AngryBird: - def __init__(self): - """ - Construct a new AngryBird by setting its position to (0, 0). - """ - self.x = 0 - self.y = 0 - - def move_up_by(self, delta): - self.y += delta - -- Note how you do not need to define `self` it is already bound to the class. -- It is good practice to write a comment at the beginning of your class, describing the class. - -**Dunder Methods** - -- Double Underscore Methods, special built in functions that PY uses in certain ways. -- i.e. `__init__()` lets you make sure all relevant attributes are set to their proper values when an object is created from the class. -- The `self` keyword refers to the current object that you are working with. -- Method is a function that is part of a class. - - - - class AngryBird: - def __init__(self): - self.x = 0 - self.y = 0 - - def move_up_by(self, delta): - self.y += delta - - bird = AngryBird() - print(bird) - print(bird.y) - bird.move_up_by(5) - print(bird.y) - -- _Use one leading underscore only for non-public methods and instance variables_ - - - - class AngryBird: - def __init__(self, x=0, y=0): - """ - Construct a new AngryBird by setting its position to (0, 0). - """ - self._x = x - self._y = y - - def move_up_by(self, delta): - self._y += delta - - def get_x(self): - return self._x - - def get_y(self): - return self._y - -- _All instance variables should be considered non-public_ -- \***\*slots\*\*** : Dunder class variable used to reserve memory for the instance variables that you know will you will use. - - - - class AngryBird: - __slots__ = ['_x', '_y'] - - def __init__(self, x=0, y=0): - """ - Construct a new AngryBird by setting its position to (0, 0). - """ - self._x = x - self._y = y - - def move_up_by(self, delta): - self._y += delta - - def get_x(self): - return self._x - - def get_y(self): - return self._y - -- You can use `__repr__()` to override the behavior of printing out a class in a verbose manner. - - - - class AngryBird: - __slots__ = ['_x', '_y'] - - def __init__(self, x=0, y=0): - """ - Construct a new AngryBird by setting its position to (0, 0). - """ - self._x = x - self._y = y - - def move_up_by(self, delta): - self._y += delta - - def get_x(self): - return self._x - - def get_y(self): - return self._y - - def __repr__(self): - return f"" - ---- - -### Properties for Classes - -- Getters and Setters are used in object-oriented programming to add validation logic around getting and setting a value. - -**Getters** - - bird = AngryBird() - - print(bird.get_x(), bird.get_y()) - -- Getting the x and y values of our class can get very cumbersome. -- **Decorators** : Allow us to change the way methods get invoked. -- Always start with the @ symbol. -- Can be applied to methods, classes, and parameters. -- Built in decorator named `property` that you can apply to a method to make it readable. - - - - @property - def x(self): - return self._x - - @property - def y(self): - return self._y - - bird = AngryBird() - - print(bird.x, bird.y) - -**Setters** - - class AngryBird: - def __init__(self, x=0, y=0): - """ - Construct a new AngryBird by setting its position to (0, 0). - """ - self._x = x - self._y = y - - def move_up_by(self, delta): - self._y += delta - - @property - def x(self): - return self._x - - @x.setter - def x(self, value): - if value < 0: - value = 0 - self._x = value - - @property - def y(self): - return self._y - - @y.setter - def y(self, value): - if value < 0: - value = 0 - self._y = value - ---- - -### List Comprehensions - -- List comprehensions are the equivalent of wrapped up filter namp array methods while also allowing nested loops. -- `new_list = [expression for member in iterable]` -- **expression** : member itself, a call to a methd, or any other valid expression that returns a value. -- **member** : object or value in the list or iterable. -- **iterable** : iterable. - -`new_list = [expression for member in iterable (if conditional)]` - -- Adding a conditional into a list comprehension. - - - - sentence = 'Mary, Mary, quite contrary, how does your garden grow?' - def is_consonant(letter): - vowels = "aeiou" - return letter.isalpha() and letter.lower() not in vowels - - consonants = [i for i in sentence if is_consonant(i)] - - print(consonants) - # Prints ['M', 'r', 'y', 'M', 'r', 'y', 'q', 't', 'c', - # 'n', 't', 'r', 'r', 'y', 'h', 'w', 'd', 's', 'y', - # 'r', 'g', 'r', 'd', 'n', 'g', 'r', 'w'] - -**When to not use list comprehensions** - -- List comprehensions may make your code run more slowly or use more memory. -- You can use nest lists to create matrices. - - - - matrix = [[i for i in range(5)] for _ in range(6)] - - print(matrix) - # Prints - # [ - # [0, 1, 2, 3, 4], - # [0, 1, 2, 3, 4], - # [0, 1, 2, 3, 4], - # [0, 1, 2, 3, 4], - # [0, 1, 2, 3, 4], - # [0, 1, 2, 3, 4] - # ] - ---- - -### My Blog: - -Web-Dev-Hub -
    - -Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…master--bgoonz-blog.netlify.app
    - -### Python Data Structures & Algorithms Resources: - -- The Framework for Learning Algorithms and intense problem solving exercises -- Algs4: Recommended book for Learning Algorithms and Data Structures -- An analysis of Dynamic Programming -- Dynamic Programming Q&A — What is Optimal Substructure -- The Framework for Backtracking Algorithm -- Binary Search in Detail: I wrote a Poem -- The Sliding Window Technique -- Difference Between Process and Thread in Linux -- Some Good Online Practice Platforms -- Dynamic Programming in Details -- Dynamic Programming Q&A — What is Optimal Substructure -- Classic DP: Longest Common Subsequence -- Classic DP: Edit Distance -- Classic DP: Super Egg -- Classic DP: Super Egg (Advanced Solution) -- The Strategies of Subsequence Problem -- Classic DP: Game Problems -- Greedy: Interval Scheduling -- KMP Algorithm In Detail -- A solution to all Buy Time to Buy and Sell Stock Problems -- A solution to all House Robber Problems -- 4 Keys Keyboard -- Regular Expression -- Longest Increasing Subsequence -- The Framework for Learning Algorithms and intense problem solving exercises -- Algs4: Recommended book for Learning Algorithms and Data Structures -- Binary Heap and Priority Queue -- LRU Cache Strategy in Detail -- Collections of Binary Search Operations -- Special Data Structure: Monotonic Stack -- Special Data Structure: Monotonic Stack -- Design Twitter -- Reverse Part of Linked List via Recursion -- Queue Implement Stack/Stack implement Queue -- My Way to Learn Algorithm -- The Framework of Backtracking Algorithm -- Binary Search in Detail -- Backtracking Solve Subset/Permutation/Combination -- Diving into the technical parts of Double Pointers -- Sliding Window Technique -- The Core Concept of TwoSum Problems -- Common Bit Manipulations -- Breaking down a Complicated Problem: Implement a Calculator -- Pancake Sorting Algorithm -- Prefix Sum: Intro and Concept -- String Multiplication -- FloodFill Algorithm in Detail -- Interval Scheduling: Interval Merging -- Interval Scheduling: Intersections of Intervals -- Russian Doll Envelopes Problem -- A collection of counter-intuitive Probability Problems -- Shuffle Algorithm -- Recursion In Detail -- How to Implement LRU Cache -- How to Find Prime Number Efficiently -- How to Calculate Minimium Edit Distance -- How to use Binary Search -- How to efficiently solve Trapping Rain Water Problem -- How to Remove Duplicates From Sorted Array -- How to Find Longest Palindromic Substring -- How to Reverse Linked List in K Group -- How to Check the Validation of Parenthesis -- How to Find Missing Element -- How to Find Duplicates and Missing Elements -- How to Check Palindromic LinkedList -- How to Pick Elements From an Infinite Arbitrary Sequence -- How to Schedule Seats for Students -- Union-Find Algorithm in Detail -- Union-Find Application -- Problems that can be solved in one line -- Find Subsequence With Binary Search -- Difference Between Process and Thread in Linux -- You Must Know About Linux Shell -- You Must Know About Cookie and Session -- Cryptology Algorithm -- Some Good Online Practice Platforms - -### Algorithms: - -- 100 days of algorithms -- Algorithms — Solved algorithms and data structures problems in many languages. -- Algorithms by Jeff Erickson (Code) (HN) -- Top algos/DS to learn -- Some neat algorithms -- Mathematical Proof of Algorithm Correctness and Efficiency (2019) -- Algorithm Visualizer — Interactive online platform that visualizes algorithms from code. -- Algorithms for Optimization book -- Collaborative book on algorithms (Code) -- Algorithms in C by Robert Sedgewick -- Algorithm Design Manual -- MIT Introduction to Algorithms course (2011) -- How to implement an algorithm from a scientific paper (2012) -- Quadsort — Stable non-recursive merge sort named quadsort. -- System design algorithms — Algorithms you should know before system design. -- Algorithms Design book -- Think Complexity -- All Algorithms implemented in Rust -- Solutions to Introduction to Algorithms book (Code) -- Maze Algorithms (2011) (HN) -- Algorithmic Design Paradigms book (Code) -- Words and buttons Online Blog (Code) -- Algorithms animated -- Cache Oblivious Algorithms (2020) (HN) -- You could have invented fractional cascading (2012) -- Guide to learning algorithms through LeetCode (Code) (HN) -- How hard is unshuffling a string? -- Optimization Algorithms on Matrix Manifolds -- Problem Solving with Algorithms and Data Structures (HN) (PDF) -- Algorithms implemented in Python -- Algorithms implemented in JavaScript -- Algorithms & Data Structures in Java -- Wolfsort — Stable adaptive hybrid radix / merge sort. -- Evolutionary Computation Bestiary — Bestiary of evolutionary, swarm and other metaphor-based algorithms. -- Elements of Programming book — Decomposing programs into a system of algorithmic components. (Review) (HN) (Lobsters) -- Competitive Programming Algorithms -- CPP/C — C/C++ algorithms/DS problems. -- How to design an algorithm (2018) -- CSE 373 — Introduction to Algorithms, by Steven Skiena (2020) -- Computer Algorithms II course (2020) -- Improving Binary Search by Guessing (2019) -- The case for a learned sorting algorithm (2020) (HN) -- Elementary Algorithms — Introduces elementary algorithms and data structures. Includes side-by-side comparisons of purely functional realization and their imperative counterpart. -- Combinatorics Algorithms for Coding Interviews (2018) -- Algorithms written in different programming languages (Web) -- Solving the Sequence Alignment problem in Python (2020) -- The Sound of Sorting — Visualization and "Audibilization" of Sorting Algorithms. (Web) -- Miniselect: Practical and Generic Selection Algorithms (2020) -- The Slowest Quicksort (2019) -- Functional Algorithm Design (2020) -- Algorithms To Live By — Book Notes -- Numerical Algorithms (2015) -- Using approximate nearest neighbor search in real world applications (2020) -- In search of the fastest concurrent Union-Find algorithm (2019) -- Computer Science 521 Advanced Algorithm Design - -### Data Structures: - -- Data Structures and Algorithms implementation in Go -- Which algorithms/data structures should I "recognize" and know by name? -- Dictionary of Algorithms and Data Structures -- Phil's Data Structure Zoo -- The Periodic Table of Data Structures (HN) -- Data Structure Visualizations (HN) -- Data structures to name-drop when you want to sound smart in an interview -- On lists, cache, algorithms, and microarchitecture (2019) -- Topics in Advanced Data Structures (2019) (HN) -- CS166 Advanced DS Course (2019) -- Advanced Data Structures (2017) (HN) -- Write a hash table in C -- Python Data Structures and Algorithms -- HAMTs from Scratch (2018) -- JavaScript Data Structures and Algorithms -- Implementing a Key-Value Store series -- Open Data Structures — Provide a high-quality open content data structures textbook that is both mathematically rigorous and provides complete implementations. (Code) -- A new analysis of the false positive rate of a Bloom filter (2009) -- Ideal Hash Trees -- RRB-Trees: Efficient Immutable Vectors -- Some data structures and algorithms written in OCaml -- Let's Invent B(+)-Trees (HN) -- Anna — Low-latency, cloud-native KVS. -- Persistent data structures thanks to recursive type aliases (2019) -- Log-Structured Merge-Trees (2020) -- Bloom Filters for the Perplexed (2017) -- Understanding Bloom Filters (2020) -- Dense vs. Sparse Indexes (2020) -- Data Structures and Algorithms Problems -- Data Structures & Algorithms I Actually Used Working at Tech Companies (2020) (Lobsters) (HN) -- Let's implement a Bloom Filter (2020) (HN) -- Data Structures Part 1: Bulk Data (2019) (Lobsters) -- Data Structures Explained -- Introduction to Cache-Oblivious Data Structures (2018) -- The Daily Coding newsletter — Master JavaScript and Data Structures. -- Lectures Note for Data Structures and Algorithms (2019) -- Mechanically Deriving Binary Tree Iterators with Continuation Defunctionalization (2020) -- Segment Tree data structure -- Structure of a binary state tree (2020) -- Introductory data structures and algorithms -- Applying Textbook Data Structures for Real Life Wins (2020) (HN) -- Michael Scott — Nonblocking data structures lectures (2020) — Nonblocking concurrent data structures are an increasingly valuable tool for shared-memory parallel programming. -- Scal — High-performance multicore-scalable data structures and benchmarks. (Web) -- Hyperbolic embedding implementations -- Morphisms of Computational Constructs — Visual catalogue + story of morphisms displayed across computational structures. -- What is key-value store? (build-your-own-x) (2020) -- Lesser Known but Useful Data Structures -- Using Bloom filters to efficiently synchronize hash graphs (2020) -- Bloom Filters by Example (Code) -- Binary Decision Diagrams (HN) -- 3 Steps to Designing Better Data Structures (2020) -- Sparse Matrices (2019) (HN) -- Algorithms & Data Structures in C++ -- Fancy Tree Traversals (2019) -- The Robson Tree Traversal (2019) -- Data structures and program structures -- cdb — Fast, reliable, simple package for creating and reading constant databases. -- PGM-index — Learned indexes that match B-tree performance with 83x less space. (HN) (Code) -- Structural and pure attributes -- Cache-Tries: O(1) Concurrent Lock-Free Hash Tries (2018) - -By Bryan Guner on [August 24, 2021](https://medium.com/p/16ce4244be12). - -Canonical link - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Object-Methods.md b/notes/articles/medium/markdown/Object-Methods.md deleted file mode 100644 index 0356c1c6b5..0000000000 --- a/notes/articles/medium/markdown/Object-Methods.md +++ /dev/null @@ -1,177 +0,0 @@ -# Object Methods - -Objects store unordered key-value pairs. With Objects we can not rely on indices to access values.Meaning - we'll have to iterate through… - ---- - -### Object Methods - -#### Objects store _unordered_ `key`-`value` pairs. With Objects we can not rely on indices to access values.Meaning - we'll have to iterate through objects in new ways to access the keys and values within. - -
    A list of all of my articles to link to future posts -
    - -You should probably skip this one… seriously it's just for internal use! - -### Iterating Through Objects - -Objects store _unordered_ -`key`-`value` pairs. With Objects we can not rely on indices to access values. -Meaning - we'll have to iterate through objects in new ways to access the keys -and values within. - -This article will cover: - -1. Iterate through Object `keys` and `values` using a `for...in` loop -2. Use the `Object.keys` and the `Object.values` methods to iterate through an Object. - -### For In Loop - -We can use special syntax to iterate through each `key` of an object (in -arbitrary order). This is super useful for looping through **both** the keys and -values of an object. - -The syntax looks like this: - - // The current key is assigned to *variable* on each iteration. - for (let variable in object) { - statement; - } - -### ex.) - - let obj = { name: "Rose", cats: 2 }; - // The key we are accessing is assigned to the `currentKey` - // *variable* on each iteration. - for (let currentKey in obj) { - console.log(currentKey); - } - // prints out: - // name - // cats - -The example above prints all the keys found in `obj` to the screen. - -On each iteration of the loop, the `key` we are currently accessing is assigned to the`currentKey` variable. - -To access values in an object, we would throw some bracket notation -into the mix: - - let obj = { name: "Rose", cats: 2 }; - for (let key in obj) { - let value = obj[key]; - console.log(value); - } - // prints out: - // Rose - // 2 - -#### You can only use variable keys when using bracket notation (`obj[key]`)! - -> Like all variables, you can name the current key variable whatever you like - -> just be descriptive! Here is an example of using a descriptive name for a key -> variable: - - let employees = { - manager: "Angela", - sales: "Gracie", - service: "Paul" - }; - for (let title in employees) { - let person = employees[title]; - console.log(person); - } - // prints out: - // Angela - // Gracie - // Paul - -### What's a method? - -A **method** is essentially a function that _belongs to_ an object. - -That means that every _method is a function_, but **not** every function -is a method. - -- `myFunc` is a function -- `myObject.myFunc` is a _method_ of the object `myObject` -- `myObject["myFunc"]` is a _method_ of the object `myObject` - A method is just a key-value pair where the **key is the function name and the - value is the function definition**! Let's use what we learned earlier to teach - our dog some new tricks: - - - - let dog = { - name: "Fido" - }; - // defining a new key-value pair where the *function name* is the key - // the function itself is the value! - dog.bark = function() { - console.log("bark bark!"); - }; - // this is the same thing as above just using Bracket Notation - dog["speak"] = function(string) { - console.log("WOOF " + string + " WOOF!!!"); - }; - dog.bark(); // prints `bark bark!` - dog.speak("pizza"); // prints `WOOF pizza WOOF!!!` - -Additionally, we can give objects methods when we initialize them: - - let dog2 = { - name: "Rover", - bark: function() { - console.log("bork bork!"); - }, - speak: function(string) { - console.log("BORK " + string + " BORK!!!"); - } - }; - // Notice that in the object above, we still separate the key-value pairs with commas. - // `bark` and `speak` are just keys with functions as values. - dog2.bark(); // prints `bork bork!` - dog2.speak("burrito"); // prints `BORK burrito BORK!!!` - -To invoke, or call, a method we need to specify **which** object is calling that method. In the example above the `dog2` object had the `bark` method so to invoke `bark` we had to specify it was `dog2`'s method: `dog2.bark()`. - -### Useful Object Methods - -### Iterating through keys using `Object.keys` - -The `Object.keys` method accepts an object as the argument and returns an array of the _keys_ within that Object. - - > let dog = {name: "Fido", age: "2"} - undefined - > Object.keys(dog) - ['name', 'age'] - > let cup = {color: "Red", contents: "coffee", weight: 5} - undefined - > Object.keys(cup) - ['color', 'contents', 'weight'] - -The return value of `Object.keys` method is an array of keys - which is useful -for iterating! - -### Iterating through keys using `Object.values` - -The `Object.values` method accepts an object as the argument and returns an -array of the _values_ within that Object. - - > let dog = {name: "Fido", age: "2"} - undefined - > Object.values(dog) - ['Fido', '2'] - > let cup = {color: "Red", contents: "coffee", weight: 5} - undefined - > Object.keys(cup) - ['Red', 'coffee', 5] - -The return value of `Object.values` method is an array of values - which is -useful for iterating! - -By Bryan Guner on [June 3, 2021](https://medium.com/p/4066ed24b214). - -Canonical link - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Object-Oriented-Programming-in-JavaScript.md b/notes/articles/medium/markdown/Object-Oriented-Programming-in-JavaScript.md deleted file mode 100644 index b827ea5740..0000000000 --- a/notes/articles/medium/markdown/Object-Oriented-Programming-in-JavaScript.md +++ /dev/null @@ -1,646 +0,0 @@ -# Object Oriented Programming in JavaScript - -Object-Oriented Programming - ---- - -### Object Oriented Programming in JavaScript - -### Object-Oriented Programming - -
    ### Overview: - -#### `Encapsulation` - -- The mechanism that puts behavior and data together behind methods that hide the specific implementation of a class. - -#### How can a `CommonJS Module import functionality` from another module? - -- Through the use of the require function. - -#### How can an ES6 module import functionality from another module? - -- Through the use of the import-from syntax that looks like this: -- `import SymbolName from './relative-path.js';` - -#### How do `CommonJS Modules` allow other modules to access exported symbols? - -- Through the use of the module.exports property. - -#### How do `ES6 Modules export` functionality so other modules can use them? - -- Through the use of the export keyword. - -#### `Implementation inheritance` - -- The data and methods defined on a parent class are available on objects created from classes that inherit from those parent classes - -#### `Inheritance` - -- The mechanism that passes traits of a parent class to its descendants. - -#### `Prototypal inheritance` - -- A method of realizing implementation inheritance through process of finding missing properties on an object by delegating the resolution to a prototype object. - -#### `The constructor method` - -- The special method of a class that is called to initialize an object when code uses the new keyword to instantiate an object from that class. - -#### `The Dependency Inversion Principle` - -- Functionality that your class depends on should be provided as parameters to methods rather than using new in the class to create a new instance of a dependency. - -#### The `extends` keyword - -- The keyword in JavaScript that allows one class to inherit from another. - -#### `The Interface Segregation Principle` - -- Method names should be grouped together into granular collections called "interfaces" - -#### `The Law Of Demeter` - -- Don't use more than one dot (not counting the one after "this"). -- A method of an object can only invoke the methods (or use the properties) of the following kinds of objects: Methods on the object itself Any of the objects passed in as parameters to the method And object created in the method Any values stored in the instance variables of the object Any values stored in global variables - -#### `The Liskov Substitution Principle` - -- You can substitute child class objects for parent class objects and not cause errors. - -#### `The Open-Close Principle` - -- A class is open for extension and closed for modification. - -#### `The Single-Responsibility Principle` - -- Any one of the following: -- A class should do one thing and do it well. -- A class should have only one reason to change. -- Gather together the things that change for the same reasons. Separate those things that change for different reasons. - ---- - -### Background: - -### Constructor Functions - -Defining a constructor function _Example of an object using object initialization_ - - const fellowshipOfTheRing = { - title: "The Fellowship of the Ring", - series: "The Lord of the Rings", - author: "J.R.R. Tolkien", - }; - -- The above literal is a "Book" object type. -- `Object Type` is defined by it's attributes and behaviors. - -> `Behaviors` **are represented by methods.** - -- `Constructor Functions` : Handle the creation of an object - it's a factory for creating objects of a specific type. -- There are a few specific things to constructors worth noting: -- **_The name of the constructor function is capitalized_** -- The Function _does not explicitly return a value_ -- Within the body, the _this_ keyword references the newly created object - - - - function Book(title, series, author) { - this.title = title; - this.series = series; - this.author = author; - } - -### Invoking a constructor function - -- We can invoke a constructor function using the `new` keyword. - - - - function Book(title, series, author) { - this.title = title; - this.series = series; - this.author = author; - } - - const fellowshipOfTheRing = new Book( - "The Fellowship of the Ring", - "The Lord of the Rings", - "J.R.R. Tolkien" - ); - - console.log(fellowshipOfTheRing); // Book { title: 'The Fellowship of the Ring', ... } - -### _Four Things will happen when invoking a constructor function_ - -1. A new empty object is created {}; -2. The new obj's `prototype` is set to the object referenced by the constructors prototype property. -3. `This` is bound to the new object. -4. The new object is returned after the constructor function has completed. - -### Understanding New Object Instances - -- `Instance` : term to describe an objected created from a constructor function. -- Every instance created is a unique object and therefore not equal to each other. - -### Using the instanceof operator to check an object's type - - console.log(fellowshipOfTheRing instanceof Book); // true - -- By using the `instanceof` operator we can verify that an object was created from a certain object type. -- _The instanceOf operator works by checking to see if the prototype object of the left side of the operator is the same as the prototype object of the right side of the operator._ - -### Invoking a constructor function without the new keyword - -- If we invoke a constructor function without the `new` keyword, we may result in one of two unexpected outcomes: - -1. In non-strict mode, this will be bound to the global object instead. -2. In `strict` mode, this will become undefined. - -- You can enable strict mode by typing `"use strict"` at the top of your file. - -### Defining Sharable Methods - -- _Avoid the temptation to store an object method inside a constructor function, it is inefficient with computer memory usage b/c each object instance would have it's own method definition._ -- `Prototype` : An object that is delegated to when a reference to an object property or method can't be resolved. -- Every instance created by a constructor function shares the same prototype. -- `Object.setPrototypeOf()` and `Object.getPrototypeOf()` are just used to set a prototype of one object to another object; and also the verify a prototype. -- `proto` : aka "dunder proto" is a property used to gain easy access to an object's prototype - it is widely supported by browsers but is considered deprecated. - - - - function Book(title, series, author) { - this.title = title; - this.series = series; - this.author = author; - } - - // Any method defined on the `Book.prototype` property - // will be shared across all `Book` instances. - Book.prototype.getInformation = function () { - return `${this.title} by ${this.author}`; - }; - - const fellowshipOfTheRing = new Book( - "The Fellowship of the Ring", - "The Lord of the Rings", - "J.R.R. Tolkien" - ); - - console.log(fellowshipOfTheRing.getInformation()); - -- Every method we define on a constructor function's prototype property will be shared across all instances of that object type. - -The Problem with Arrow Functions - -- We cannot use arrow functions when defining methods on a constructor function's prototype property. -- Arrow functions don't include their own this binding; therefore it will not reference the current instance — always stick with the function () keyword. - ---- - -### Putting the Class in JavaScript Classes - -In ES2015, JS gained the `class` keyword - replacing the need to use only constructor functions & prototypes to mimic classes! - -- `class` : keyword that gives developers a formal way to create a class definition to specify an object type's attributes and behavior; also used to create objects of that specific type. - -Defining a ES2015 class - - class Book { - constructor(title, series, author) { - this.title = title; - this.series = series; - this.author = author; - } - } - -- Class names also begin only with capital letters. -- Although not required, class definitions can include a `class constructor function` - these are similar to regular constructors in that: -- They don't explicitly return a value. -- The this keyword references the newly created object instance. - -### Instantiating an instance of a class - -> We can also use the `new`. - -### Four things occur when instantiating an instance of a class: - -1. New empty object is created {}; -2. The new obj's prototype is set to the class prototype's property value. -3. `This` is bound to the new object. -4. After the constructor method has completed, the new obj is returned. - -- **Don't try to instatiate a class object without the new keyword.** - -#### Class Definitions are NOT hoisted - - test(); - - function test() { - console.log("This works!"); - } - -- In JS you can call a function before it's declared — this is known as `hoisting`. -- Class definitions are **NOT hoisted,** so just get in the habit of declaring them before you use them. - -Defining Methods - -- A class can contain two types of methods: -- `Instance Method` : Methods that are invoked on an instance of the class - useful for performing an action on a specific instance. -- Instance methods are also sometimes referred to as `prototype` methods because they are defined on a shared prototype object. -- `Static Method` : Methods that invoked directly on a class, not on an instance. -- `Important`: Invoking a static method on an instance will result in a runtime error. -- Prepending the `static` keyword at the beginning on the method name will make it static. - - - - class Book { - constructor(title, series, author) { - this.title = title; - this.series = series; - this.author = author; - } - - // Notice the use of a rest parameter (...books) - // to capture the passed parameters as an array of values. - static getTitles(...books) { - return books.map((book) => book.title); - } - - getInformation() { - return `${this.title} by ${this.author}`; - } - } - - const fellowshipOfTheRing = new Book( - "The Fellowship of the Ring", - "The Lord of the Rings", - "J.R.R. Tolkien" - ); - - const theTwoTowers = new Book( - "The Two Towers", - "The Lord of the Rings", - "J.R.R. Tolkien" - ); - - const bookTitles = Book.getTitles(fellowshipOfTheRing, theTwoTowers); - - console.log(bookTitles.join(", ")); // The Fellowship of the Ring, The Two Towers - -- If we go back to an example of how constructor functions also use static methods — we see that static methods are _defined directly on the constructor function_ — whereas instance methods need to be defined on the _prototype_ object. - - - - function Book(title, series, author) { - this.title = title; - this.series = series; - this.author = author; - } - - // Static methods are defined - // directly on the constructor function. - Book.getTitles = function (...books) { - return books.map((book) => book.title); - }; - - // Instance methods are defined - // on the constructor function's `prototype` property. - Book.prototype.getInformation = function () { - return `${this.title} by ${this.author}`; - }; - - const fellowshipOfTheRing = new Book( - "The Fellowship of the Ring", - "The Lord of the Rings", - "J.R.R. Tolkien" - ); - - const theTwoTowers = new Book( - "The Two Towers", - "The Lord of the Rings", - "J.R.R. Tolkien" - ); - - console.log(fellowshipOfTheRing.getInformation()); // The Fellowship of the Ring by J.R.R. Tolkien - - console.log(theTwoTowers.getInformation()); // The Two Towers by J.R.R. Tolkien - - // Call the static `Book.getTitles()` method - // to get an array of the book titles. - const bookTitles = Book.getTitles(fellowshipOfTheRing, theTwoTowers); - - console.log(bookTitles.join(", ")); // The Fellowship of the Ring, The Two Towers - -### Comparing Classes to Constructor Functions - -> _ES2015 Classes are essentially_ **_syntactic sugar_** _over traditional constructor functions and prototypes._ - ---- - -### Javascript Inheritance - -- `Child Class` : Class that is based upon another class and inherits properties and methods from that other class. -- `Parent Class` : Class that is being inherited downwards. -- `Inheritance` : The process of basing a class upon another class. - - - - class CatalogItem { - constructor(title, series) { - this.title = title; - this.series = series; - } - - getInformation() { - if (this.series) { - return `${this.title} (${this.series})`; - } else { - return this.title; - } - } - } - - class Book extends CatalogItem { - constructor(title, series, author) { - super(title, series); - this.author = author; - } - } - - class Movie extends CatalogItem { - constructor(title, series, director) { - super(title, series); - this.director = director; - } - } - - const theGrapesOfWrath = new Book( - "The Grapes of Wrath", - null, - "John Steinbeck" - ); - const aNewHope = new Movie( - "Episode 4: A New Hope", - "Star Wars", - "George Lucas" - ); - - console.log(theGrapesOfWrath.getInformation()); // The Grapes of Wrath - console.log(aNewHope.getInformation()); // Episode 4: A New Hope (Star Wars) - console.log(Catalogitem instanceof Function); // true - console.log(Book instanceof Function); // true - -- A `prototype chain` defines a series of prototype objects that are delegated to one by one, when a property or method can't be found on an instance object. - - - - console.log(theGrapesOfWrath.getInformation()); // The Grapes of Wrath - -- When the `getInformation()` method is invoked: -- JS looks for get() on the current object. -- If it isn't found, the method call is delegated to the object's prototype. -- It continues up the prototype chain until the method is found. - -Overriding a method in a parent class - -- `Method Overriding` : when a child class provides an implementation of a method that's already defined in a parent class. - - - - class Movie extends CatalogItem { - constructor(title, series, director) { - super(title, series); - this.director = director; - } - - getInformation() { - let result = super.getInformation(); - - if (this.director) { - result += ` [directed by ${this.director}]`; - } - - return result; - } - } - -- We can simply declare our own method of the same name in our child class to override our parent's version of `getInformation()` - ---- - -### JavaScript Modules - -Introducing Node.js modules - -- In Node.js, each JS file in a project defines a `module`. -- Module's contents are private by default. -- `Local Modules` : Modules defined within your project. -- `Core Modules` : Native modules contained within Node.js that you can use to perform tasks or to add functionality to your application. -- `CommonJS` : A legacy module system. -- `ES Modules` : Newer module sysem that will eventually replace CommonJS. -- `Entry Point` : JS File that is passed to Node for access to the entire application. - -### Syntax for exporting modules: - - module.exports.Book = Book; module.exports.Movie = Movie; - - module.exports = { Book, Movie, }; - -#### Syntax for importing modules: - - const classes = require("./classes"); - - const { Book, Movie } = require("./classes"); - -#### Using Single Item Modules - -- Following the convention of a single exported item per module helps to keep modules focused and less likely to become bloted with too much code. - -#### Understanding Module Loading - -- When loading a module, Node will examine the identifier passed to the require() function to determine if our module is local, core, or third-party: -- `Local Module`: identifier starts with ./ ../ or / -- `Node.js Core`: identifier matches name -- `Third-Party`: identifier matches a module in the node modules folder (installed package) - ---- - -### `Encapsulation` - -- Puts the behavior and data together behind methods that hide the specific implementation so that code that uses it doesn't need to worry about the details of it. - -### `Inheritance` - -- `Implementation Inheritance`** :** Means that data and methods defined on a parent class are available on objects created from classes that inherit from those parent classes. -- `Prototypal Inheritance` : Means that JS uses prototype objects to make its `implementation inheritance` actually work. -- Parent Class === Prototype === Super Class === Base Class -- Inheritance === Subtyping - - - - class MyClass {} - - // is the same as - class MyClass extends Object {} - -- **When you declare a class with no explicit parent class, JS will make it a child of Object.** - - - - class Charity {} - - class Business { - toString() { - return "Give us your money."; - } - } - - class Restaurant extends Business { - toString() { - return "Eat at Joe's!"; - } - } - - class AutoRepairShop extends Business {} - - class Retail extends Business { - toString() { - return "Buy some stuff!"; - } - } - - class ClothingStore extends Retail {} - - class PhoneStore extends Retail { - toString() { - return "Upgrade your perfectly good phone, now!"; - } - } - - console.log(new PhoneStore().toString()); // 'Upgrade your perfectly good phone, now!' - console.log(new ClothingStore().toString()); // 'Buy some stuff!'; - console.log(new Restaurant().toString()); // 'Eat at Joe\'s!' - console.log(new AutoRepairShop().toString()); // 'Give us your money.' - console.log(new Charity().toString()); // [object object] - -#### The nuts and bolts of prototypal inheritance - -
    - When JavaScript uses a property (or method) from a prototype that it found through prototypal inheritance, then the this property points to the original object on which the first call was made. - - - - class Parent { - constructor() { - this.name = "PARENT"; - } - toString() { - return `My name is ${this.name}`; - } - } - - class Child extends Parent { - constructor() { - super(); - this.name = "CHILD"; - } - } - - const parent = new Parent(); - console.log(parent.toString()); // my name is Parent - - const child = new Child(); - console.log(child.toString()); // my name is Child - -### Polymorphism - -- The ability to treat an object as if it were an instance of one of its parent classes. - ---- - -### The SOLID Principles Explained - -SOLID is an anagram for: - -- `The Single-Responsibility Principle` -- `The Open-Close Principle` -- `The Liskov Substitution Principle` -- `The Interface Segregation Principle` -- `The Dependency Inversion Principle` - -### `Single-Responsibility Principle` - -> _A class should do one thing and do it well_ - -- This principle is about limiting the impact of change. - -### `The Liskov Substitution Principle:` - -_Subtype Requirement: Let ϕ(x) be a property provable about objects x of type T. Then ϕ(y) should be true for objects y of type S where S is a subtype of T._ - -> _You can substitute child class objects for parent class objects and not cause errors._ - -`The Other Three` - -- The remaining three principles are important for languages that have `static typing` - which means a variable can have only one kind of thing in it. -- `Open-Close Principle` -- A class is open for extension and closed for modification. -- Creating new functionality can happen in child classes, and not the original class. -- `Interface Segregation Principle` -- Method names should be grouped together into granular collections called "interfaces". -- `Dependency Inversion Principle` -- Functionality that your class depends on should be provided as parameters to methods rather than using new in the class to create a new instance. - -### Controlling Coupling with The Law of Demeter - -- `Coupling` : The degree of interdependence between two or more classes. -- The fewer the connections between classes, the less chance there is for the _ripple effect_. -- Here is the formal definition: -- A method of an object can only invoke the methods (or use the properties) of the following kind of objects: -- Methods on the object itself. -- Any of the objects passed in as parameters to the method. -- Any object created in the method. -- Any values stores in the instance variables of the object. -- Any values stored in global variables. -- Law of Demeter is more so of a guideline than a law. -- Easiest way to implement it is to _not us more than one dot_ -- You cannot cheat by separating extra calls onto different lines. - -### When to ignore the Law of Demeter - -- When you work with objects that come from code that you didn't create — you will often have to break the LoD. - - - - document - .getElementById("that-link") - .addEventListener("click", (e) => e.preventDefault()); - -- This breaks the law but there is way about it because your code needs to know about both elements and you have to use the API provided by the DOM. -- UI's will break LoD because they are not object-oriented programs. - -### If you found this guide helpful feel free to checkout my GitHub/gists where I host similar content: - -bgoonz's gists -
    - -Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…gist.github.com
    - -bgoonz — Overview -
    - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
    - -### Or Checkout my personal Resource Site: - -Web-Dev-Resource-Hub -
    - -Edit descriptionweb-dev-resource-hub.netlify.app
    - -By Bryan Guner on [March 14, 2021](https://medium.com/p/d45007d06333). - -Canonical link - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Object-Oriented-Programming-in.md b/notes/articles/medium/markdown/Object-Oriented-Programming-in.md deleted file mode 100644 index 3d32dcc69d..0000000000 --- a/notes/articles/medium/markdown/Object-Oriented-Programming-in.md +++ /dev/null @@ -1,646 +0,0 @@ -# Object Oriented Programming in JavaScript - -Object-Oriented Programming - ---- - -### Object Oriented Programming in JavaScript - -### Object-Oriented Programming - -
    ### Overview: - -#### `Encapsulation` - -- The mechanism that puts behavior and data together behind methods that hide the specific implementation of a class. - -#### How can a `CommonJS Module import functionality` from another module? - -- Through the use of the require function. - -#### How can an ES6 module import functionality from another module? - -- Through the use of the import-from syntax that looks like this: -- `import SymbolName from './relative-path.js';` - -#### How do `CommonJS Modules` allow other modules to access exported symbols? - -- Through the use of the module.exports property. - -#### How do `ES6 Modules export` functionality so other modules can use them? - -- Through the use of the export keyword. - -#### `Implementation inheritance` - -- The data and methods defined on a parent class are available on objects created from classes that inherit from those parent classes - -#### `Inheritance` - -- The mechanism that passes traits of a parent class to its descendants. - -#### `Prototypal inheritance` - -- A method of realizing implementation inheritance through process of finding missing properties on an object by delegating the resolution to a prototype object. - -#### `The constructor method` - -- The special method of a class that is called to initialize an object when code uses the new keyword to instantiate an object from that class. - -#### `The Dependency Inversion Principle` - -- Functionality that your class depends on should be provided as parameters to methods rather than using new in the class to create a new instance of a dependency. - -#### The `extends` keyword - -- The keyword in JavaScript that allows one class to inherit from another. - -#### `The Interface Segregation Principle` - -- Method names should be grouped together into granular collections called "interfaces" - -#### `The Law Of Demeter` - -- Don't use more than one dot (not counting the one after "this"). -- A method of an object can only invoke the methods (or use the properties) of the following kinds of objects: Methods on the object itself Any of the objects passed in as parameters to the method And object created in the method Any values stored in the instance variables of the object Any values stored in global variables - -#### `The Liskov Substitution Principle` - -- You can substitute child class objects for parent class objects and not cause errors. - -#### `The Open-Close Principle` - -- A class is open for extension and closed for modification. - -#### `The Single-Responsibility Principle` - -- Any one of the following: -- A class should do one thing and do it well. -- A class should have only one reason to change. -- Gather together the things that change for the same reasons. Separate those things that change for different reasons. - ---- - -### Background: - -### Constructor Functions - -Defining a constructor function _Example of an object using object initialization_ - - const fellowshipOfTheRing = { - title: "The Fellowship of the Ring", - series: "The Lord of the Rings", - author: "J.R.R. Tolkien", - }; - -- The above literal is a "Book" object type. -- `Object Type` is defined by it's attributes and behaviors. - -> `Behaviors` **are represented by methods.** - -- `Constructor Functions` : Handle the creation of an object - it's a factory for creating objects of a specific type. -- There are a few specific things to constructors worth noting: -- **_The name of the constructor function is capitalized_** -- The Function _does not explicitly return a value_ -- Within the body, the _this_ keyword references the newly created object - - - - function Book(title, series, author) { - this.title = title; - this.series = series; - this.author = author; - } - -### Invoking a constructor function - -- We can invoke a constructor function using the `new` keyword. - - - - function Book(title, series, author) { - this.title = title; - this.series = series; - this.author = author; - } - - const fellowshipOfTheRing = new Book( - "The Fellowship of the Ring", - "The Lord of the Rings", - "J.R.R. Tolkien" - ); - - console.log(fellowshipOfTheRing); // Book { title: 'The Fellowship of the Ring', ... } - -### _Four Things will happen when invoking a constructor function_ - -1. A new empty object is created {}; -2. The new obj's `prototype` is set to the object referenced by the constructors prototype property. -3. `This` is bound to the new object. -4. The new object is returned after the constructor function has completed. - -### Understanding New Object Instances - -- `Instance` : term to describe an objected created from a constructor function. -- Every instance created is a unique object and therefore not equal to each other. - -### Using the instanceof operator to check an object's type - - console.log(fellowshipOfTheRing instanceof Book); // true - -- By using the `instanceof` operator we can verify that an object was created from a certain object type. -- _The instanceOf operator works by checking to see if the prototype object of the left side of the operator is the same as the prototype object of the right side of the operator._ - -### Invoking a constructor function without the new keyword - -- If we invoke a constructor function without the `new` keyword, we may result in one of two unexpected outcomes: - -1. In non-strict mode, this will be bound to the global object instead. -2. In `strict` mode, this will become undefined. - -- You can enable strict mode by typing `"use strict"` at the top of your file. - -### Defining Sharable Methods - -- _Avoid the temptation to store an object method inside a constructor function, it is inefficient with computer memory usage b/c each object instance would have it's own method definition._ -- `Prototype` : An object that is delegated to when a reference to an object property or method can't be resolved. -- Every instance created by a constructor function shares the same prototype. -- `Object.setPrototypeOf()` and `Object.getPrototypeOf()` are just used to set a prototype of one object to another object; and also the verify a prototype. -- `proto` : aka "dunder proto" is a property used to gain easy access to an object's prototype - it is widely supported by browsers but is considered deprecated. - - - - function Book(title, series, author) { - this.title = title; - this.series = series; - this.author = author; - } - - // Any method defined on the `Book.prototype` property - // will be shared across all `Book` instances. - Book.prototype.getInformation = function () { - return `${this.title} by ${this.author}`; - }; - - const fellowshipOfTheRing = new Book( - "The Fellowship of the Ring", - "The Lord of the Rings", - "J.R.R. Tolkien" - ); - - console.log(fellowshipOfTheRing.getInformation()); - -- Every method we define on a constructor function's prototype property will be shared across all instances of that object type. - -The Problem with Arrow Functions - -- We cannot use arrow functions when defining methods on a constructor function's prototype property. -- Arrow functions don't include their own this binding; therefore it will not reference the current instance — always stick with the function () keyword. - ---- - -### Putting the Class in JavaScript Classes - -In ES2015, JS gained the `class` keyword - replacing the need to use only constructor functions & prototypes to mimic classes! - -- `class` : keyword that gives developers a formal way to create a class definition to specify an object type's attributes and behavior; also used to create objects of that specific type. - -Defining a ES2015 class - - class Book { - constructor(title, series, author) { - this.title = title; - this.series = series; - this.author = author; - } - } - -- Class names also begin only with capital letters. -- Although not required, class definitions can include a `class constructor function` - these are similar to regular constructors in that: -- They don't explicitly return a value. -- The this keyword references the newly created object instance. - -### Instantiating an instance of a class - -> We can also use the `new`. - -### Four things occur when instantiating an instance of a class: - -1. New empty object is created {}; -2. The new obj's prototype is set to the class prototype's property value. -3. `This` is bound to the new object. -4. After the constructor method has completed, the new obj is returned. - -- **Don't try to instatiate a class object without the new keyword.** - -#### Class Definitions are NOT hoisted - - test(); - - function test() { - console.log("This works!"); - } - -- In JS you can call a function before it's declared — this is known as `hoisting`. -- Class definitions are **NOT hoisted,** so just get in the habit of declaring them before you use them. - -Defining Methods - -- A class can contain two types of methods: -- `Instance Method` : Methods that are invoked on an instance of the class - useful for performing an action on a specific instance. -- Instance methods are also sometimes referred to as `prototype` methods because they are defined on a shared prototype object. -- `Static Method` : Methods that invoked directly on a class, not on an instance. -- `Important`: Invoking a static method on an instance will result in a runtime error. -- Prepending the `static` keyword at the beginning on the method name will make it static. - - - - class Book { - constructor(title, series, author) { - this.title = title; - this.series = series; - this.author = author; - } - - // Notice the use of a rest parameter (...books) - // to capture the passed parameters as an array of values. - static getTitles(...books) { - return books.map((book) => book.title); - } - - getInformation() { - return `${this.title} by ${this.author}`; - } - } - - const fellowshipOfTheRing = new Book( - "The Fellowship of the Ring", - "The Lord of the Rings", - "J.R.R. Tolkien" - ); - - const theTwoTowers = new Book( - "The Two Towers", - "The Lord of the Rings", - "J.R.R. Tolkien" - ); - - const bookTitles = Book.getTitles(fellowshipOfTheRing, theTwoTowers); - - console.log(bookTitles.join(", ")); // The Fellowship of the Ring, The Two Towers - -- If we go back to an example of how constructor functions also use static methods — we see that static methods are _defined directly on the constructor function_ — whereas instance methods need to be defined on the _prototype_ object. - - - - function Book(title, series, author) { - this.title = title; - this.series = series; - this.author = author; - } - - // Static methods are defined - // directly on the constructor function. - Book.getTitles = function (...books) { - return books.map((book) => book.title); - }; - - // Instance methods are defined - // on the constructor function's `prototype` property. - Book.prototype.getInformation = function () { - return `${this.title} by ${this.author}`; - }; - - const fellowshipOfTheRing = new Book( - "The Fellowship of the Ring", - "The Lord of the Rings", - "J.R.R. Tolkien" - ); - - const theTwoTowers = new Book( - "The Two Towers", - "The Lord of the Rings", - "J.R.R. Tolkien" - ); - - console.log(fellowshipOfTheRing.getInformation()); // The Fellowship of the Ring by J.R.R. Tolkien - - console.log(theTwoTowers.getInformation()); // The Two Towers by J.R.R. Tolkien - - // Call the static `Book.getTitles()` method - // to get an array of the book titles. - const bookTitles = Book.getTitles(fellowshipOfTheRing, theTwoTowers); - - console.log(bookTitles.join(", ")); // The Fellowship of the Ring, The Two Towers - -### Comparing Classes to Constructor Functions - -> _ES2015 Classes are essentially_ **_syntactic sugar_** _over traditional constructor functions and prototypes._ - ---- - -### Javascript Inheritance - -- `Child Class` : Class that is based upon another class and inherits properties and methods from that other class. -- `Parent Class` : Class that is being inherited downwards. -- `Inheritance` : The process of basing a class upon another class. - - - - class CatalogItem { - constructor(title, series) { - this.title = title; - this.series = series; - } - - getInformation() { - if (this.series) { - return `${this.title} (${this.series})`; - } else { - return this.title; - } - } - } - - class Book extends CatalogItem { - constructor(title, series, author) { - super(title, series); - this.author = author; - } - } - - class Movie extends CatalogItem { - constructor(title, series, director) { - super(title, series); - this.director = director; - } - } - - const theGrapesOfWrath = new Book( - "The Grapes of Wrath", - null, - "John Steinbeck" - ); - const aNewHope = new Movie( - "Episode 4: A New Hope", - "Star Wars", - "George Lucas" - ); - - console.log(theGrapesOfWrath.getInformation()); // The Grapes of Wrath - console.log(aNewHope.getInformation()); // Episode 4: A New Hope (Star Wars) - console.log(Catalogitem instanceof Function); // true - console.log(Book instanceof Function); // true - -- A `prototype chain` defines a series of prototype objects that are delegated to one by one, when a property or method can't be found on an instance object. - - - - console.log(theGrapesOfWrath.getInformation()); // The Grapes of Wrath - -- When the `getInformation()` method is invoked: -- JS looks for get() on the current object. -- If it isn't found, the method call is delegated to the object's prototype. -- It continues up the prototype chain until the method is found. - -Overriding a method in a parent class - -- `Method Overriding` : when a child class provides an implementation of a method that's already defined in a parent class. - - - - class Movie extends CatalogItem { - constructor(title, series, director) { - super(title, series); - this.director = director; - } - - getInformation() { - let result = super.getInformation(); - - if (this.director) { - result += ` [directed by ${this.director}]`; - } - - return result; - } - } - -- We can simply declare our own method of the same name in our child class to override our parent's version of `getInformation()` - ---- - -### JavaScript Modules - -Introducing Node.js modules - -- In Node.js, each JS file in a project defines a `module`. -- Module's contents are private by default. -- `Local Modules` : Modules defined within your project. -- `Core Modules` : Native modules contained within Node.js that you can use to perform tasks or to add functionality to your application. -- `CommonJS` : A legacy module system. -- `ES Modules` : Newer module sysem that will eventually replace CommonJS. -- `Entry Point` : JS File that is passed to Node for access to the entire application. - -### Syntax for exporting modules: - - module.exports.Book = Book; module.exports.Movie = Movie; - - module.exports = { Book, Movie, }; - -#### Syntax for importing modules: - - const classes = require("./classes"); - - const { Book, Movie } = require("./classes"); - -#### Using Single Item Modules - -- Following the convention of a single exported item per module helps to keep modules focused and less likely to become bloted with too much code. - -#### Understanding Module Loading - -- When loading a module, Node will examine the identifier passed to the require() function to determine if our module is local, core, or third-party: -- `Local Module`: identifier starts with ./ ../ or / -- `Node.js Core`: identifier matches name -- `Third-Party`: identifier matches a module in the node modules folder (installed package) - ---- - -### `Encapsulation` - -- Puts the behavior and data together behind methods that hide the specific implementation so that code that uses it doesn't need to worry about the details of it. - -### `Inheritance` - -- `Implementation Inheritance`** :** Means that data and methods defined on a parent class are available on objects created from classes that inherit from those parent classes. -- `Prototypal Inheritance` : Means that JS uses prototype objects to make its `implementation inheritance` actually work. -- Parent Class === Prototype === Super Class === Base Class -- Inheritance === Subtyping - - - - class MyClass {} - - // is the same as - class MyClass extends Object {} - -- **When you declare a class with no explicit parent class, JS will make it a child of Object.** - - - - class Charity {} - - class Business { - toString() { - return "Give us your money."; - } - } - - class Restaurant extends Business { - toString() { - return "Eat at Joe's!"; - } - } - - class AutoRepairShop extends Business {} - - class Retail extends Business { - toString() { - return "Buy some stuff!"; - } - } - - class ClothingStore extends Retail {} - - class PhoneStore extends Retail { - toString() { - return "Upgrade your perfectly good phone, now!"; - } - } - - console.log(new PhoneStore().toString()); // 'Upgrade your perfectly good phone, now!' - console.log(new ClothingStore().toString()); // 'Buy some stuff!'; - console.log(new Restaurant().toString()); // 'Eat at Joe\'s!' - console.log(new AutoRepairShop().toString()); // 'Give us your money.' - console.log(new Charity().toString()); // [object object] - -#### The nuts and bolts of prototypal inheritance - -
    - When JavaScript uses a property (or method) from a prototype that it found through prototypal inheritance, then the this property points to the original object on which the first call was made. - - - - class Parent { - constructor() { - this.name = "PARENT"; - } - toString() { - return `My name is ${this.name}`; - } - } - - class Child extends Parent { - constructor() { - super(); - this.name = "CHILD"; - } - } - - const parent = new Parent(); - console.log(parent.toString()); // my name is Parent - - const child = new Child(); - console.log(child.toString()); // my name is Child - -### Polymorphism - -- The ability to treat an object as if it were an instance of one of its parent classes. - ---- - -### The SOLID Principles Explained - -SOLID is an anagram for: - -- `The Single-Responsibility Principle` -- `The Open-Close Principle` -- `The Liskov Substitution Principle` -- `The Interface Segregation Principle` -- `The Dependency Inversion Principle` - -### `Single-Responsibility Principle` - -> _A class should do one thing and do it well_ - -- This principle is about limiting the impact of change. - -### `The Liskov Substitution Principle:` - -_Subtype Requirement: Let ϕ(x) be a property provable about objects x of type T. Then ϕ(y) should be true for objects y of type S where S is a subtype of T._ - -> _You can substitute child class objects for parent class objects and not cause errors._ - -`The Other Three` - -- The remaining three principles are important for languages that have `static typing` - which means a variable can have only one kind of thing in it. -- `Open-Close Principle` -- A class is open for extension and closed for modification. -- Creating new functionality can happen in child classes, and not the original class. -- `Interface Segregation Principle` -- Method names should be grouped together into granular collections called "interfaces". -- `Dependency Inversion Principle` -- Functionality that your class depends on should be provided as parameters to methods rather than using new in the class to create a new instance. - -### Controlling Coupling with The Law of Demeter - -- `Coupling` : The degree of interdependence between two or more classes. -- The fewer the connections between classes, the less chance there is for the _ripple effect_. -- Here is the formal definition: -- A method of an object can only invoke the methods (or use the properties) of the following kind of objects: -- Methods on the object itself. -- Any of the objects passed in as parameters to the method. -- Any object created in the method. -- Any values stores in the instance variables of the object. -- Any values stored in global variables. -- Law of Demeter is more so of a guideline than a law. -- Easiest way to implement it is to _not us more than one dot_ -- You cannot cheat by separating extra calls onto different lines. - -### When to ignore the Law of Demeter - -- When you work with objects that come from code that you didn't create — you will often have to break the LoD. - - - - document - .getElementById("that-link") - .addEventListener("click", (e) => e.preventDefault()); - -- This breaks the law but there is way about it because your code needs to know about both elements and you have to use the API provided by the DOM. -- UI's will break LoD because they are not object-oriented programs. - -### If you found this guide helpful feel free to checkout my GitHub/gists where I host similar content: - -bgoonz's gists -
    - -Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…gist.github.com
    - -bgoonz — Overview -
    - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
    - -### Or Checkout my personal Resource Site: - -Web-Dev-Resource-Hub -
    - -Edit descriptionweb-dev-resource-hub.netlify.app
    - -By Bryan Guner on [March 14, 2021](https://medium.com/p/d45007d06333). - -Canonical link - -August 6, 2021. diff --git a/notes/articles/medium/markdown/Object.md b/notes/articles/medium/markdown/Object.md deleted file mode 100644 index 8cb7bab8b8..0000000000 --- a/notes/articles/medium/markdown/Object.md +++ /dev/null @@ -1,177 +0,0 @@ -# Object Methods - -Objects store unordered key-value pairs. With Objects we can not rely on indices to access values.Meaning - we'll have to iterate through… - ---- - -### Object Methods - -#### Objects store _unordered_ `key`-`value` pairs. With Objects we can not rely on indices to access values.Meaning - we'll have to iterate through objects in new ways to access the keys and values within. - -
    A list of all of my articles to link to future posts -
    - -You should probably skip this one… seriously it's just for internal use! - -### Iterating Through Objects - -Objects store _unordered_ -`key`-`value` pairs. With Objects we can not rely on indices to access values. -Meaning - we'll have to iterate through objects in new ways to access the keys -and values within. - -This article will cover: - -1. Iterate through Object `keys` and `values` using a `for...in` loop -2. Use the `Object.keys` and the `Object.values` methods to iterate through an Object. - -### For In Loop - -We can use special syntax to iterate through each `key` of an object (in -arbitrary order). This is super useful for looping through **both** the keys and -values of an object. - -The syntax looks like this: - - // The current key is assigned to *variable* on each iteration. - for (let variable in object) { - statement; - } - -### ex.) - - let obj = { name: "Rose", cats: 2 }; - // The key we are accessing is assigned to the `currentKey` - // *variable* on each iteration. - for (let currentKey in obj) { - console.log(currentKey); - } - // prints out: - // name - // cats - -The example above prints all the keys found in `obj` to the screen. - -On each iteration of the loop, the `key` we are currently accessing is assigned to the`currentKey` variable. - -To access values in an object, we would throw some bracket notation -into the mix: - - let obj = { name: "Rose", cats: 2 }; - for (let key in obj) { - let value = obj[key]; - console.log(value); - } - // prints out: - // Rose - // 2 - -#### You can only use variable keys when using bracket notation (`obj[key]`)! - -> Like all variables, you can name the current key variable whatever you like - -> just be descriptive! Here is an example of using a descriptive name for a key -> variable: - - let employees = { - manager: "Angela", - sales: "Gracie", - service: "Paul" - }; - for (let title in employees) { - let person = employees[title]; - console.log(person); - } - // prints out: - // Angela - // Gracie - // Paul - -### What's a method? - -A **method** is essentially a function that _belongs to_ an object. - -That means that every _method is a function_, but **not** every function -is a method. - -- `myFunc` is a function -- `myObject.myFunc` is a _method_ of the object `myObject` -- `myObject["myFunc"]` is a _method_ of the object `myObject` - A method is just a key-value pair where the **key is the function name and the - value is the function definition**! Let's use what we learned earlier to teach - our dog some new tricks: - - - - let dog = { - name: "Fido" - }; - // defining a new key-value pair where the *function name* is the key - // the function itself is the value! - dog.bark = function() { - console.log("bark bark!"); - }; - // this is the same thing as above just using Bracket Notation - dog["speak"] = function(string) { - console.log("WOOF " + string + " WOOF!!!"); - }; - dog.bark(); // prints `bark bark!` - dog.speak("pizza"); // prints `WOOF pizza WOOF!!!` - -Additionally, we can give objects methods when we initialize them: - - let dog2 = { - name: "Rover", - bark: function() { - console.log("bork bork!"); - }, - speak: function(string) { - console.log("BORK " + string + " BORK!!!"); - } - }; - // Notice that in the object above, we still separate the key-value pairs with commas. - // `bark` and `speak` are just keys with functions as values. - dog2.bark(); // prints `bork bork!` - dog2.speak("burrito"); // prints `BORK burrito BORK!!!` - -To invoke, or call, a method we need to specify **which** object is calling that method. In the example above the `dog2` object had the `bark` method so to invoke `bark` we had to specify it was `dog2`'s method: `dog2.bark()`. - -### Useful Object Methods - -### Iterating through keys using `Object.keys` - -The `Object.keys` method accepts an object as the argument and returns an array of the _keys_ within that Object. - - > let dog = {name: "Fido", age: "2"} - undefined - > Object.keys(dog) - ['name', 'age'] - > let cup = {color: "Red", contents: "coffee", weight: 5} - undefined - > Object.keys(cup) - ['color', 'contents', 'weight'] - -The return value of `Object.keys` method is an array of keys - which is useful -for iterating! - -### Iterating through keys using `Object.values` - -The `Object.values` method accepts an object as the argument and returns an -array of the _values_ within that Object. - - > let dog = {name: "Fido", age: "2"} - undefined - > Object.values(dog) - ['Fido', '2'] - > let cup = {color: "Red", contents: "coffee", weight: 5} - undefined - > Object.keys(cup) - ['Red', 'coffee', 5] - -The return value of `Object.values` method is an array of values - which is -useful for iterating! - -By Bryan Guner on [June 3, 2021](https://medium.com/p/4066ed24b214). - -Canonical link - -August 6, 2021. diff --git a/notes/articles/medium/markdown/Objects-In-JavaScript.md b/notes/articles/medium/markdown/Objects-In-JavaScript.md deleted file mode 100644 index c5b7c5fd91..0000000000 --- a/notes/articles/medium/markdown/Objects-In-JavaScript.md +++ /dev/null @@ -1,233 +0,0 @@ -# Objects In JavaScript - -The object is a data structure that stores other data, similar to how an array stores elements. - ---- - -### Objects In JavaScript - -#### The `object` is a data structure that stores other data, similar to how an array stores elements. - -
    - The object differs in that each `value` stores in an obj is associated with a `key`. - -### **The Object** - -In other programming languages, objects are referred to as, "dictionaries", "maps", or "associative arrays". - -- Objects are indexed with `keys` instead of numbers. -- Order is not guaranteed within an Object. -- Objects are defined by using curly braces `{}` -- You can think of Objects as tables. - -#### **Setting Keys and Values** - -- We assign values to an object by defining the name of the key in brackets and assigning it to a value. - - - - > car { - color: "Blue", - seats: 2 - } - - > - "color" in car; - true - - > - "model" in car; - false - -- If we try to access a key that has not yet been assigned within an object we will output undefined. -- The **preferred method** for checking to see if an object exists at a key is to use the `in` operator. - -#### **Using Variables as Keys** - -- It is useful to set a variable as a key because variables can be re-assigned new values — this way we can quickly access different data and also create new key/value pairs. - -### Using Different Notations - -**Dot notation:** - -- Property identifies can only be alphanumeric (and `_` and `$`) -- Property identifiers cannot start with a number. -- Property identifiers cannot contain variables. -- OK — `obj.prop_1`, `obj.prop$` -- Not OK — `obj.1prop`, `obj.prop name` - -**Bracket notation:** - -- Property identifiers have to be a String or a variable that references a String. -- It is okay to use variables, spaces, and Strings that start with numbers -- OK — `obj["1prop"]`, `obj["prop name"]` - - - - > - let dog = {}; - undefined - - > - dog.bark = "Bowowowo"; - "Bowowowowo" - - > - dog.bark "Bowowowo" - - > - dog { - bark: "Bowowowowo" - } - -- We can also use **dot notation** **"."** to access key/value pairs in an object. -- One thing to note is that when using dot notation, we do not have to use string quotes as the key. - -#### **Bracket Notation vs Dot Notation** - -**DotBracket**Easier To ReadYou can use variables as keys! Easier To Write b/c do not need Quotations. Okay to use variables and Strings that start with numbers.Cannot access with VariablesKeys cannot contain numbers as their first character - -- **When accessing object keys**: Bracket notation needs to refer to that key in quotations, dot notation doesn't. -- **When accessing object keys via a variable**: Bracket notation can refer to that key w/o use of quotations, dot notation can't do this at all. - - - -- As illustrated above, the dot notation cannot access a variable key — since it takes a **literal** interpretation of the key. - -You can put an object together in a single statement. - - let myDog = { - name: "Fido", - type: "Doge", - age: 2, - favoriteToys: ["bone", "ball"], - }; - -#### **Operator Precedence Revisited** - -- The concept of Operator Precedence also applies to objects. -- There are two types of associativity: -- `Right Associativity` : When code is evaluated right to left. - - - - a = b = 1; - - - Since **assignment of variables** takes lowest precedence, we end up evaluating b = 1 first before a = b. - -- `Left Associativity` : When code is evaluated left to right. - - - - let id = "header"; - let element = document.getElementById(id).value; - - - We first resolve the document variable, then use dot notation to retrieve the getElementById function, we eval it's arguments, access it's value, and then retrieve assignment \(the lowest precedence\). - -### Iterating Through Objects - -Because objects store **unordered** key-value pairs, we do not rely on indices to access values; instead, we rely on our keys. - -#### **A New Kind of For Loop** - -> SYNTAX: for (let variable in object) {statement}; - -- We use a special syntax to iterate through each key of an object called a `for-in loop`. - -#### **Methods vs Functions** - -A `Method` is a function that belongs to an object. Every method is a function, but not every function is a method. - - myFunc is a - function - myObject.myFunc is a method of the object myObject - myObject["myFunc"] is a method of the object myObject - -- **Methods** are just a key-value pair where the **key is the function name and the value is the function definition**. - - - -- To invoke these methods we just need to specify which object is calling that method. - - - - myObject.methodName(); - -#### **Useful Object Methods** - -- `Object.keys()` : A method that allows us to iterate through keys, it accepts an obj as the argument and returns an array of the keys. -- `Object.values()` : Method that accepts an object as the argument and returns an array of the values. - -#### **Iterating through an Object's keys & values** - -- `Object.entries` : Method that accepts an object as the argument and returns an array of the \[key, value\] pairs within. - - - - > Object.entries(cat)[['name', 'Freyja'], ['color', 'orange']] - -### References vs Primitives - -#### **Primitives vs Objects** - -So far we have learned about 6 different data types: - -- **Primitive**: Boolean, Null, Undefined, Number, String. -- **Reference**: Object (Arrays are a type of object) -- Remember that **primitive** types are immutable! - -#### **Immutability** - -- When we reassign primitives we simply have our variable point elsewhere in memory. -- In a nutshell, **immutability** cannot change values in memory, but only reassign where our variables are pointing to. - -#### **Mutability** - -- If we change either cat1 or cat2, our computer memory will change because they are both pointing at the same memory location. - -### Rest and Spread - -#### **Using the Spread Operator and Rest Parameter Syntax** **Accepting Arguments** - -- Just keep in mind that the function will still run even if it is not passed any arguments. -- Parameters will take just as many arguments as they need even if more than enough is offered. -- We will encounter an error if there are not enough parameters ( > 0). - -#### **Utilizing Rest Parameters** - -- `Rest Parameter Syntax` : Allows us to capture all of a function's incoming arguments into an array. -- Only the last parameter can be a rest parameter. - -#### **Utilizing Spread Syntax** - -- **Spread Operator**: This allows us to break down a data type into the elements that make it up. -- Takes a data type (i.e. array, obj) and spreads the values of that type where elements are expected. -- Takes iterable data and spreads the elements of that type where arguments are expected. - - - - let numArray = [1, 2, 3]; - - // here we are taking `numArray` and *spreading* it into a new array where - // comma separated elements are expected to be - let moreNums = [...numArray, 4, 5, 6]; - - > - moreNums - // => [1, 2, 3, 4, 5, 6] - -**With Objects** - ---- - -### Learn More On My Blog: - -Web-Dev-Hub -
    - -Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…bgoonz-blog.netlify.app
    - -By Bryan Guner on [May 27, 2021](https://medium.com/p/b212486dade6). - -Canonical link - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Objects-in-Javascript-cc578a781e1d.md b/notes/articles/medium/markdown/Objects-in-Javascript-cc578a781e1d.md deleted file mode 100644 index bc5a922daa..0000000000 --- a/notes/articles/medium/markdown/Objects-in-Javascript-cc578a781e1d.md +++ /dev/null @@ -1,253 +0,0 @@ -# Objects in Javascript - -Codepen with examples for you to practice with below! - ---- - -### Objects in Javascript - -#### Codepen with examples for you to practice with below! - -
    ### The Object Type - -The `object` is a data structure that stores other data, similar to how an array stores elements. - -Javascript simple types: - -- numbers _(has object-like methods but they are immutable)_ -- strings _(has object-like methods but they are immutable)_ -- booleans _(has object-like methods but they are immutable)_ -- null -- undefined - -All other values are _objects_ including arrays and functions. - -Objects are class free, can contain other objects and can inherit properties from their prototypes (which can _reduce object initialisation time and memory consumption_). - -In other programming languages, objects are referred to as, "dictionaries", "maps", or "associative arrays". - -- Objects are indexed with `keys` instead of numbers. -- Order is not guaranteed within an Object. -- Objects are defined by using curly braces `{}` -- You can think of Objects as tables. - -> _Fun Fact: Objects are affectionately known as POJO's (Plain Old Javascript Objects)_ - -**Setting Keys and Values** - -- If we try to access a key that has not yet been assigned within an object we will output undefined. -- The **preferred method** for checking to see if an object exists at a key is to use the operator. - -**Using Variables as Keys** - -### Using Different Notations - -**Bracket Notation vs Dot Notation** - -Easier To Read - -You can use variables as keys! - -Easier To Write b/c do not need Quotations. - -Okay to use variables and Strings that start with numbers. - -Cannot access with Variables - -Keys cannot contain numbers as their first character - -- **When accessing object keys**: Bracket notation needs to refer to that key in quotations, dot notation doesn't. -- **When accessing object keys via a variable**: Bracket notation can refer to that key w/o use of quotations, dot notation can't do this at all. - -**Putting it All Together** - -You can put an object together in a single statement. - -**Operator Precedence Revisited** - -### Iterating Through Objects - -Because objects store **_unordered_** key-value pairs, we do not rely on indices to access values; instead we rely on our keys. - -**Methods vs Functions** - -A is a function that _belongs_ to an object. Every method is a function, but _not_ every function is a method. - -**Useful Object Methods** - -- `Object.keys()` : A method that allows us to iterate through keys, it accepts an obj as the argument and returns an array of the keys. -- `Object.values()` : Method that accepts an object as the argument and returns an array of the values. - -**Iterating through an Object's keys & values** - -### References vs Primitives - -**Primitives vs Objects** - -So far we have learned about 6 different data types: - -- **Primitive** : Boolean, Null, Undefined, Number, String. -- **Reference** : Object (Arrays are a type of object) -- Remember that **primitive** types are immutable! - -**Immutability** - -- When we reassign primitives we simply have our variable point elsewhere in memory. -- In a nutshell, **immutability** cannot change values in memory, but only reassign where our variables are pointing to. - -**Mutability** - -### Rest and Spread - -**Using the Spread Operator and Rest Parameter Syntax** -**Accepting Arguments** - -- Just keep in mind that function will still run even if it is not passed any arguments. -- Parameters will take just as many arguments they need even if more than enough are offered. -- We will encounter an error if there are not enough parameters ( > 0). - -**Utilizing Rest Parameters** - -- `Rest Parameter Syntax` : Allows us to capture all of a function's incoming arguments into an array. -- Only the last parameter can be a rest parameter. - -**Utilizing Spread Syntax** - -- Takes a data type (i.e. array, obj) and spreads the values of that type where elements are expected. -- Takes iterable data and spreads the elements of that type where arguments are expected. - -### Destructuring - -**Swapping Variables using destructuring** - -**Destructuring objects into variables** - -**Destructuring and the Rest Pattern** - -### Destructuring Parameters - -We can also destructure **incoming parameters** of a function. - This is very useful when we're passing objects around to different functions. - ---- - -### Object Literals - -- An object literal is _zero or more comma-separated name/value pairs surrounded by curly braces_ {} - - - - let empty_object = {}; - - let today = { - day: "Wednesday", - month: "April", - year: 2014, - - weather: { //objects can contain nested objects like this one - morning: "sunny", - afternoon: "cloudy" - } - } - -### Retrieval - -- Can be done with either dot notation `today.weather.morning` or with square brackets `today['month']` -- Or operand (||) can be used to fill in default values for nonexistent data to prevent and _undefined_ error: `var weath = today.weather.evening || "unknown"` - -### Update - -- Assigning a property value to an object overwrites any existing property values with that property name - -### Reference - -- Objects refer to each other, they don't hold duplicate copies of data - -### Prototype - -- Every object has a prototype object from which it inherits properties -- _Object.prototype_ comes standard with Javascript and is almost like a 'root parent' - -
    - The `Object.create` method is now available in ES5 (but the method is in the book if required for older versions) -- If an object does not have a property you ask it for, it will keep looking up the prototype chain until it finds it -- If the property *does note exist* anywhere in the chain, it will return *undefined* -- A new property is *immediately visible* to all of the objects below it in the chain once created - -More details in Chapter 6 - -### Reflection - -- Determining what properties an object has -- Using `typeof` includes all properties in the prototype chain including functions -- To avoid inherited properties, use `hasOwnProperty(type);` which returns _true_ if that property exists only in that object itself (not the chain) - - - - today.hasOwnProperty('number') //will return true today.hasOwnProperty('constructor') //will return false - -### Enumeration - -- Best way to enumerate all the properties you want is a for loop: - - - - let i; - let properties = [ 'day', 'month', 'year' ]; - for (i = 0; i < properties.length; i++) { - document.writeIn(properties[i] + ':' + today[properties[i]]); - } - -- This ensures you get the properties you want (i.e. not up the prototype chain) and in the order you want, as opposed to a _for in_ loop which achieves neither of these - -### Delete - -- Removes property from object, but also reveals property from further up the prototype chain if it exists -- Format: `delete today.month` - -### Global Abatement - -- One way to mitigate the risks of global variables is to _create a single global variable_ which then contains your whole application - - - - let MYAPP = {} - - MYAPP.today = { - day: "Wednesday", - month: "April", - year: 2014, - - weather: { //objects can contain nested objects like this one - morning: "sunny", - afternoon: "cloudy" - } - } - //Making sure all other variables (like today) are contained within this one global variable (MYAPP) means none of them have global scope and therefore the risk of naming conflicts, etc in your application is reduced - -#### Further resources: - -A list of all of my articles to link to future posts -
    - -You should probably skip this one… seriously it's just for internal use! - -bgoonz's gists -
    - -Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…gist.github.com
    - -bgoonz — Overview -
    - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
    - -Web-Dev-Resource-Hub -
    - -Edit descriptionweb-dev-resource-hub.netlify.app
    - -By Bryan Guner on [April 15, 2021](https://medium.com/p/cc578a781e1d). - -Canonical link - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Objects-in.md b/notes/articles/medium/markdown/Objects-in.md deleted file mode 100644 index b78e8f0b27..0000000000 --- a/notes/articles/medium/markdown/Objects-in.md +++ /dev/null @@ -1,253 +0,0 @@ -# Objects in Javascript - -Codepen with examples for you to practice with below! - ---- - -### Objects in Javascript - -#### Codepen with examples for you to practice with below! - -
    ### The Object Type - -The `object` is a data structure that stores other data, similar to how an array stores elements. - -Javascript simple types: - -- numbers _(has object-like methods but they are immutable)_ -- strings _(has object-like methods but they are immutable)_ -- booleans _(has object-like methods but they are immutable)_ -- null -- undefined - -All other values are _objects_ including arrays and functions. - -Objects are class free, can contain other objects and can inherit properties from their prototypes (which can _reduce object initialisation time and memory consumption_). - -In other programming languages, objects are referred to as, "dictionaries", "maps", or "associative arrays". - -- Objects are indexed with `keys` instead of numbers. -- Order is not guaranteed within an Object. -- Objects are defined by using curly braces `{}` -- You can think of Objects as tables. - -> _Fun Fact: Objects are affectionately known as POJO's (Plain Old Javascript Objects)_ - -**Setting Keys and Values** - -- If we try to access a key that has not yet been assigned within an object we will output undefined. -- The **preferred method** for checking to see if an object exists at a key is to use the operator. - -**Using Variables as Keys** - -### Using Different Notations - -**Bracket Notation vs Dot Notation** - -Easier To Read - -You can use variables as keys! - -Easier To Write b/c do not need Quotations. - -Okay to use variables and Strings that start with numbers. - -Cannot access with Variables - -Keys cannot contain numbers as their first character - -- **When accessing object keys**: Bracket notation needs to refer to that key in quotations, dot notation doesn't. -- **When accessing object keys via a variable**: Bracket notation can refer to that key w/o use of quotations, dot notation can't do this at all. - -**Putting it All Together** - -You can put an object together in a single statement. - -**Operator Precedence Revisited** - -### Iterating Through Objects - -Because objects store **_unordered_** key-value pairs, we do not rely on indices to access values; instead we rely on our keys. - -**Methods vs Functions** - -A is a function that _belongs_ to an object. Every method is a function, but _not_ every function is a method. - -**Useful Object Methods** - -- `Object.keys()` : A method that allows us to iterate through keys, it accepts an obj as the argument and returns an array of the keys. -- `Object.values()` : Method that accepts an object as the argument and returns an array of the values. - -**Iterating through an Object's keys & values** - -### References vs Primitives - -**Primitives vs Objects** - -So far we have learned about 6 different data types: - -- **Primitive** : Boolean, Null, Undefined, Number, String. -- **Reference** : Object (Arrays are a type of object) -- Remember that **primitive** types are immutable! - -**Immutability** - -- When we reassign primitives we simply have our variable point elsewhere in memory. -- In a nutshell, **immutability** cannot change values in memory, but only reassign where our variables are pointing to. - -**Mutability** - -### Rest and Spread - -**Using the Spread Operator and Rest Parameter Syntax** -**Accepting Arguments** - -- Just keep in mind that function will still run even if it is not passed any arguments. -- Parameters will take just as many arguments they need even if more than enough are offered. -- We will encounter an error if there are not enough parameters ( > 0). - -**Utilizing Rest Parameters** - -- `Rest Parameter Syntax` : Allows us to capture all of a function's incoming arguments into an array. -- Only the last parameter can be a rest parameter. - -**Utilizing Spread Syntax** - -- Takes a data type (i.e. array, obj) and spreads the values of that type where elements are expected. -- Takes iterable data and spreads the elements of that type where arguments are expected. - -### Destructuring - -**Swapping Variables using destructuring** - -**Destructuring objects into variables** - -**Destructuring and the Rest Pattern** - -### Destructuring Parameters - -We can also destructure **incoming parameters** of a function. - This is very useful when we're passing objects around to different functions. - ---- - -### Object Literals - -- An object literal is _zero or more comma-separated name/value pairs surrounded by curly braces_ {} - - - - let empty_object = {}; - - let today = { - day: "Wednesday", - month: "April", - year: 2014, - - weather: { //objects can contain nested objects like this one - morning: "sunny", - afternoon: "cloudy" - } - } - -### Retrieval - -- Can be done with either dot notation `today.weather.morning` or with square brackets `today['month']` -- Or operand (||) can be used to fill in default values for nonexistent data to prevent and _undefined_ error: `var weath = today.weather.evening || "unknown"` - -### Update - -- Assigning a property value to an object overwrites any existing property values with that property name - -### Reference - -- Objects refer to each other, they don't hold duplicate copies of data - -### Prototype - -- Every object has a prototype object from which it inherits properties -- _Object.prototype_ comes standard with Javascript and is almost like a 'root parent' - -
    - The `Object.create` method is now available in ES5 (but the method is in the book if required for older versions) -- If an object does not have a property you ask it for, it will keep looking up the prototype chain until it finds it -- If the property *does note exist* anywhere in the chain, it will return *undefined* -- A new property is *immediately visible* to all of the objects below it in the chain once created - -More details in Chapter 6 - -### Reflection - -- Determining what properties an object has -- Using `typeof` includes all properties in the prototype chain including functions -- To avoid inherited properties, use `hasOwnProperty(type);` which returns _true_ if that property exists only in that object itself (not the chain) - - - - today.hasOwnProperty('number') //will return true today.hasOwnProperty('constructor') //will return false - -### Enumeration - -- Best way to enumerate all the properties you want is a for loop: - - - - let i; - let properties = [ 'day', 'month', 'year' ]; - for (i = 0; i < properties.length; i++) { - document.writeIn(properties[i] + ':' + today[properties[i]]); - } - -- This ensures you get the properties you want (i.e. not up the prototype chain) and in the order you want, as opposed to a _for in_ loop which achieves neither of these - -### Delete - -- Removes property from object, but also reveals property from further up the prototype chain if it exists -- Format: `delete today.month` - -### Global Abatement - -- One way to mitigate the risks of global variables is to _create a single global variable_ which then contains your whole application - - - - let MYAPP = {} - - MYAPP.today = { - day: "Wednesday", - month: "April", - year: 2014, - - weather: { //objects can contain nested objects like this one - morning: "sunny", - afternoon: "cloudy" - } - } - //Making sure all other variables (like today) are contained within this one global variable (MYAPP) means none of them have global scope and therefore the risk of naming conflicts, etc in your application is reduced - -#### Further resources: - -A list of all of my articles to link to future posts -
    - -You should probably skip this one… seriously it's just for internal use! - -bgoonz's gists -
    - -Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…gist.github.com
    - -bgoonz — Overview -
    - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
    - -Web-Dev-Resource-Hub -
    - -Edit descriptionweb-dev-resource-hub.netlify.app
    - -By Bryan Guner on [April 15, 2021](https://medium.com/p/cc578a781e1d). - -Canonical link - -August 6, 2021. diff --git a/notes/articles/medium/markdown/Open-Ended-Frontend-Interview-Questions-You-Should-Answer-Before-Your-Next-Interview.md b/notes/articles/medium/markdown/Open-Ended-Frontend-Interview-Questions-You-Should-Answer-Before-Your-Next-Interview.md deleted file mode 100644 index 4b33860422..0000000000 --- a/notes/articles/medium/markdown/Open-Ended-Frontend-Interview-Questions-You-Should-Answer-Before-Your-Next-Interview.md +++ /dev/null @@ -1,61 +0,0 @@ -# Open Ended Frontend Interview Questions You Should Answer Before Your Next Interview - -Explain event delegation. - ---- - -### Open Ended Frontend Interview Questions You Should Answer Before Your Next Interview - -- Explain event delegation. -- Explain how `this` works in JavaScript. -- Can you give an example of one of the ways that working with `this` has changed in ES6? -- Explain how prototypal inheritance works. -- What's the difference between a variable that is: `null`, `undefined` or undeclared? -- How would you go about checking for any of these states? -- What is a closure, and how/why would you use one? -- What language constructions do you use for iterating over object properties and array items? -- Can you describe the main difference between the `Array.forEach()` loop and `Array.map()` methods and why you would pick one versus the other? -- What's a typical use case for anonymous functions? -- What's the difference between host objects and native objects? -- Explain the difference between: `function Person(){}`, `var person = Person()`, and `var person = new Person()`? -- Explain the differences on the usage of `foo` between `function foo() {}` and `var foo = function() {}` -- Can you explain what `Function.call` and `Function.apply` do? What's the notable difference between the two? -- Explain `Function.prototype.bind`. -- What's the difference between feature detection, feature inference, and using the UA string? -- Explain "hoisting". -- Describe event bubbling. -- Describe event capturing. -- What's the difference between an "attribute" and a "property"? -- What are the pros and cons of extending built-in JavaScript objects? -- What is the difference between `==` and `===`? -- Explain the same-origin policy with regards to JavaScript. -- Why is it called a Ternary operator, what does the word "Ternary" indicate? -- What is strict mode? What are some of the advantages/disadvantages of using it? -- What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript? -- What tools and techniques do you use debugging JavaScript code? -- Explain the difference between mutable and immutable objects. -- What is an example of an immutable object in JavaScript? -- What are the pros and cons of immutability? -- How can you achieve immutability in your own code? -- Explain the difference between synchronous and asynchronous functions. -- What is event loop? -- What is the difference between call stack and task queue? -- What are the differences between variables created using `let`, `var` or `const`? -- What are the differences between ES6 class and ES5 function constructors? -- Can you offer a use case for the new arrow `=>` function syntax? How does this new syntax differ from other functions? -- What advantage is there for using the arrow syntax for a method in a constructor? -- What is the definition of a higher-order function? -- Can you give an example for destructuring an object or an array? -- Can you give an example of generating a string with ES6 Template Literals? -- Can you give an example of a curry function and why this syntax offers an advantage? -- What are the benefits of using `spread syntax` and how is it different from `rest syntax`? -- How can you share code between files? -- Why you might want to create static class members? -- What is the difference between `while` and `do-while` loops in JavaScript? -- What is a promise? Where and how would you use promise? - -By Bryan Guner on [June 7, 2021](https://medium.com/p/7c9722712521). - -Canonical link - -August 31, 2021. diff --git a/notes/articles/medium/markdown/PostgreSQL-In-43-Commands-Or-Less.md b/notes/articles/medium/markdown/PostgreSQL-In-43-Commands-Or-Less.md deleted file mode 100644 index ac4e8029b5..0000000000 --- a/notes/articles/medium/markdown/PostgreSQL-In-43-Commands-Or-Less.md +++ /dev/null @@ -1,1386 +0,0 @@ -# PostgreSQL In 43 Commands Or Less - -In database jargon, PostgreSQL uses a client/server model. A PostgreSQL session consists of the following cooperating processes (programs): - ---- - -### PostgreSQL In 43 Commands Or Less - -#### In database jargon, PostgreSQL uses a client/server model. A PostgreSQL session consists of the following cooperating processes (programs): - -
    - A server process, which manages the database files, accepts connections to the database from client applications, and performs database actions on behalf of the clients. The database server program is called `postgres`. -- The user's client (frontend) application that wants to perform database operations. Client applications can be very diverse in nature: a client could be a text-oriented tool, a graphical application, a web server that accesses the database to display web pages, or a specialized database maintenance tool. Some client applications are supplied with the PostgreSQL distribution; most are developed by users. - -As is typical of client/server applications, the client and the server can be on different hosts. In that case they communicate over a TCP/IP network connection. You should keep this in mind, because the files that can be accessed on a client machine might not be accessible (or might only be accessible using a different file name) on the database server machine. - -The PostgreSQL server can handle multiple concurrent connections from clients. To achieve this it starts ("forks") a new process for each connection. From that point on, the client and the new server process communicate without intervention by the original `postgres` process. Thus, the master server process is always running, waiting for client connections, whereas client and associated server processes come and go. (All of this is of course invisible to the user. We only mention it here for completeness.) - ---- - -> MAIN PART OF ARTICLE IS BELOW DATABASE PRIMER SECTION… YOU CAN TELL YOU'VE GOTTEN TO THE MAIN CONTENT WHEN YOU SEE A NUMBERED LIST! - -> IT'S ALMOST EXACTLY HALFWAY DOWN THIS PAGE - -### Database Primer: - -- Databases power our internet and our applications. -- `Relational Database Management Systems` -- When we install a RDBMS our our PC, our PC becomes a Database System. -- Some popular RDBMS: Oracle, MySQL, MS SQLServer, Postgres SQL… - -#### `Users` - -- Software Apps connect to Databases so that the users of those apps can access data. -- **Types of Users**: -- **Normal Users**: Those who can just access data. -- **Super Users**: Can create and manipulate aspects of your database. -- Keep as little Super Users as possible. - -### `Databases` - -- Place where we store data. -- Data is stored in tables, tables are inter-related with one another (this is why it is called Relational Database) - -### `Tables` - -- Contains an ID column (that provides a unique IQ for every row of the table) -- Contains a Type column that indicates the data type that is being stored. -- Every row is a record in the database. - -Creating Database Entities -Log into PSQL - - psql - -Create a Super User named Berber -create user berber with superuser password 'good-cat'; - -Quit SQL - - \q - -Log-in as your Super User - - psql -U berber postgres - good-cat - -See who you are - - select current_user - -Create a normal user - - user bryan with password 'supersecurepassword؋σενδνυδεσ¤৻ãÃä↬'; - -Quit and log-in with your normal user - - \q - psql -U bryan postgres - -Normal Users cannot create databases, they can only view, select and insert data. -Log back in as yourself, and drop normal user and super user. - - psql (default user is a super) - drop user bryan - drop user berber - -Create a database - - create database cat_database - -View all databases in your RDBMS - - \list - -Create database for a normal user as your super user. - - create database berber_db with owner berber;. - -The normal user will have full control over this granted DB. -Can't create duplicate usernames. -Get rid of database - - drop database - -See all the users in your database - - \du - -See all tables in your database - - \dt - -Create a table in your database - -Lookup definition of a specific table - - \d people - -Delete your people table and remake it - - drop table people - -Remake people - -Create Pet Table w/ references to people table - -- **Data Types**: Text (unlimited) VARCHAR(limit), always user VC if there can be a character limit. -- Always pick the smallest value type in your database. -- End all SQL commands with a semi-colon. -- **Serial** datatype creates a unique serial number. -- Primary Key indicates the most significant way to identify each row of data. -- References keep our database clean, using foreign keys maintains our database integrity. - ---- - -### What is SQL? - -SQL is short for Structured Query Language. Originally, it used to be called SEQUEL (Structured English Query Language) and was used for storing and manipulating data in databases. Today SQL is used to perform all types of data operations in relational database management systems (RDBMS). - -SQL is a powerful language where we can perform a wide range of operations: - -- execute queries -- fetch data -- insert, update, and delete records in a database (DML operations) -- create new objects in a database (DDL operations) -- set permissions on tables, procedures, functions, and views -- and much, much more... - -Data is absolutely everywhere. When you visited this web page, you generated data. When you took a note of your to-dos for the day in your reminders, you generated data. - -All of this data needs to go somewhere! That's where databases come in. Databases store information in a structured way so that it is accessible by computer programs. Programmers use a tool called Structured Query Language (SQL) to access and manipulate databases. - -In this guide, we're going to provide a brief overview of SQL to help you level up your skills! Without further ado, let's get started! - -### More On SQL? - -SQL was invented in the early 1970s by the IBM researchers Donald Chamberlin and Raymond Boyce. The technology may be old but it's still a crucial part of interacting with databases. - -SQL is used to retrieve data from databases, insert records into a database, update a database, and to control the permissions in a database. - -SQL is used with Relational Database Management Systems, or RDBMS. These are databases which are broken up into tables. Each table consists of a list of columns and rows. Tables can be linked together by creating primary and foreign keys between the tables. - -Data scientists, database administrators, data analysts, business analysts and back-end web developers are several of the many types of technologists who use databases in their work. - -### Here's a guide on how to get setup with PSQL: - -PostgreSQL Setup For Windows & WSL/Ubuntu -
    - -If you follow this guide to a tee… you will install PostgreSQL itself on your Windows installation. Then, you will…
    - -### Here's a Cheatsheet I made: - -Postgresql Cheat Sheet -
    - -PostgreSQL commandsmedium.com
    - ---- - -### Inserting Data into a Database - -### Create a Table - -The CREATE TABLE statement creates a new table in a database. You can use this command to specify what columns should appear in a database and the types of those columns. - -### Insert a Record - -The INSERT INTO statement inserts a new row into a database. Depending on the structure of a table, this statement can be used to insert some or all the values into a record. - -### Selecting Data from a Database - -### Selecting Data - -The SELECT statement selects data from one or more tables. It can be used to retrieve all the rows in a table or only rows that meet a set of conditions. You can filter out what columns will be returned by the SELECT statement. - -### Where Statement - -The WHERE statement allows you to select a record based on a condition. - -For instance, you could select all of the names in an Employees table that start with the letter "B". You could select all the people in an Employees table who have worked for a business for at least four years. - -### Ordering Data - -The ORDER BY clause sorts data by a particular column name. It can be used to sort data in either ascending or descending order. - -You could sort a list of employees in ascending order based on the day they were hired. You could sort a list of coffee products by their prices in descending order. - -### Limiting Data - -SQL databases can contain a lot of records. The LIMIT clause allows you to limit how many rows are returned by a query. For instance, you could return only the first five responses from a particular query. - -### Query Values Using Between - -The BETWEEN operator allows you to select records where a column value is within a particular range. For instance, you could use BETWEEN to retrieve a list of employees who work at a business and who earn between $20,000 and $30,000. You could use BETWEEN to retrieve a list of all the coffees at a cafe which cost between $2.00 and $2.50. - -### Updating a Database - -Updating a database allows you to modify the information you have already stored, and you can do so by doing the following: - -### Updating Records - -The UPDATE statement amends the contents of a table. This statement will change all the values in a database that meet a particular condition or set of conditions. You can use a WHERE statement to select which values should be updated. - -### Deleting Records - -The DELETE statement removes one or more rows from a table. By default, this command deletes all the records in a table. The DELETE statement is usually used with a WHERE statement so that only particular records are deleted. - -_The SQL ALTER TABLE statement adds, changes, or removes a column in a table. This statement lets you modify a table after it has been created, even if the table stores records._ - -You may decide that you need to make a change to an SQL table. For instance, you may want to rename a column or add a new column to the table. These changes are all possible with the SQL ALTER TABLE command. - -
    ### SQL ALTER TABLE - -The ALTER TABLE command allows you to change an existing table by: - -- Adding a column. -- Adding a constraint. -- Removing a column. -- Changing a data type. -- Renaming a column. - -_There is no SQL ADD COLUMN statement. To add a column to an SQL table, you must use the ALTER TABLE ADD syntax. ALTER TABLE lets you add, delete, or modify columns in a table._ - -After you have created a table in _SQL_, you may realize that you forgot to add in a specific column that you need. For example, say you may have created a database to store a list of suppliers. Maybe you forgot to include a field to store the category of goods the supplier offers. - -In these situations, you can use the _SQL ALTER TABLE_ statement to amend an existing table. This statement allows you to add a column, change a column, or delete a column. - -Below is an _SQL_ command that will create an employee database that stores three columns. This database stores name of an employee, their title, and the branch for which they work. - - CREATE TABLE employees ( - name VARCHAR(50) NOT NULL, - title VARCHAR(75) NOT NULL, - branch VARCHAR(25) NOT NULL - ); - -But what if we've forgotten to add a column? Say we need to add a column that states whether an employee is on probation. That's where the _ALTER TABLE_ statement comes in. - -### SQL Add Column - -To perform an SQL add column operation, use the ALTER TABLE ADD command. This command alters a table and adds in a column with the specified data type. Using this command, you can add a column to a table after you have created the table. - -### SQL UNION: - -When you're querying a database, you may want to combine the result of two or more `SELECT` statements. For example, you may want to get a list of the cities in which your customers are based, and the cities in which your business has branches. You could run two queries to achieve this goal, but you may want to have a result in one query. - -That's where the `SQL UNION` operator comes in. The `UNION` clause can be used to combine the results of two or more `SELECT` queries into a single result set. - -In this tutorial, we are going to break down the basics of the `SQL UNION` operator and discuss where you may want to use this command when you're working with a database. - -### Query Refresher - -Programmers use queries to retrieve information from a database. Queries almost always begin with the `SQL SELECT` statement and are used to retrieve data based on a set of criteria. Queries usually include the `FROM` operator, which states which table will be queried, among other operators that can filter the resulting data. - -Here is the general syntax for an `SQL` query: - - SELECT column_name FROM table_name WHERE your_condititions_are_met; - -Here's an example of an `SQL` query that returns a list of all employee names: - - SELECT name FROM employees; - -The output from our query is as follows: - -nameLuke -Mike -Hannah -Geoff -Alexis -Emma -Jonah - -(7 rows) - -If you want to retrieve information from multiple columns, you can so do by separating the column names with a comma. If you want to get data from every column, you can use an asterisk (`*`) instead, which represents every column in a table. - -» MORE: SQL Outer Join - -### SQL Union - -The `SQL UNION` operator can be used to combine the results of two or more queries into a single response that results in one table. - -In order to use the `UNION` operator, two conditions must be met. Firstly, the data types of the new columns should be compatible—if a salary is an integer in one table and a float in the other, the union would not work. Secondly, the number and order of the columns must be the same in your queries. - -Here's the syntax for an `SQL UNION` query: - - SELECT column_name FROM table1_name - UNION SELECT column_name FROM table2_name; - -Let's use an example to illustrate how the `SQL UNION` operator works. Let's say that we are a business that needs to send an announcement to all of our customers. We also want all employees to be sent this announcement so they are aware of what is going on. - -### SQL Aggregate Functions: - -SQL aggregate functions collate information about what is in a database. For instance, you can use SUM to find the total of all the values in a column. Aggregate functions save you time when you need to find out information that involves aggregating records., - -Here is a list of the aggregate functions in SQL you can use: - -- COUNT -- SUM -- AVG -- MIN -- MAX - -Let's walk through each of these individually. We're going to be referring to a database of employees throughout this tutorial. - -Aggregate functions are used at the beginning of the SQL SELECT statement. - -If you query both a column and an aggregate function in the same SELECT statement, you must use an SQL GROUP BY clause. This clause tells SQL how to represent the data in your query. - -### SQL Subquery - -_An SQL subquery is a query inside another query. It is used in the WHERE or HAVING clause of an SQL statement. Subqueries let you specify the results of one query as an argument in another query._ - -When you're writing an _SQL_ query, you may want to specify a parameter based on the result of another query. For example, say you have a list of customers. You may want to get a list of customers who have placed orders worth a value over a certain amount. Order and customer information is stored within a different table. - -That's where the _SQL subquery_ operation comes in. _Subqueries_, also known as nested queries, are _SELECT_ queries within the _WHERE_ clause of another _SQL_ query. The main _SQL_ query then uses the result of the subquery. - ---- - -### SQL query examples - -Now let's explore some examples of common and useful PostgreSQL queries that can be used in various situations. - -From PSQL DOCS: - ---- - -### MAIN ARTICLE CONTENT: - -### 1. CREATE TABLE query in PostgreSQL - -### CREATE TABLE is a keyword that will create a new, initially empty table in the database. The table will be owned by the user who has issued this command. - - postgres=# create table dummy_table(name varchar(20),address text,age int); - CREATE TABLE - -### 2. INSERT query in PostgreSQL - -The INSERT command is used to insert data into a table: - - postgres=# insert into dummy_table values('XYZ','location-A',25); - INSERT 0 1 - postgres=# insert into dummy_table values('ABC','location-B',35); - INSERT 0 1 - postgres=# insert into dummy_table values('DEF','location-C',40); - INSERT 0 1 - postgres=# insert into dummy_table values('PQR','location-D',54); - INSERT 0 1 - -### 3. SELECT query without WHERE condition in PostgreSQL - -The SELECT command (when used without the optional WHERE condition) is used to fetch all data from a database table: - - postgres=# select * from dummy_table; - name | address | age - ---------+--------------+ ----- - XYZ | location-A | 25 - ABC | location-B | 35 - DEF | location-C | 40 - PQR | location-D | 54 - (4 rows) - -### 4. UPDATE query in PostgreSQL - -UPDATE is used to make updates to the data or row(s) of a database table. In the example below we use UPDATE to change the age of a person whose name is 'PQR': - - postgres=# update dummy_table set age=50 where name='PQR'; - UPDATE 1 - postgres=# select * from dummy_table; - name | address | age - --------+--------------+------- - XYZ | location-A | 25 - ABC | location-B | 35 - DEF | location-C | 40 - PQR | location-D | 50 - (4 rows) - -Next, we'll use the UPDATE command to change the name and age of a person whose address is 'location-D': - - postgres=# update dummy_table set name='GHI',age=54 where address='location-D'; - UPDATE 1 - postgres=# select * from dummy_table; - name | address | age - ------+------------+----- - XYZ | location-A | 25 - ABC | location-B | 35 - DEF | location-C | 40 - GHI | location-D | 54 - (4 rows) - - postgres=# - -If we want to modify all the values in the address and age columns in dummy_table, then we do not need to use the WHERE clause. The UPDATE query would look like this: - - postgres=# update dummy_table set age=54,address='location-X'; - UPDATE 4 - - - postgres=# select * from dummy_table ; - name | address | age - ------+------------+-------- - XYZ | location-X | 54 - ABC | location-X | 54 - DEF | location-X | 54 - GHI | location-X | 54 - (4 rows) - - postgres=# - -A RETURNING clause returns the updated rows. This is optional in UPDATE: - - postgres=# update dummy_table set age=30 where name='XYZ' returning age as age_no; - age_no - --------- - 30 - (1 row) - - UPDATE 1 - -It is always recommended to perform such operations under transaction blocks (i.e., BEGIN...COMMIT/ROLLBACK;), so we have the option to roll back the operation. - -### 5. DELETE query in PostgreSQL - -The DELETE command is used to delete row(s). It can be used with or without the optional WHERE condition, but take note: if the WHERE condition is missing, the command will delete all rows, leaving you with an empty table. - -In this example, we are deleting one row whose age column has the value 65: - - postgres=# delete from dummy_table where age=65; - DELETE 1 - postgres=# - -### 6. Comparison Operators in PostgreSQL queries - -In PostgreSQL, with the help of comparison operators we can find results where the value in a column is not equal to the specified condition or value. - -### Less than or equal to query: - - postgres=# select * from dummy_table where age <=50; - name | address | age - ------+------------+----- - XYZ | location-A | 25 - ABC | location-B | 35 - DEF | location-C | 40 - PQR | location-D | 50 - (4 rows) - -### Greater than or equal to query: - - postgres=# select * from dummy_table where age>=50; - name | address | age - ------+------------+----- - PQR | location-D | 50 - (1 row) - -### Not equal to query: - - postgres=# select * from dummy_table where age<>50; - name | address | age - ------+------------+----- - XYZ | location-A | 25 - ABC | location-B | 35 - DEF | location-C | 40 - (3 rows) - -### Equal to query: - - postgres=# select * from dummy_table where age=50; - name | address | age - ------+------------+----- - PQR | location-D | 50 - (1 row) - -### 7. SELECT DISTINCT query in PostgreSQL - -The SELECT DISTINCT statement is used to return only distinct values from the table. It removes any duplicate values. - -### SELECT query without DISTINCT clause - - postgres=# select age from dummy_table order by 1; - age - ----- - 1 - 1 - 2 - 2 - 3 - (5 rows) - -### SELECT query with DISTINCT clause - - postgres=# select distinct age from dummy_table order by 1; - age - ----- - 1 - 2 - 3 - (3 rows) - -### 8. TRUNCATE query in PostgreSQL - -The TRUNCATE command is used to empty a table: - - postgres=# truncate table dummy_table; - TRUNCATE TABLE - -### 9. DROP TABLE query in PostgreSQL - -This DROP TABLE command is used to drop a table from the database: - - postgresql=# drop table if exists dummy; - NOTICE: table "dummy" does not exist, skipping - DROP TABLE - -This command has removed the full table, including any associated data, indexes, rules, triggers, and constraints for that table. - -### 10. CREATE VIEW query in PostgreSQL - -The CREATE VIEW command is used to generate views. Views are pseudo-tables, which are used to present a full table, subset, or select columns from the underlying table: - - postgres=# create or replace view vi as select * from dummy_table where age is NULL; - CREATE VIEW - -### 11. Create a table in Postgresql using the SELECT statement - -Using the syntax in the example below, we can create a table using a SELECT statement: - - postgres=# select 'My name is X' as col1 , 10 as col2, 'Address is -XYZ location' as col3 into new_table; - SELECT 1 - postgres=# select * from new_table ; - col1 | col2 | col3 - ---------------+------+-------------------------- - My name is X | 10 | Address is -XYZ location - (1 row) - -### 12. Query timeout in PostgreSQL - -We can command a query to timeout after a certain period with the help of GUC parameters (short for grand unified configuration) like statement_timeout, which aborts any statement that takes more than the specified number of milliseconds: - - postgresql=# set statement_timeout=10; - SET - postgresql=# select pg_sleep(20); - ERROR: canceling statement due to statement timeout - -### 13. Using CREATE SEQUENCE with the INSERT query in PostgreSQL - -The CREATE SEQUENCE command is a sequential number generator. Once the sequence is created, we can use the sequence's nextval and currval functions to insert values into a table: - - postgres=# create sequence seq; - CREATE SEQUENCE - postgres=# create table tab(n int); - CREATE TABLE - postgres=# insert into tab values (nextval('seq')); - INSERT 0 1 - postgres=# insert into tab values (currval('seq')); - INSERT 0 1 - postgres=# insert into tab values (nextval('seq')); - INSERT 0 1 - postgres=# select * from tab; - n - --- - 1 - 1 - 2 - (3 rows) - -### 14. Importing BLOB data types into PostgreSQL - -PostgreSQL doesn't directly support BLOBs (binary large objects), but we can work with them using the following methods: - -Let's assume you have an image (in png format) downloaded in the /home/edb/ folder: - - [edb@localhost]$ ls /home/edb/mypic.png - /home/edb/mypic.png - -We want to store this image in the PostgreSQL database. - -Go to the bin folder of your PostgreSQL installation and connect to the psql terminal: - - postgres=# Create table testing(n int,n1 oid); - CREATE TABLE - postgres=# insert into testing values (1,lo_import('/home/edb/mypic.png')); - INSERT 0 1 - -The lo_import() function loads the named file into pg_largeobject and returns an OID (object identifier) value that will refer to the large object. Selecting the testing table will show just the OID and not the bits that have made up this photo. - -### 15. ILIKE query in PostgreSQL - -The ILIKE operator is a matching function similar to the LIKE operator, but with the advantage that it matches valus case-insensitively. - - postgres=# select * from ted; - n - ----- - TAR - TaR - Tar - tar - (4 rows) - -### Using ILIKE in a WHERE condition - - postgres=# select * from ted where n ilike 'TAR%'; - n - ----- - TAR - TaR - Tar - tar - (4 rows) - -### 16. Hierarchical queries in PostgreSQL - -Hierarchical queries are ones where the results have a structured or parent-child relationship and are displayed in a tree structure. To see how hierarchical queries work, create a dummy table: - - create table test_table( - emp_no int, - ename char(5), - job char(9), - manager_no int - ); - -Insert data into 'test_table': - - insert into test_table values(10,'A1','CEO',null); - insert into test_table values(11, 'B1', 'VP', 10); - insert into test_table values(12, 'B2', 'VP', 10); - insert into test_table values(13, 'B3', 'VP', 10); - insert into test_table values(14, 'C1', 'DIRECTOR', 13); - insert into test_table values(15, 'C2', 'DIRECTOR', 13); - insert into test_table values(16, 'D1', 'MANAGER', 15); - insert into test_table values(17 ,'E1', 'ENGINEER', 11); - insert into test_table values(18, 'E2', 'ENGINEER', 11); - -We can perform hierarchical queries on this table using the methods below. - -### 17. Length function in PostgreSQL - -The length function returns the number of characters or number of bytes in a specified string variable. - -### Basic SELECT query - - postgres=# select name,age from dummy_table; - name | age - ------+----- - XYZ | 25 - ABC | 35 - DEF | 40 - PQR | 54 - PQR | - (5 rows) - -### Query with length function for column name and age - - postgres=# select length(name),length(age) from dummy_table; - length | length - --------+-------- - 3 | 2 - 3 | 2 - 3 | 2 - 3 | 2 - 3 | - (5 rows) - -### 18. When a query has no destination for result data in PostgreSQL - -Say that while selecting a given function, we receive the error message below: - - postgresql=# create or replace function f(n int) - returns int - as - $$ - begin - select now(); - return 1; - end; - $$ language 'plpgsql'; - CREATE FUNCTION - postgres=# select f(9); - ERROR: query has no destination for result data - HINT: If you want to discard the results of a SELECT, use PERFORM instead. - -To avoid such errors, we can either use PERFORM or declare a variable and use it in a SELECT INTO statement: - -### Using PERFORM - - postgres=# create or replace function f(n int) - returns int - as - $$ - begin - perform - now(); - return 1; - end; - $$ language 'plpgsql'; - CREATE FUNCTION - postgresql=# select f(9); - f - --- - 1 - (1 row) - -### Declaring a variable and using it in a SELECT INTO statement - - postgres=# create or replace function f(n int) - returns int - as - $$ - declare - a date; - begin - select now() into a; - raise notice '%s',a; - return 1; - end; - $$ language 'plpgsql'; - CREATE FUNCTION - - - postgresql=# select f(9); - NOTICE: 24-SEP-20 13:15:46.23388s - f - --- - 1 - (1 row) - -### 19. Exporting query result to a text file in PostgreSQL - -With the help of the COPY command, we can export data from a table to an outside text file as well as import data from a text file into a table. - -### Exporting data from a table to a text file - - postgres=# copy dummy_table to '/tmp/abc.txt'; - COPY 5 - - postgres=# \! cat /tmp/abc.txt - XYZ location-A 25 - ABC location-B 35 - DEF location-C 40 - PQR location-D 50 - CXC 1 50 - -### Importing data from a text file into a table - - postgres=# copy dummy_table from '/tmp/abc.txt'; - COPY 5 - -- With the help of common table expressions (CTE): - - - - postgres=#WITH RECURSIVE cte AS ( SELECT emp_no, ename, manager_no, 1 AS level FROM test_table where manager_no is null UNION ALL SELECT e.emp_no, e.ename, e.manager_no, c.level + 1 FROM cte c JOIN test_table e ON e.manager_no = c.emp_no ) SELECT * FROM cte; emp_no | ename | manager_no | level -----------+----------+------------------+------- 10 | A1 | | 1 11 | B1 | 10 | 2 12 | B2 | 10 | 2 13 | B3 | 10 | 2 14 | C1 | 13 | 3 17 | E1 | 11 | 3 18 | E2 | 11 | 3 15 | C2 | 13 | 3 16 | D1 | 15 | 4 (9 rows) postgres=# - -- Using the tablefunc extension: - -1. The tablefunc extension is a contrib module that resides in the contrib/ folder in PostgreSQL sources. -2. First, create the tablefunc extension: - -- `postgres=# CREATE EXTENSION tablefunc; CREATE EXTENSION postgres=#` - -1. Then, use tablefunc's connectby function to display results hierarchically: - - - - postgres=# SELECT * FROM connectby('dummy_table', 'emp_no', 'manager_no', '10', 0, '->') AS t(emp_no int, manager_no int, level int, ord text) order by emp_no; emp_no | manager_no | level | ord --------+------------+-------+---------------- 10 | | 0 | 10 11 | 10 | 1 | 10->11 12 | 10 | 1 | 10->12 13 | 10 | 1 | 10->13 14 | 13 | 2 | 10->13->14 15 | 13 | 2 | 10->13->15 16 | 15 | 3 | 10->13->15->16 17 | 11 | 2 | 10->11->17 18 | 11 | 2 | 10->11->18 (9 rows) postgres=# - -### 20. Listing databases query in PostgreSQL - -The following query can be used to show all the databases created: - - postgres=# select oid,datname from pg_database; - oid | datname - -----------+----------- - 13743 | postgres - 1 | template1 - 13742 | template0 - (3 rows) - -We can also list out all the database names using the \\l command at the psql prompt. - -### 21. Checking query execution time in PostgreSQL - -We can check the time needed for a query to execute by enabling \\timing at the psql prompt: - - postgres=# \timing - Timing is on. - -The SELECT query will now show the execution time: - - postgres=# select * from dummy_table; - name | address | age - ------+------------+-------- - XYZ | location-A | 25 - ABC | location-B | 35 - DEF | location-C | 40 - PQR | location-D | 50 - CXC | 1 | 50 - (5 rows) - - Time: 0.440 ms - postgres=# - -### 22. Dynamic SQL query in PostgreSQL - -Dynamic SQL is used to reduce repetitive tasks when it comes to querying. -Dynamic SQL queries are not cached in memory. - - postgres=# do - postgres-# $$ - postgres$# begin - postgres$# execute 'select * from dummy_table'; - postgres$# end; - postgres$# $$; - DO - -### 23. COUNT query in PostgreSQL - -The COUNT query returns the number of rows in a table. If we use (\*) this will include null values; otherwise null values will be excluded. - - postgres=# select count(*) from dummy_table; - count - ------- - 5 - (1 row) - - postgres=# select count(avg) from dummy_table; - count - ------- - 4 - (1 row) - -### 24. LIMIT and OFFSET query in PostgreSQL - -The LIMIT clause is used to limit the data amount returned by the SELECT statement. The query below will display only 1 row: - - postgres=# select * from dummy_table limit 1; - name | address | age - ------+------------+----- - XYZ | location-A | 25 - (1 row) - -OFFSET is used when we want to skip a particular number of rows: - - postgres=# select * from dummy_table offset 4; - name | address | age - ------+---------+----- - cxc | 1 | 50 - (1 row) - -### 25. IF … ELSE expression in PostgreSQL - -We can use conditional statements like IF ... ELSE in an anonymous block. The example below checks if the values of variables abc and xyz are matching and prints the result— i.e., 150: - - postgres=# Do - $$ - Declare - abc int; - xyz int; - begin - abc:=100; - xyz:=abc; - if abc=xyz then - xyz=150; - raise notice '%',xyz; - else - end if; - end; - $$ - ; - NOTICE: 150 - DO - -### 26. UPDATE with JOIN query in PostgreSQL - -We can use UPDATE with a JOIN and WHERE clause when we want to update the values from one table (table X) based on values from another table (table Y): - - postgres=# create table X(n int, n1 char(10)); - CREATE TABLE - postgres=# insert into X values (1,'abc'); - INSERT 0 1 - postgres=# insert into X values (2,'xyz'); - INSERT 0 1 - postgres=# insert into X values (3,'pqr'); - INSERT 0 1 - - postgres=# create table Y(n int, n1 char(10)); - CREATE TABLE - - postgres=# insert into Y values (1,''); - INSERT 0 1 - postgres=# insert into Y values (2,''); - INSERT 0 1 - - postgres=# insert into Y values (5,'axyz'); - INSERT 0 1 - - postgres=# update Y set n1=X.n1 from X where X.n=Y.n; - UPDATE 2 - postgres=# select * from Y; - n | n1 - ---+------------ - 5 | axyz - 1 | abc - 2 | xyz - (3 rows) - - postgres=# - -### 27. INNER JOIN query in PostgreSQL - -The INNER JOIN command will find rows from two (or more) tables where the specified columns data in the tables match: - - postgres=# select * from x inner join y on x.n1 = y.n1; - n | n1 | n | n1 - ---+------------+---+------------ - 1 | abc | 1 | abc - 2 | xyz | 2 | xyz - (2 rows) - - postgres=# - -### 28. CASE expression in PostgreSQL - -The CASE expression is a generic conditional expression, similar to the IF … ELSE statement. - - postgres=# SELECT age, - CASE age WHEN 25 THEN 'one' - WHEN 50 THEN 'two' - ELSE 'other' - END - FROM dummy_table; - age | case - -----+------- - 25 | one - 35 | other - 40 | other - 50 | two - 50 | two - (5 rows) - -### 29. PostgreSQL recursive query - -Recursive queries are used to deal with hierarchical queries or tree-structured data. The structure of a WITH RECURSIVE query is always: a) Non-recursive term - b) UNION (or UNION ALL), then a recursive term - -where the recursive term includes a reference to the query's output. - - CREATE TABLE emp_test ( - id int, - ename varchar(255), - emanager int - ); - - INSERT INTO emp_test VALUES (1, 'abc', null); - INSERT INTO emp_test VALUES (2, 'xyz', 1); - INSERT INTO emp_test VALUES (3, 'def', 2); - INSERT INTO emp_test VALUES (4, 'cde', 1); - INSERT INTO emp_test VALUES (5, 'qrs', 2); - INSERT INTO emp_test VALUES (9, 'iop', 3); - INSERT INTO emp_test VALUES (10, 'klm', 4); - -The recursive query below will give all the reports in a certain order: - - postgres=#WITH RECURSIVE emp_testnew AS ( - SELECT id, ename, emanager - FROM emp_test - WHERE id = 2 - UNION ALL - SELECT e.id, e.ename, e.emanager - FROM emp_test e - INNER JOIN emp_testnew e1 ON e1.id = e.emanager - ) - SELECT * - FROM emp_testnew; - - id | ename | emanager - ----+-------+---------- - 2 | xyz | 1 - 3 | def | 2 - 5 | qrs | 2 - 9 | iop | 3 - (4 rows) - - postgres=# - -### 30. PostgreSQL log queries - -Using the pg_stat_statements module, we can track execution statistics for all SQL statements. To do this, we need to create an extension and add in shared_preload_libraries inside the postgresql.conf file: - - postgres=# create extension pg_stat_statements; - CREATE EXTENSION - - - postgres=# show shared_preload_libraries ; - shared_preload_libraries - ------------------------------------------------- - $libdir/pg_stat_statements - (1 row) - - - postgres=# select query from pg_stat_statements where query like 'create table%'; - -[ RECORD 1 ]------------------- - query | create table test(n int) - -We can also configure PostgreSQL to generate log output by enabling these parameters in the postgresql.conf file: - - logging_collector = on - log_directory = 'log' - log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log' - log_destination = 'stderr' - Log file will be created under the pg_log directory which resides under the data folder. - - [centos@tushar-ldap-docker bin]$ ls data/log - postgresql-2020-09-17_150932.log postgresql-2020-09-19_000000.log - [centos@tushar-ldap-docker bin]$ - -Queries will be recorded in these files. - -### 31. Using a variable in a PostgreSQL query - -We can declare a variable in PostgreSQL at the psql prompt: - - postgres=# \set cond 50 - -### Using a variable in a WHERE condition - - postgres=# select * from dummy_table where age=:cond; - name | address | age - ------+------------+----- - PQR | location-D | 50 - (1 row) - -OR - - postgres=# \set cond 50 - postgres=# select :cond+100 ; - ?column? - ---------- - 150 - (1 row) - -### 32. Date query in PostgreSQL - -PostgreSQL offers functions for date and time that can be used in queries. - - postgres=# select now(); - now - ---------------------------------- - 22-SEP-20 03:08:42.636385 +05:30 - (1 row) - - postgres=# select current_date; - current_date - -------------- - 22-SEP-20 - (1 row) - - postgres=# select current_time; - current_time - ----------------------- - 03:08:53.648466+05:30 - (1 row) - -We can also perform a date range query to find rows with values between two time stamps: - - postgres=# create table datetable(n int,n1 date); - CREATE TABLE - - postgres=# insert into datetable values (1,'12-01-1980'); - INSERT 0 1 - postgres=# insert into datetable values (2,'12-01-2020'); - INSERT 0 1 - postgres=# insert into datetable values (3,'12-01-2000'); - INSERT 0 1 - postgres=# select * from datetable where n1 between '12-01-1980' and '12-01-2000'; - n | n1 - ---+-------------------- - 1 | 12-JAN-80 00:00:00 - 3 | 12-JAN-00 00:00:00 - (2 rows) - -### 33. PostgreSQL function RETURN QUERY result - -When a PL/pgSQL function is declared to return a SETOF some data type, the return is specified by a RETURN QUERY command: - - postgres=# CREATE FUNCTION get(int) RETURNS SETOF integer AS - $BODY$ - BEGIN - RETURN QUERY SELECT age - FROM dummy_table - WHERE age >= $1 ; - RETURN; - END - $BODY$ - LANGUAGE plpgsql; - - - postgres=# select * from get(9); - get - ----- - 25 - 35 - 40 - 50 - (4 rows) - -### 34. PostgreSQL parallel query performance - -Parallel queries in PostgreSQL allow you to finish queries faster by utilizing many CPUs. These GUCs parameters are set in postgresql.conf file: - - #max_parallel_maintenance_workers = 2 # taken from max_parallel_workers - #max_parallel_workers_per_gather = 2 # taken from max_parallel_workers - #parallel_leader_participation = on - #max_parallel_workers = 8 # maximum number of max_worker_processes that - # can be used in parallel operations - - - postgres=# create table ty(n int); - CREATE TABLE - postgres=# insert into ty values (generate_series(1,300000)); - INSERT 0 300000 - - postgres=# analyze ty; - ANALYZE - postgres=# explain select * from ty where n<=1; - QUERY PLAN - --------------------------------------------------------------------- - Gather (cost=1000.00..4536.88 rows=30 width=4) - Workers Planned: 1 - -> Parallel Seq Scan on ty (cost=0.00..3533.88 rows=18 width=4) - Filter: (n <= 1) - (4 rows) - - postgres=# - -### 35. Logical operators in PostgreSQL - -There are three basic logical operators available in PostgreSQL: AND, OR, and NOT. - -These operators are used to match conditions in SQL statements—e.g., in WHERE and HAVING clauses. - - AND = when both boolean expressions are true then it will return TRUE - OR = when any boolean expression is true then it will return TRUE - NOT = reverses the value of Boolean operator - -### Some logical operator examples - - If both expressions are true, then the result is TRUE. postgresql=# select 1=1/1 and 200=2+198 as result_and_operator; result_and_operator --------------------- t (1 row) postgresql=# - - If one expression is true and another expression is NULL, then the result is NULL. postgresql=# select 4=4 and null; ?column? ---------- (1 row) - If one expression is true and another expression is false, then the result is TRUE. postgres=# select 1=100 OR 2=2; ?column? ---------- t (1 row) - -### 36. Catching duplicate rows in a PostgreSQL table - -In the following SQL query, there are two records with the value 50: - - postgres=# select age from dummy_table; - age - ----- - 25 - 35 - 40 - 50 - 50 - (5 rows) - -We can use the following SELECT … HAVING query to find the duplicate rows: - - postgres=# select age, count(age) from dummy_table group by age having count(age)>1; - age | count - -----+------- - 50 | 2 - (1 row) - -### 37. Enum query in PostgreSQL - -Enumerated (enum) types are data types that comprise a static, ordered set of values. - - postgres=# CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy'); - CREATE TYPE - postgres=# create table testi(n int, n1 mood); - CREATE TABLE - postgres=# insert into testi values (1,'happy'); - INSERT 0 1 - postgres=# insert into testi values (1,'sad'); - INSERT 0 1 - postgres=# insert into testi values (1,'ok'); - INSERT 0 1 - -If the enum has not been specified, it will give an error: - - postgres=# insert into testi values (1,'happyo'); - ERROR: invalid input value for enum mood: "happyo" - -### 38. Pivot query in PostgreSQL - -A pivot table is a useful way to analyze large quantities of data by organizing it into a more manageable format. - - CREATE TABLE newtb(id SERIAL, rowid varchar(10), attri varchar(10), val varchar(10)); - INSERT INTO newtb(rowid, attri, val) values('t1','a1','v1'); - INSERT INTO newtb(rowid, attri, val) values('t1','a2','v2'); - INSERT INTO newtb(rowid, attri, val) values('t1','a3','v3'); - INSERT INTO newtb(rowid, attri, val) values('t1','a4','v4'); - INSERT INTO newtb(rowid, attri, val) values('t2','a1','v5'); - INSERT INTO newtb(rowid, attri, val) values('t2','a2','v6'); - INSERT INTO newtb(rowid, attri, val) values('t2','a3','v7'); - INSERT INTO newtb(rowid, attri, val) values('t2','a4','v8'); - -To create a pivot table you need to install the tablefunc extension: - - postgres=# create extension tablefunc; - CREATE EXTENSION - - Select * - FROM crosstab( - 'select rowid, attri, val - from newtb - where attri = ''a2'' or attri = ''a3'' - order by 1,2') - AS newtb(row_name varchar(10), category_1 varchar(10), category_2 varchar(10), category_3 varchar(10)); - row_name | category_1 | category_2 | category_3 - ----------+------------+------------+-------------------------- - t1 | v2 | v3 | - t2 | v6 | v7 | - (2 rows) - -### 39. SELF JOIN query in PostgreSQL - -When we join a table against itself, this is called a SELF JOIN. This can be done using INNER JOIN or LEFT JOIN. SELF JOINs are useful when comparing the columns of rows within the same table: - - postgres=# create table emp1(emp_id int, firstname char(10), lastname char(10) , manager_id int); - CREATE TABLE - postgres=# - postgres=# - postgres=# insert into emp1 values(1,'ABC','XYZ',NULL); - INSERT 0 1 - postgres=# insert into emp1 values(2,'TYU','BGV',1); - INSERT 0 1 - postgres=# insert into emp1 values(3,'TEU','ZZV',1); - INSERT 0 1 - postgres=# insert into emp1 values(4,'REU','AZV',2); - INSERT 0 1 - postgres=# insert into emp1 values(5,'QREU','WZV',2); - INSERT 0 1 - postgres=# insert into emp1 values(6,'DREU','QZV',3); - INSERT 0 1 - - - postgres=# select a.firstname,b.lastname from emp1 a inner join emp1 b on a.emp_id=b.manager_id order by 1 ; - firstname | lastname - ------------+------------ - ABC | ZZV - ABC | BGV - TEU | QZV - TYU | WZV - TYU | AZV - (5 rows) - - postgres=# - -### 40. Parent-child recursive query in PostgreSQL - -With the help of common table expressions (CTE) we can perform parent-child recursive queries: - - postgres=# CREATE TABLE recu_pc ( - id SERIAL PRIMARY KEY, - name varchar(10) NOT NULL, - parent_id integer ); - CREATE TABLE - - postgres=# insert into recu_pc values (1, 'Grandmother', NULL); - INSERT 0 1 - postgres=# insert into recu_pc values (2, 'mother', 1); - INSERT 0 1 - postgres=# insert into recu_pc values (3, 'daughter', 2); - INSERT 0 1 - - - postgres=# WITH RECURSIVE rec_q (id) as - ( - SELECT recu_pc.id, recu_pc.name from recu_pc where name='mother' - UNION ALL - SELECT recu_pc.id, recu_pc.name from rec_q, recu_pc where recu_pc.parent_id = rec_q.id - ) - SELECT * - FROM rec_q; - id | name - ----+---------- - 2 | mother - 3 | daughter - (2 rows) - -### 41. Defining a variable in a query in PostgreSQL - -Using an anonymous block, we can define a variable that can be passed to in a query: - - postgres=# do - $$ - declare - a int; - begin - select age into a from dummy_table - where name ='XYZ'; - raise notice '%',a; - end; - $$; - NOTICE: 25 - DO - -### 42. PREPARE statement in PostgreSQL - -A prepared statement is used to optimize performance. When the PREPARE statement is executed, it is not only parsed but analyzed too, and when we fire the EXECUTE command the prepared statement is planned and executed. - -Prepared statements can accept parameters. - - postgres=# prepare test(int) as - select * from dummy_table where age=$1; - PREPARE - - postgres=# execute test(50); - name | address | age - ------+------------+--------- - PQR | location-D | 50 - CXC | 1 | 50 - (2 rows) - -### 43. Checking NULL values in PostgreSQL - -To Identify or select rows that have NULL values, the IS NULL condition can be used in the WHERE clause. - - postgres=# select * from dummy_table; - name | address | age - ------+------------+----- - XYZ | location-A | 25 - ABC | location-B | 35 - DEF | location-C | 40 - PQR | location-D | 54 - PQR | location-D | - (5 rows) - -Identifying null values in 'age' column: - - postgres=# select name from dummy_table where age is null; - name - ------ - PQR - (1 row) - -### Sources: - -1. ) https://careerkarma.com/blog/sql-deep-dives/ -2. https://www.postgresql.org/docs/13/app-psql.html - -Learn More: - -Web-Dev-Hub -
    - -Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…bgoonz-blog.netlify.app
    - -### Further Examples / Readings: - -By Bryan Guner on [July 14, 2021](https://medium.com/p/19fba3e37110). - -Canonical link - -August 31, 2021. diff --git a/notes/articles/medium/markdown/PostgreSQL-In-43-Commands-Or.md b/notes/articles/medium/markdown/PostgreSQL-In-43-Commands-Or.md deleted file mode 100644 index 135de30d59..0000000000 --- a/notes/articles/medium/markdown/PostgreSQL-In-43-Commands-Or.md +++ /dev/null @@ -1,1264 +0,0 @@ -# PostgreSQL In 43 Commands Or Less - -In database jargon, PostgreSQL uses a client/server model. A PostgreSQL session consists of the following cooperating processes (programs): - ---- - -### PostgreSQL In 43 Commands Or Less - -#### In database jargon, PostgreSQL uses a client/server model. A PostgreSQL session consists of the following cooperating processes (programs): - -
    - A server process, which manages the database files, accepts connections to the database from client applications, and performs database actions on behalf of the clients. The database server program is called `postgres`. -- The user's client (frontend) application that wants to perform database operations. Client applications can be very diverse in nature: a client could be a text-oriented tool, a graphical application, a web server that accesses the database to display web pages, or a specialized database maintenance tool. Some client applications are supplied with the PostgreSQL distribution; most are developed by users. - -As is typical of client/server applications, the client and the server can be on different hosts. In that case they communicate over a TCP/IP network connection. You should keep this in mind, because the files that can be accessed on a client machine might not be accessible (or might only be accessible using a different file name) on the database server machine. - -The PostgreSQL server can handle multiple concurrent connections from clients. To achieve this it starts ("forks") a new process for each connection. From that point on, the client and the new server process communicate without intervention by the original `postgres` process. Thus, the master server process is always running, waiting for client connections, whereas client and associated server processes come and go. (All of this is of course invisible to the user. We only mention it here for completeness.) - -### What is SQL? - -SQL is short for Structured Query Language. Originally, it used to be called SEQUEL (Structured English Query Language) and was used for storing and manipulating data in databases. Today SQL is used to perform all types of data operations in relational database management systems (RDBMS). - -SQL is a powerful language where we can perform a wide range of operations: - -- execute queries -- fetch data -- insert, update, and delete records in a database (DML operations) -- create new objects in a database (DDL operations) -- set permissions on tables, procedures, functions, and views -- and much, much more... - -Data is absolutely everywhere. When you visited this web page, you generated data. When you took a note of your to-dos for the day in your reminders, you generated data. - -All of this data needs to go somewhere! That's where databases come in. Databases store information in a structured way so that it is accessible by computer programs. Programmers use a tool called Structured Query Language (SQL) to access and manipulate databases. - -In this guide, we're going to provide a brief overview of SQL to help you level up your skills! Without further ado, let's get started! - -### More On SQL? - -SQL was invented in the early 1970s by the IBM researchers Donald Chamberlin and Raymond Boyce. The technology may be old but it's still a crucial part of interacting with databases. - -SQL is used to retrieve data from databases, insert records into a database, update a database, and to control the permissions in a database. - -SQL is used with Relational Database Management Systems, or RDBMS. These are databases which are broken up into tables. Each table consists of a list of columns and rows. Tables can be linked together by creating primary and foreign keys between the tables. - -Data scientists, database administrators, data analysts, business analysts and back-end web developers are several of the many types of technologists who use databases in their work. - -### Here's a guide on how to get setup with PSQL: - -PostgreSQL Setup For Windows & WSL/Ubuntu -
    - -If you follow this guide to a tee… you will install PostgreSQL itself on your Windows installation. Then, you will…
    - -### Here's a Cheatsheet I made: - -Postgresql Cheat Sheet -
    - -PostgreSQL commandsmedium.com
    - ---- - -### Inserting Data into a Database - -### Create a Table - -The CREATE TABLE statement creates a new table in a database. You can use this command to specify what columns should appear in a database and the types of those columns. - -### Insert a Record - -The INSERT INTO statement inserts a new row into a database. Depending on the structure of a table, this statement can be used to insert some or all the values into a record. - -### Selecting Data from a Database - -### Selecting Data - -The SELECT statement selects data from one or more tables. It can be used to retrieve all the rows in a table or only rows that meet a set of conditions. You can filter out what columns will be returned by the SELECT statement. - -### Where Statement - -The WHERE statement allows you to select a record based on a condition. - -For instance, you could select all of the names in an Employees table that start with the letter "B". You could select all the people in an Employees table who have worked for a business for at least four years. - -### Ordering Data - -The ORDER BY clause sorts data by a particular column name. It can be used to sort data in either ascending or descending order. - -You could sort a list of employees in ascending order based on the day they were hired. You could sort a list of coffee products by their prices in descending order. - -### Limiting Data - -SQL databases can contain a lot of records. The LIMIT clause allows you to limit how many rows are returned by a query. For instance, you could return only the first five responses from a particular query. - -### Query Values Using Between - -The BETWEEN operator allows you to select records where a column value is within a particular range. For instance, you could use BETWEEN to retrieve a list of employees who work at a business and who earn between $20,000 and $30,000. You could use BETWEEN to retrieve a list of all the coffees at a cafe which cost between $2.00 and $2.50. - -### Updating a Database - -Updating a database allows you to modify the information you have already stored, and you can do so by doing the following: - -### Updating Records - -The UPDATE statement amends the contents of a table. This statement will change all the values in a database that meet a particular condition or set of conditions. You can use a WHERE statement to select which values should be updated. - -### Deleting Records - -The DELETE statement removes one or more rows from a table. By default, this command deletes all the records in a table. The DELETE statement is usually used with a WHERE statement so that only particular records are deleted. - -_The SQL ALTER TABLE statement adds, changes, or removes a column in a table. This statement lets you modify a table after it has been created, even if the table stores records._ - -You may decide that you need to make a change to an SQL table. For instance, you may want to rename a column or add a new column to the table. These changes are all possible with the SQL ALTER TABLE command. - -
    ### SQL ALTER TABLE - -The ALTER TABLE command allows you to change an existing table by: - -- Adding a column. -- Adding a constraint. -- Removing a column. -- Changing a data type. -- Renaming a column. - -_There is no SQL ADD COLUMN statement. To add a column to an SQL table, you must use the ALTER TABLE ADD syntax. ALTER TABLE lets you add, delete, or modify columns in a table._ - -After you have created a table in _SQL_, you may realize that you forgot to add in a specific column that you need. For example, say you may have created a database to store a list of suppliers. Maybe you forgot to include a field to store the category of goods the supplier offers. - -In these situations, you can use the _SQL ALTER TABLE_ statement to amend an existing table. This statement allows you to add a column, change a column, or delete a column. - -Below is an _SQL_ command that will create an employee database that stores three columns. This database stores name of an employee, their title, and the branch for which they work. - - CREATE TABLE employees ( - name VARCHAR(50) NOT NULL, - title VARCHAR(75) NOT NULL, - branch VARCHAR(25) NOT NULL - ); - -But what if we've forgotten to add a column? Say we need to add a column that states whether an employee is on probation. That's where the _ALTER TABLE_ statement comes in. - -### SQL Add Column - -To perform an SQL add column operation, use the ALTER TABLE ADD command. This command alters a table and adds in a column with the specified data type. Using this command, you can add a column to a table after you have created the table. - -### SQL UNION: - -When you're querying a database, you may want to combine the result of two or more `SELECT` statements. For example, you may want to get a list of the cities in which your customers are based, and the cities in which your business has branches. You could run two queries to achieve this goal, but you may want to have a result in one query. - -That's where the `SQL UNION` operator comes in. The `UNION` clause can be used to combine the results of two or more `SELECT` queries into a single result set. - -In this tutorial, we are going to break down the basics of the `SQL UNION` operator and discuss where you may want to use this command when you're working with a database. - -### Query Refresher - -Programmers use queries to retrieve information from a database. Queries almost always begin with the `SQL SELECT` statement and are used to retrieve data based on a set of criteria. Queries usually include the `FROM` operator, which states which table will be queried, among other operators that can filter the resulting data. - -Here is the general syntax for an `SQL` query: - - SELECT column_name FROM table_name WHERE your_condititions_are_met; - -Here's an example of an `SQL` query that returns a list of all employee names: - - SELECT name FROM employees; - -The output from our query is as follows: - -nameLuke -Mike -Hannah -Geoff -Alexis -Emma -Jonah - -(7 rows) - -If you want to retrieve information from multiple columns, you can so do by separating the column names with a comma. If you want to get data from every column, you can use an asterisk (`*`) instead, which represents every column in a table. - -» MORE: SQL Outer Join - -### SQL Union - -The `SQL UNION` operator can be used to combine the results of two or more queries into a single response that results in one table. - -In order to use the `UNION` operator, two conditions must be met. Firstly, the data types of the new columns should be compatible—if a salary is an integer in one table and a float in the other, the union would not work. Secondly, the number and order of the columns must be the same in your queries. - -Here's the syntax for an `SQL UNION` query: - - SELECT column_name FROM table1_name - UNION SELECT column_name FROM table2_name; - -Let's use an example to illustrate how the `SQL UNION` operator works. Let's say that we are a business that needs to send an announcement to all of our customers. We also want all employees to be sent this announcement so they are aware of what is going on. - -### SQL Aggregate Functions: - -SQL aggregate functions collate information about what is in a database. For instance, you can use SUM to find the total of all the values in a column. Aggregate functions save you time when you need to find out information that involves aggregating records., - -Here is a list of the aggregate functions in SQL you can use: - -- COUNT -- SUM -- AVG -- MIN -- MAX - -Let's walk through each of these individually. We're going to be referring to a database of employees throughout this tutorial. - -Aggregate functions are used at the beginning of the SQL SELECT statement. - -If you query both a column and an aggregate function in the same SELECT statement, you must use an SQL GROUP BY clause. This clause tells SQL how to represent the data in your query. - -### SQL Subquery - -_An SQL subquery is a query inside another query. It is used in the WHERE or HAVING clause of an SQL statement. Subqueries let you specify the results of one query as an argument in another query._ - -When you're writing an _SQL_ query, you may want to specify a parameter based on the result of another query. For example, say you have a list of customers. You may want to get a list of customers who have placed orders worth a value over a certain amount. Order and customer information is stored within a different table. - -That's where the _SQL subquery_ operation comes in. _Subqueries_, also known as nested queries, are _SELECT_ queries within the _WHERE_ clause of another _SQL_ query. The main _SQL_ query then uses the result of the subquery. - ---- - -### SQL query examples - -Now let's explore some examples of common and useful PostgreSQL queries that can be used in various situations. - -From PSQL DOCS: - -### 1. CREATE TABLE query in PostgreSQL - -### CREATE TABLE is a keyword that will create a new, initially empty table in the database. The table will be owned by the user who has issued this command. - - postgres=# create table dummy_table(name varchar(20),address text,age int); - CREATE TABLE - -### 2. INSERT query in PostgreSQL - -The INSERT command is used to insert data into a table: - - postgres=# insert into dummy_table values('XYZ','location-A',25); - INSERT 0 1 - postgres=# insert into dummy_table values('ABC','location-B',35); - INSERT 0 1 - postgres=# insert into dummy_table values('DEF','location-C',40); - INSERT 0 1 - postgres=# insert into dummy_table values('PQR','location-D',54); - INSERT 0 1 - -### 3. SELECT query without WHERE condition in PostgreSQL - -The SELECT command (when used without the optional WHERE condition) is used to fetch all data from a database table: - - postgres=# select * from dummy_table; - name | address | age - ---------+--------------+ ----- - XYZ | location-A | 25 - ABC | location-B | 35 - DEF | location-C | 40 - PQR | location-D | 54 - (4 rows) - -### 4. UPDATE query in PostgreSQL - -UPDATE is used to make updates to the data or row(s) of a database table. In the example below we use UPDATE to change the age of a person whose name is 'PQR': - - postgres=# update dummy_table set age=50 where name='PQR'; - UPDATE 1 - postgres=# select * from dummy_table; - name | address | age - --------+--------------+------- - XYZ | location-A | 25 - ABC | location-B | 35 - DEF | location-C | 40 - PQR | location-D | 50 - (4 rows) - -Next, we'll use the UPDATE command to change the name and age of a person whose address is 'location-D': - - postgres=# update dummy_table set name='GHI',age=54 where address='location-D'; - UPDATE 1 - postgres=# select * from dummy_table; - name | address | age - ------+------------+----- - XYZ | location-A | 25 - ABC | location-B | 35 - DEF | location-C | 40 - GHI | location-D | 54 - (4 rows) - - postgres=# - -If we want to modify all the values in the address and age columns in dummy_table, then we do not need to use the WHERE clause. The UPDATE query would look like this: - - postgres=# update dummy_table set age=54,address='location-X'; - UPDATE 4 - - - postgres=# select * from dummy_table ; - name | address | age - ------+------------+-------- - XYZ | location-X | 54 - ABC | location-X | 54 - DEF | location-X | 54 - GHI | location-X | 54 - (4 rows) - - postgres=# - -A RETURNING clause returns the updated rows. This is optional in UPDATE: - - postgres=# update dummy_table set age=30 where name='XYZ' returning age as age_no; - age_no - --------- - 30 - (1 row) - - UPDATE 1 - -It is always recommended to perform such operations under transaction blocks (i.e., BEGIN...COMMIT/ROLLBACK;), so we have the option to roll back the operation. - -### 5. DELETE query in PostgreSQL - -The DELETE command is used to delete row(s). It can be used with or without the optional WHERE condition, but take note: if the WHERE condition is missing, the command will delete all rows, leaving you with an empty table. - -In this example, we are deleting one row whose age column has the value 65: - - postgres=# delete from dummy_table where age=65; - DELETE 1 - postgres=# - -### 6. Comparison Operators in PostgreSQL queries - -In PostgreSQL, with the help of comparison operators we can find results where the value in a column is not equal to the specified condition or value. - -### Less than or equal to query: - - postgres=# select * from dummy_table where age <=50; - name | address | age - ------+------------+----- - XYZ | location-A | 25 - ABC | location-B | 35 - DEF | location-C | 40 - PQR | location-D | 50 - (4 rows) - -### Greater than or equal to query: - - postgres=# select * from dummy_table where age>=50; - name | address | age - ------+------------+----- - PQR | location-D | 50 - (1 row) - -### Not equal to query: - - postgres=# select * from dummy_table where age<>50; - name | address | age - ------+------------+----- - XYZ | location-A | 25 - ABC | location-B | 35 - DEF | location-C | 40 - (3 rows) - -### Equal to query: - - postgres=# select * from dummy_table where age=50; - name | address | age - ------+------------+----- - PQR | location-D | 50 - (1 row) - -### 7. SELECT DISTINCT query in PostgreSQL - -The SELECT DISTINCT statement is used to return only distinct values from the table. It removes any duplicate values. - -### SELECT query without DISTINCT clause - - postgres=# select age from dummy_table order by 1; - age - ----- - 1 - 1 - 2 - 2 - 3 - (5 rows) - -### SELECT query with DISTINCT clause - - postgres=# select distinct age from dummy_table order by 1; - age - ----- - 1 - 2 - 3 - (3 rows) - -### 8. TRUNCATE query in PostgreSQL - -The TRUNCATE command is used to empty a table: - - postgres=# truncate table dummy_table; - TRUNCATE TABLE - -### 9. DROP TABLE query in PostgreSQL - -This DROP TABLE command is used to drop a table from the database: - - postgresql=# drop table if exists dummy; - NOTICE: table "dummy" does not exist, skipping - DROP TABLE - -This command has removed the full table, including any associated data, indexes, rules, triggers, and constraints for that table. - -### 10. CREATE VIEW query in PostgreSQL - -The CREATE VIEW command is used to generate views. Views are pseudo-tables, which are used to present a full table, subset, or select columns from the underlying table: - - postgres=# create or replace view vi as select * from dummy_table where age is NULL; - CREATE VIEW - -### 11. Create a table in Postgresql using the SELECT statement - -Using the syntax in the example below, we can create a table using a SELECT statement: - - postgres=# select 'My name is X' as col1 , 10 as col2, 'Address is -XYZ location' as col3 into new_table; - SELECT 1 - postgres=# select * from new_table ; - col1 | col2 | col3 - ---------------+------+-------------------------- - My name is X | 10 | Address is -XYZ location - (1 row) - -### 12. Query timeout in PostgreSQL - -We can command a query to timeout after a certain period with the help of GUC parameters (short for grand unified configuration) like statement_timeout, which aborts any statement that takes more than the specified number of milliseconds: - - postgresql=# set statement_timeout=10; - SET - postgresql=# select pg_sleep(20); - ERROR: canceling statement due to statement timeout - -### 13. Using CREATE SEQUENCE with the INSERT query in PostgreSQL - -The CREATE SEQUENCE command is a sequential number generator. Once the sequence is created, we can use the sequence's nextval and currval functions to insert values into a table: - - postgres=# create sequence seq; - CREATE SEQUENCE - postgres=# create table tab(n int); - CREATE TABLE - postgres=# insert into tab values (nextval('seq')); - INSERT 0 1 - postgres=# insert into tab values (currval('seq')); - INSERT 0 1 - postgres=# insert into tab values (nextval('seq')); - INSERT 0 1 - postgres=# select * from tab; - n - --- - 1 - 1 - 2 - (3 rows) - -### 14. Importing BLOB data types into PostgreSQL - -PostgreSQL doesn't directly support BLOBs (binary large objects), but we can work with them using the following methods: - -Let's assume you have an image (in png format) downloaded in the /home/edb/ folder: - - [edb@localhost]$ ls /home/edb/mypic.png - /home/edb/mypic.png - -We want to store this image in the PostgreSQL database. - -Go to the bin folder of your PostgreSQL installation and connect to the psql terminal: - - postgres=# Create table testing(n int,n1 oid); - CREATE TABLE - postgres=# insert into testing values (1,lo_import('/home/edb/mypic.png')); - INSERT 0 1 - -The lo_import() function loads the named file into pg_largeobject and returns an OID (object identifier) value that will refer to the large object. Selecting the testing table will show just the OID and not the bits that have made up this photo. - -### 15. ILIKE query in PostgreSQL - -The ILIKE operator is a matching function similar to the LIKE operator, but with the advantage that it matches valus case-insensitively. - - postgres=# select * from ted; - n - ----- - TAR - TaR - Tar - tar - (4 rows) - -### Using ILIKE in a WHERE condition - - postgres=# select * from ted where n ilike 'TAR%'; - n - ----- - TAR - TaR - Tar - tar - (4 rows) - -### 16. Hierarchical queries in PostgreSQL - -Hierarchical queries are ones where the results have a structured or parent-child relationship and are displayed in a tree structure. To see how hierarchical queries work, create a dummy table: - - create table test_table( - emp_no int, - ename char(5), - job char(9), - manager_no int - ); - -Insert data into 'test_table': - - insert into test_table values(10,'A1','CEO',null); - insert into test_table values(11, 'B1', 'VP', 10); - insert into test_table values(12, 'B2', 'VP', 10); - insert into test_table values(13, 'B3', 'VP', 10); - insert into test_table values(14, 'C1', 'DIRECTOR', 13); - insert into test_table values(15, 'C2', 'DIRECTOR', 13); - insert into test_table values(16, 'D1', 'MANAGER', 15); - insert into test_table values(17 ,'E1', 'ENGINEER', 11); - insert into test_table values(18, 'E2', 'ENGINEER', 11); - -We can perform hierarchical queries on this table using the methods below. - -### 17. Length function in PostgreSQL - -The length function returns the number of characters or number of bytes in a specified string variable. - -### Basic SELECT query - - postgres=# select name,age from dummy_table; - name | age - ------+----- - XYZ | 25 - ABC | 35 - DEF | 40 - PQR | 54 - PQR | - (5 rows) - -### Query with length function for column name and age - - postgres=# select length(name),length(age) from dummy_table; - length | length - --------+-------- - 3 | 2 - 3 | 2 - 3 | 2 - 3 | 2 - 3 | - (5 rows) - -### 18. When a query has no destination for result data in PostgreSQL - -Say that while selecting a given function, we receive the error message below: - - postgresql=# create or replace function f(n int) - returns int - as - $$ - begin - select now(); - return 1; - end; - $$ language 'plpgsql'; - CREATE FUNCTION - postgres=# select f(9); - ERROR: query has no destination for result data - HINT: If you want to discard the results of a SELECT, use PERFORM instead. - -To avoid such errors, we can either use PERFORM or declare a variable and use it in a SELECT INTO statement: - -### Using PERFORM - - postgres=# create or replace function f(n int) - returns int - as - $$ - begin - perform - now(); - return 1; - end; - $$ language 'plpgsql'; - CREATE FUNCTION - postgresql=# select f(9); - f - --- - 1 - (1 row) - -### Declaring a variable and using it in a SELECT INTO statement - - postgres=# create or replace function f(n int) - returns int - as - $$ - declare - a date; - begin - select now() into a; - raise notice '%s',a; - return 1; - end; - $$ language 'plpgsql'; - CREATE FUNCTION - - - postgresql=# select f(9); - NOTICE: 24-SEP-20 13:15:46.23388s - f - --- - 1 - (1 row) - -### 19. Exporting query result to a text file in PostgreSQL - -With the help of the COPY command, we can export data from a table to an outside text file as well as import data from a text file into a table. - -### Exporting data from a table to a text file - - postgres=# copy dummy_table to '/tmp/abc.txt'; - COPY 5 - - postgres=# \! cat /tmp/abc.txt - XYZ location-A 25 - ABC location-B 35 - DEF location-C 40 - PQR location-D 50 - CXC 1 50 - -### Importing data from a text file into a table - - postgres=# copy dummy_table from '/tmp/abc.txt'; - COPY 5 - -- With the help of common table expressions (CTE): - - - - postgres=#WITH RECURSIVE cte AS ( SELECT emp_no, ename, manager_no, 1 AS level FROM test_table where manager_no is null UNION ALL SELECT e.emp_no, e.ename, e.manager_no, c.level + 1 FROM cte c JOIN test_table e ON e.manager_no = c.emp_no ) SELECT * FROM cte; emp_no | ename | manager_no | level -----------+----------+------------------+------- 10 | A1 | | 1 11 | B1 | 10 | 2 12 | B2 | 10 | 2 13 | B3 | 10 | 2 14 | C1 | 13 | 3 17 | E1 | 11 | 3 18 | E2 | 11 | 3 15 | C2 | 13 | 3 16 | D1 | 15 | 4 (9 rows) postgres=# - -- Using the tablefunc extension: - -1. The tablefunc extension is a contrib module that resides in the contrib/ folder in PostgreSQL sources. -2. First, create the tablefunc extension: - -- `postgres=# CREATE EXTENSION tablefunc; CREATE EXTENSION postgres=#` - -1. Then, use tablefunc's connectby function to display results hierarchically: - - - - postgres=# SELECT * FROM connectby('dummy_table', 'emp_no', 'manager_no', '10', 0, '->') AS t(emp_no int, manager_no int, level int, ord text) order by emp_no; emp_no | manager_no | level | ord --------+------------+-------+---------------- 10 | | 0 | 10 11 | 10 | 1 | 10->11 12 | 10 | 1 | 10->12 13 | 10 | 1 | 10->13 14 | 13 | 2 | 10->13->14 15 | 13 | 2 | 10->13->15 16 | 15 | 3 | 10->13->15->16 17 | 11 | 2 | 10->11->17 18 | 11 | 2 | 10->11->18 (9 rows) postgres=# - -### 20. Listing databases query in PostgreSQL - -The following query can be used to show all the databases created: - - postgres=# select oid,datname from pg_database; - oid | datname - -----------+----------- - 13743 | postgres - 1 | template1 - 13742 | template0 - (3 rows) - -We can also list out all the database names using the \\l command at the psql prompt. - -### 21. Checking query execution time in PostgreSQL - -We can check the time needed for a query to execute by enabling \\timing at the psql prompt: - - postgres=# \timing - Timing is on. - -The SELECT query will now show the execution time: - - postgres=# select * from dummy_table; - name | address | age - ------+------------+-------- - XYZ | location-A | 25 - ABC | location-B | 35 - DEF | location-C | 40 - PQR | location-D | 50 - CXC | 1 | 50 - (5 rows) - - Time: 0.440 ms - postgres=# - -### 22. Dynamic SQL query in PostgreSQL - -Dynamic SQL is used to reduce repetitive tasks when it comes to querying. -Dynamic SQL queries are not cached in memory. - - postgres=# do - postgres-# $$ - postgres$# begin - postgres$# execute 'select * from dummy_table'; - postgres$# end; - postgres$# $$; - DO - -### 23. COUNT query in PostgreSQL - -The COUNT query returns the number of rows in a table. If we use (\*) this will include null values; otherwise null values will be excluded. - - postgres=# select count(*) from dummy_table; - count - ------- - 5 - (1 row) - - postgres=# select count(avg) from dummy_table; - count - ------- - 4 - (1 row) - -### 24. LIMIT and OFFSET query in PostgreSQL - -The LIMIT clause is used to limit the data amount returned by the SELECT statement. The query below will display only 1 row: - - postgres=# select * from dummy_table limit 1; - name | address | age - ------+------------+----- - XYZ | location-A | 25 - (1 row) - -OFFSET is used when we want to skip a particular number of rows: - - postgres=# select * from dummy_table offset 4; - name | address | age - ------+---------+----- - cxc | 1 | 50 - (1 row) - -### 25. IF … ELSE expression in PostgreSQL - -We can use conditional statements like IF ... ELSE in an anonymous block. The example below checks if the values of variables abc and xyz are matching and prints the result— i.e., 150: - - postgres=# Do - $$ - Declare - abc int; - xyz int; - begin - abc:=100; - xyz:=abc; - if abc=xyz then - xyz=150; - raise notice '%',xyz; - else - end if; - end; - $$ - ; - NOTICE: 150 - DO - -### 26. UPDATE with JOIN query in PostgreSQL - -We can use UPDATE with a JOIN and WHERE clause when we want to update the values from one table (table X) based on values from another table (table Y): - - postgres=# create table X(n int, n1 char(10)); - CREATE TABLE - postgres=# insert into X values (1,'abc'); - INSERT 0 1 - postgres=# insert into X values (2,'xyz'); - INSERT 0 1 - postgres=# insert into X values (3,'pqr'); - INSERT 0 1 - - postgres=# create table Y(n int, n1 char(10)); - CREATE TABLE - - postgres=# insert into Y values (1,''); - INSERT 0 1 - postgres=# insert into Y values (2,''); - INSERT 0 1 - - postgres=# insert into Y values (5,'axyz'); - INSERT 0 1 - - postgres=# update Y set n1=X.n1 from X where X.n=Y.n; - UPDATE 2 - postgres=# select * from Y; - n | n1 - ---+------------ - 5 | axyz - 1 | abc - 2 | xyz - (3 rows) - - postgres=# - -### 27. INNER JOIN query in PostgreSQL - -The INNER JOIN command will find rows from two (or more) tables where the specified columns data in the tables match: - - postgres=# select * from x inner join y on x.n1 = y.n1; - n | n1 | n | n1 - ---+------------+---+------------ - 1 | abc | 1 | abc - 2 | xyz | 2 | xyz - (2 rows) - - postgres=# - -### 28. CASE expression in PostgreSQL - -The CASE expression is a generic conditional expression, similar to the IF … ELSE statement. - - postgres=# SELECT age, - CASE age WHEN 25 THEN 'one' - WHEN 50 THEN 'two' - ELSE 'other' - END - FROM dummy_table; - age | case - -----+------- - 25 | one - 35 | other - 40 | other - 50 | two - 50 | two - (5 rows) - -### 29. PostgreSQL recursive query - -Recursive queries are used to deal with hierarchical queries or tree-structured data. The structure of a WITH RECURSIVE query is always: a) Non-recursive term - b) UNION (or UNION ALL), then a recursive term - -where the recursive term includes a reference to the query's output. - - CREATE TABLE emp_test ( - id int, - ename varchar(255), - emanager int - ); - - INSERT INTO emp_test VALUES (1, 'abc', null); - INSERT INTO emp_test VALUES (2, 'xyz', 1); - INSERT INTO emp_test VALUES (3, 'def', 2); - INSERT INTO emp_test VALUES (4, 'cde', 1); - INSERT INTO emp_test VALUES (5, 'qrs', 2); - INSERT INTO emp_test VALUES (9, 'iop', 3); - INSERT INTO emp_test VALUES (10, 'klm', 4); - -The recursive query below will give all the reports in a certain order: - - postgres=#WITH RECURSIVE emp_testnew AS ( - SELECT id, ename, emanager - FROM emp_test - WHERE id = 2 - UNION ALL - SELECT e.id, e.ename, e.emanager - FROM emp_test e - INNER JOIN emp_testnew e1 ON e1.id = e.emanager - ) - SELECT * - FROM emp_testnew; - - id | ename | emanager - ----+-------+---------- - 2 | xyz | 1 - 3 | def | 2 - 5 | qrs | 2 - 9 | iop | 3 - (4 rows) - - postgres=# - -### 30. PostgreSQL log queries - -Using the pg_stat_statements module, we can track execution statistics for all SQL statements. To do this, we need to create an extension and add in shared_preload_libraries inside the postgresql.conf file: - - postgres=# create extension pg_stat_statements; - CREATE EXTENSION - - - postgres=# show shared_preload_libraries ; - shared_preload_libraries - ------------------------------------------------- - $libdir/pg_stat_statements - (1 row) - - - postgres=# select query from pg_stat_statements where query like 'create table%'; - -[ RECORD 1 ]------------------- - query | create table test(n int) - -We can also configure PostgreSQL to generate log output by enabling these parameters in the postgresql.conf file: - - logging_collector = on - log_directory = 'log' - log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log' - log_destination = 'stderr' - Log file will be created under the pg_log directory which resides under the data folder. - - [centos@tushar-ldap-docker bin]$ ls data/log - postgresql-2020-09-17_150932.log postgresql-2020-09-19_000000.log - [centos@tushar-ldap-docker bin]$ - -Queries will be recorded in these files. - -### 31. Using a variable in a PostgreSQL query - -We can declare a variable in PostgreSQL at the psql prompt: - - postgres=# \set cond 50 - -### Using a variable in a WHERE condition - - postgres=# select * from dummy_table where age=:cond; - name | address | age - ------+------------+----- - PQR | location-D | 50 - (1 row) - -OR - - postgres=# \set cond 50 - postgres=# select :cond+100 ; - ?column? - ---------- - 150 - (1 row) - -### 32. Date query in PostgreSQL - -PostgreSQL offers functions for date and time that can be used in queries. - - postgres=# select now(); - now - ---------------------------------- - 22-SEP-20 03:08:42.636385 +05:30 - (1 row) - - postgres=# select current_date; - current_date - -------------- - 22-SEP-20 - (1 row) - - postgres=# select current_time; - current_time - ----------------------- - 03:08:53.648466+05:30 - (1 row) - -We can also perform a date range query to find rows with values between two time stamps: - - postgres=# create table datetable(n int,n1 date); - CREATE TABLE - - postgres=# insert into datetable values (1,'12-01-1980'); - INSERT 0 1 - postgres=# insert into datetable values (2,'12-01-2020'); - INSERT 0 1 - postgres=# insert into datetable values (3,'12-01-2000'); - INSERT 0 1 - postgres=# select * from datetable where n1 between '12-01-1980' and '12-01-2000'; - n | n1 - ---+-------------------- - 1 | 12-JAN-80 00:00:00 - 3 | 12-JAN-00 00:00:00 - (2 rows) - -### 33. PostgreSQL function RETURN QUERY result - -When a PL/pgSQL function is declared to return a SETOF some data type, the return is specified by a RETURN QUERY command: - - postgres=# CREATE FUNCTION get(int) RETURNS SETOF integer AS - $BODY$ - BEGIN - RETURN QUERY SELECT age - FROM dummy_table - WHERE age >= $1 ; - RETURN; - END - $BODY$ - LANGUAGE plpgsql; - - - postgres=# select * from get(9); - get - ----- - 25 - 35 - 40 - 50 - (4 rows) - -### 34. PostgreSQL parallel query performance - -Parallel queries in PostgreSQL allow you to finish queries faster by utilizing many CPUs. These GUCs parameters are set in postgresql.conf file: - - #max_parallel_maintenance_workers = 2 # taken from max_parallel_workers - #max_parallel_workers_per_gather = 2 # taken from max_parallel_workers - #parallel_leader_participation = on - #max_parallel_workers = 8 # maximum number of max_worker_processes that - # can be used in parallel operations - - - postgres=# create table ty(n int); - CREATE TABLE - postgres=# insert into ty values (generate_series(1,300000)); - INSERT 0 300000 - - postgres=# analyze ty; - ANALYZE - postgres=# explain select * from ty where n<=1; - QUERY PLAN - --------------------------------------------------------------------- - Gather (cost=1000.00..4536.88 rows=30 width=4) - Workers Planned: 1 - -> Parallel Seq Scan on ty (cost=0.00..3533.88 rows=18 width=4) - Filter: (n <= 1) - (4 rows) - - postgres=# - -### 35. Logical operators in PostgreSQL - -There are three basic logical operators available in PostgreSQL: AND, OR, and NOT. - -These operators are used to match conditions in SQL statements—e.g., in WHERE and HAVING clauses. - - AND = when both boolean expressions are true then it will return TRUE - OR = when any boolean expression is true then it will return TRUE - NOT = reverses the value of Boolean operator - -### Some logical operator examples - - If both expressions are true, then the result is TRUE. postgresql=# select 1=1/1 and 200=2+198 as result_and_operator; result_and_operator --------------------- t (1 row) postgresql=# - - If one expression is true and another expression is NULL, then the result is NULL. postgresql=# select 4=4 and null; ?column? ---------- (1 row) - If one expression is true and another expression is false, then the result is TRUE. postgres=# select 1=100 OR 2=2; ?column? ---------- t (1 row) - -### 36. Catching duplicate rows in a PostgreSQL table - -In the following SQL query, there are two records with the value 50: - - postgres=# select age from dummy_table; - age - ----- - 25 - 35 - 40 - 50 - 50 - (5 rows) - -We can use the following SELECT … HAVING query to find the duplicate rows: - - postgres=# select age, count(age) from dummy_table group by age having count(age)>1; - age | count - -----+------- - 50 | 2 - (1 row) - -### 37. Enum query in PostgreSQL - -Enumerated (enum) types are data types that comprise a static, ordered set of values. - - postgres=# CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy'); - CREATE TYPE - postgres=# create table testi(n int, n1 mood); - CREATE TABLE - postgres=# insert into testi values (1,'happy'); - INSERT 0 1 - postgres=# insert into testi values (1,'sad'); - INSERT 0 1 - postgres=# insert into testi values (1,'ok'); - INSERT 0 1 - -If the enum has not been specified, it will give an error: - - postgres=# insert into testi values (1,'happyo'); - ERROR: invalid input value for enum mood: "happyo" - -### 38. Pivot query in PostgreSQL - -A pivot table is a useful way to analyze large quantities of data by organizing it into a more manageable format. - - CREATE TABLE newtb(id SERIAL, rowid varchar(10), attri varchar(10), val varchar(10)); - INSERT INTO newtb(rowid, attri, val) values('t1','a1','v1'); - INSERT INTO newtb(rowid, attri, val) values('t1','a2','v2'); - INSERT INTO newtb(rowid, attri, val) values('t1','a3','v3'); - INSERT INTO newtb(rowid, attri, val) values('t1','a4','v4'); - INSERT INTO newtb(rowid, attri, val) values('t2','a1','v5'); - INSERT INTO newtb(rowid, attri, val) values('t2','a2','v6'); - INSERT INTO newtb(rowid, attri, val) values('t2','a3','v7'); - INSERT INTO newtb(rowid, attri, val) values('t2','a4','v8'); - -To create a pivot table you need to install the tablefunc extension: - - postgres=# create extension tablefunc; - CREATE EXTENSION - - Select * - FROM crosstab( - 'select rowid, attri, val - from newtb - where attri = ''a2'' or attri = ''a3'' - order by 1,2') - AS newtb(row_name varchar(10), category_1 varchar(10), category_2 varchar(10), category_3 varchar(10)); - row_name | category_1 | category_2 | category_3 - ----------+------------+------------+-------------------------- - t1 | v2 | v3 | - t2 | v6 | v7 | - (2 rows) - -### 39. SELF JOIN query in PostgreSQL - -When we join a table against itself, this is called a SELF JOIN. This can be done using INNER JOIN or LEFT JOIN. SELF JOINs are useful when comparing the columns of rows within the same table: - - postgres=# create table emp1(emp_id int, firstname char(10), lastname char(10) , manager_id int); - CREATE TABLE - postgres=# - postgres=# - postgres=# insert into emp1 values(1,'ABC','XYZ',NULL); - INSERT 0 1 - postgres=# insert into emp1 values(2,'TYU','BGV',1); - INSERT 0 1 - postgres=# insert into emp1 values(3,'TEU','ZZV',1); - INSERT 0 1 - postgres=# insert into emp1 values(4,'REU','AZV',2); - INSERT 0 1 - postgres=# insert into emp1 values(5,'QREU','WZV',2); - INSERT 0 1 - postgres=# insert into emp1 values(6,'DREU','QZV',3); - INSERT 0 1 - - - postgres=# select a.firstname,b.lastname from emp1 a inner join emp1 b on a.emp_id=b.manager_id order by 1 ; - firstname | lastname - ------------+------------ - ABC | ZZV - ABC | BGV - TEU | QZV - TYU | WZV - TYU | AZV - (5 rows) - - postgres=# - -### 40. Parent-child recursive query in PostgreSQL - -With the help of common table expressions (CTE) we can perform parent-child recursive queries: - - postgres=# CREATE TABLE recu_pc ( - id SERIAL PRIMARY KEY, - name varchar(10) NOT NULL, - parent_id integer ); - CREATE TABLE - - postgres=# insert into recu_pc values (1, 'Grandmother', NULL); - INSERT 0 1 - postgres=# insert into recu_pc values (2, 'mother', 1); - INSERT 0 1 - postgres=# insert into recu_pc values (3, 'daughter', 2); - INSERT 0 1 - - - postgres=# WITH RECURSIVE rec_q (id) as - ( - SELECT recu_pc.id, recu_pc.name from recu_pc where name='mother' - UNION ALL - SELECT recu_pc.id, recu_pc.name from rec_q, recu_pc where recu_pc.parent_id = rec_q.id - ) - SELECT * - FROM rec_q; - id | name - ----+---------- - 2 | mother - 3 | daughter - (2 rows) - -### 41. Defining a variable in a query in PostgreSQL - -Using an anonymous block, we can define a variable that can be passed to in a query: - - postgres=# do - $$ - declare - a int; - begin - select age into a from dummy_table - where name ='XYZ'; - raise notice '%',a; - end; - $$; - NOTICE: 25 - DO - -### 42. PREPARE statement in PostgreSQL - -A prepared statement is used to optimize performance. When the PREPARE statement is executed, it is not only parsed but analyzed too, and when we fire the EXECUTE command the prepared statement is planned and executed. - -Prepared statements can accept parameters. - - postgres=# prepare test(int) as - select * from dummy_table where age=$1; - PREPARE - - postgres=# execute test(50); - name | address | age - ------+------------+--------- - PQR | location-D | 50 - CXC | 1 | 50 - (2 rows) - -### 43. Checking NULL values in PostgreSQL - -To Identify or select rows that have NULL values, the IS NULL condition can be used in the WHERE clause. - - postgres=# select * from dummy_table; - name | address | age - ------+------------+----- - XYZ | location-A | 25 - ABC | location-B | 35 - DEF | location-C | 40 - PQR | location-D | 54 - PQR | location-D | - (5 rows) - -Identifying null values in 'age' column: - - postgres=# select name from dummy_table where age is null; - name - ------ - PQR - (1 row) - -### Sources: - -1. ) https://careerkarma.com/blog/sql-deep-dives/ -2. https://www.postgresql.org/docs/13/app-psql.html - -Learn More: - -Web-Dev-Hub -
    - -Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…bgoonz-blog.netlify.app
    - -### Further Examples / Readings: - -By Bryan Guner on [July 14, 2021](https://medium.com/p/19fba3e37110). - -Canonical link - -August 6, 2021. diff --git a/notes/articles/medium/markdown/PostgreSQL-Setup-For-Windows---WSL-Ubuntu.md b/notes/articles/medium/markdown/PostgreSQL-Setup-For-Windows---WSL-Ubuntu.md deleted file mode 100644 index 6328f08487..0000000000 --- a/notes/articles/medium/markdown/PostgreSQL-Setup-For-Windows---WSL-Ubuntu.md +++ /dev/null @@ -1,324 +0,0 @@ -# PostgreSQL Setup For Windows & WSL/Ubuntu - -If you follow this guide to a tee… you will install PostgreSQL itself on your Windows installation. Then, you will install psql in your… - ---- - -### PostgreSQL Setup For Windows & WSL/Ubuntu - -
    If you follow this guide to a tee… you will install PostgreSQL itself on your Windows installation. Then, you will install `psql` in your Ubuntu installation. Then you will also install Postbird, a cross-platform graphical user interface that makes working with SQL and PostgreSQL 'allegedly' …(personally I prefer to just use the command line but PG Admin makes for an immeasurably more complicated tutorial than postbird)… better than just using the **command line tool** `psql`**.** - -### Important Distinction: PSQL is the frontend interface for PostgreSQL … they are not synonymous! - -**Postgres**, is a free and open-source relational database management system (RDBMS) - -**PSQL:** - -The primary front-end for PostgreSQL is the `psql` command-line program, which can be used to enter SQL queries directly, or execute them from a file. - -In addition, psql provides a number of meta-commands and various shell-like features to facilitate writing scripts and automating a wide variety of tasks; for example tab completion of object names and SQL syntax. - -**pgAdmin:** - -The pgAdmin package is a free and open-source graphical user interface (GUI) administration tool for PostgreSQL. - -When you read "installation", that means the actual OS that's running on your machine. So, you have a Windows installation, Windows 10, that's running when you boot your computer. Then, when you start the Ubuntu installation, it's as if there's a completely separate computer running inside your computer. It's like having two completely different laptops. - -### Other Noteworthy Distinctions: - -
    ### Installing PostgreSQL 12 - -To install PostgreSQL 12, you need to download the installer from the Internet. PostgreSQL's commercial company, Enterprise DB, offers installers for PostgreSQL for every major platform. - -Open https://www.enterprisedb.com/downloads/postgres-postgresql-downloads. Click the link for PostgreSQL 12 for Windows x86-64. - -
    Once that installer downloads, run it. You need to go through the normal steps of installing software. - -- Yes, Windows, let the installer make changes to _my_ device. -- Thanks for the welcome. Next. -- Yeah, that's a good place to install it. Next. -- I don't want that pgAdmin nor the Stack Builder things. Uncheck. Uncheck. Next. - -
    - Also, great looking directory. Thanks. Next. - -### Oooh! A password! I'll enter **\*\*\*\***. I sure won't forget that because, if I do, I'll have to uninstall and reinstall PostgreSQL and lose all of my hard work. **Seriously, write down this password or use one you will not forget!!!!!!!!!!!!!!!** - -### I REALLY CANNOT STRESS THE ABOVE POINT ENOUGH… Experience is a great teacher but in this case … it's not worth it. - -- Sure. 5432. Good to go. Next. -- Not even sure what that means. Default! Next. -- Yep. Looks good. Next. - -Insert pop culture reference to pass the time - -### Installing PostgreSQL Client Tools on Ubuntu - -Now, to install the PostgreSQL Client tools for Ubuntu. You need to do this so that the Node.js (and later Python) programs running on your Ubuntu installation can access the PostgreSQL server running on your Windows installation. You need to tell `apt`, the package manager, that you want it to go find the PostgreSQL 12 client tools from PostgreSQL itself rather than the common package repositories. You do that by issuing the following two commands. Copy and paste them one at a time into your shell. (If your Ubuntu shell isn't running, start one.) - -**Pro-tip**: Copy those commands because you're not going to type them, right? After you copy one of them, you can just right-click on the Ubuntu shell. That should paste them in there for you. - - wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add - - -If prompted for your password, type it. - - echo "deb http://apt.postgresql.org/pub/repos/apt/ `lsb_release -cs`-pgdg main" | sudo tee /etc/apt/sources.list.d/pgdg.list - -The last line of output of those two commands running should read "OK". If it does not, try copying and pasting them one at a time. - -Now that you've registered the PostgreSQL repositories as a source to look for PostgreSQL, you need to update the `apt` registry. You should do this before you install _any_ software on Ubuntu. - - sudo apt update - -Once that's finished running, the new entries for PostgreSQL 12 should be in the repository. Now, you can install them with the following command. - - sudo apt install postgresql-client-12 postgresql-common - -If it asks you if you want to install them, please tell it "Y". - -Test that it installed by typing `psql --version`. You should see it print out information about the version of the installed tools. If it tells you that it can't find the command, try these instructions over. - -### Configuring the client tools - -Since you're going to be accessing the PosgreSQL installation from your Ubuntu installation on your Windows installation, you're going to have to type that you want to access it over and over, which means extra typing. To prevent you from having to do this, you can customize your shell to always add the extra commands for you. - -This assumes you're still using Bash. If you changed the shell that your Ubuntu installation uses, please follow that shell's directions for adding an alias to its startup file. - -Make sure you're in your Ubuntu home directory. You can do that by typing `cd` and hitting enter. Use `ls` to find out if you have a `.bashrc` file. Type `ls .bashrc`. If it shows you that one exists, that's the one you will add the alias to. If it tells you that there is no file named that, then type `ls .profile`. If it shows you that one exists, that's the one you will add the alias to. If it shows you that it does not exist, then use the file name `.bashrc` in the following section. - -Now that you know which profile file to use, type `code «profile file name»` where "profile file name" is the name of the file you determined from the last section. Once Visual Studio Code starts up with your file, at the end of it (or if you've already added aliases, in that section), type the following. - - alias psql="psql -h localhost" - -When you run `psql` from the command line, it will now always add the part about wanting to connect to _localhost_ every time. You would have to type that each time, otherwise. - -To make sure that you set that up correctly, type `psql -U postgres postgres`. This tells the `psql` client that you want to connect as the user "postgres" (`-U postgres`) to the database postgres (`postgres` at the end), which is the default database created when PostgreSQL is installed. It will prompt you for a password. Type the password that you used when you installed PostgrSQL, earlier. If the alias works correctly and you type the correct password, then you should see something like the following output. - - psql (12.2 (Ubuntu 12.2-2.pgdg18.04+1)) - Type "help" for help. - - postgres=# - -Type `\q` and hit Enter to exit the PostgreSQL client tool. - -Now, you will add a user for your Ubuntu identity so that you don't have to specify it all the time. Then, you will create a file that PostgreSQL will use to automatically send your password every time. - -Copy and paste the following into your Ubuntu shell. Think of a password that you want to use for your user. **Replace the password in the single quotes in the command with the password that you want.** It _has_ to be a non-empty string. PostgreSQL doesn't like it when it's not. - - psql -U postgres -c "CREATE USER `whoami` WITH PASSWORD 'password' SUPERUSER" - -It should prompt you for a password. Type the password that you created when you installed PostgreSQL. Once you type the correct password, you should see "CREATE ROLE". - -Now you will create your PostgreSQL password file. Type the following into your Ubuntu shell to open Visual Studio Code and create a new file. - - code ~/.pgpass - -In that file, you will add this line, which tells it that on localhost for port 5432 (where PostgreSQL is running), for all databases (\*), **use your Ubuntu user name and the password that you just created for that user with the** `psql` **command you just typed.** (If you have forgotten your Ubuntu user name, type `whoami` on the command line.) Your entry in the file should have this format. - - localhost:5432:*:«your Ubuntu user name»:«the password you just used» - -Once you have that information in the file, save it, and close Visual Studio Code. - -The last step you have to take is change the permission on that file so that it is only readable by your user. PostgreSQL will ignore it if just anyone can read and write to it. This is for _your_ security. Change the file permissions so only you can read and write to it. You did this once upon a time. Here's the command. - - chmod go-rw ~/.pgpass - -You can confirm that only you have read/write permission by typing `ls -al ~/.pgpass`. That should return output that looks like this, **with your Ubuntu user name instead of "web-dev-hub".** - - -rw------- 1 web-dev-hub web-dev-hub 37 Mar 28 21:20 /home/web-dev-hub/.pgpass - -Now, try connecting to PostreSQL by typing `psql postgres`. Because you added the alias to your startup script, and because you created your **.pgpass** file, it should now connect without prompting you for any credentials! Type `\q` and press Enter to exit the PostgreSQL command line client. - -### Installing Postbird - -Head over to the Postbird releases page on GitHub. Click the installer for Windows which you can recognize because it's the only file in the list that ends with ".exe". - -
    After that installer downloads, run it. You will get a warning from Windows that this is from an unidentified developer. If you don't want to install this, find a PostgreSQL GUI client that you do trust and install it or do everything from the command line. - -
    You should get used to seeing this because many open-source applications aren't signed with the Microsoft Store for monetary and philosophical reasons. - -Otherwise, if you trust Paxa like web-dev-hub and tens of thousands of other developers do, then click the link that reads "More info" and the "Run anyway" button. - -
    When it's done installing, it will launch itself. Test it out by typing the "postgres" into the "Username" field and the password from your installation in the "Password" field. Click the Connect button. It should properly connect to the running - -You can close it for now. It also installed an icon on your desktop. You can launch it from there or your Start Menu at any time. - -### Now.. if you still have some gas in the tank… let's put our new tools to work: - -### The node-postgres - -The node-postgres is a collection of Node.js modules for interfacing with the PostgreSQL database. It has support for callbacks, promises, async/await, connection pooling, prepared statements, cursors, and streaming results. - -In our examples we also use the Ramda library. See Ramda tutorial for more information. - -### Setting up node-postgres - -First, we install node-postgres. - -$ node -v -v14.2 - -$ npm init -y - -We initiate a new Node application. - -npm i pg - -We install node-postgres with `nmp i pg`. - -npm i ramda - -In addition, we install Ramda for beautiful work with data. - -cars.sql - -DROP TABLE IF EXISTS cars; - -CREATE TABLE cars(id SERIAL PRIMARY KEY, name VARCHAR(255), price INT); -INSERT INTO cars(name, price) VALUES('Audi', 52642); -INSERT INTO cars(name, price) VALUES('Mercedes', 57127); -INSERT INTO cars(name, price) VALUES('Skoda', 9000); -INSERT INTO cars(name, price) VALUES('Volvo', 29000); -INSERT INTO cars(name, price) VALUES('Bentley', 350000); -INSERT INTO cars(name, price) VALUES('Citroen', 21000); -INSERT INTO cars(name, price) VALUES('Hummer', 41400); -INSERT INTO cars(name, price) VALUES('Volkswagen', 21600); - -In some of the examples, we use this `cars` table. - -### The node-postgres first example - -In the first example, we connect to the PostgreSQL database and return a simple SELECT query result. - -first.js - - const pg = require('pg'); - const R = require('ramda'); - const cs = 'postgres://postgres:s$cret@localhost:5432/ydb'; - const client = new pg.Client(cs); - client.connect(); - client.query('SELECT 1 + 4').then(res => { - - const result = R.head(R.values(R.head(res.rows))) - - console.log(result) - }).finally(() => client.end()); - -The example connects to the database and issues a SELECT statement. - - const pg = require('pg'); - const R = require('ramda'); - -We include the `pg` and `ramda` modules. - - const cs = 'postgres://postgres:s$cret@localhost:5432/ydb'; - -This is the PostgreSQL connection string. It is used to build a connection to the database. - - const client = new pg.Client(cs); - client.connect(); - -A client is created. We connect to the database with `connect()`. - - client.query('SELECT 1 + 4').then(res => { - - const result = R.head(R.values(R.head(res.rows))); - - console.log(result); - - }).finally(() => client.end()); - -We issue a simple SELECT query. We get the result and output it to the console. The `res.rows` is an array of objects; we use Ramda to get the returned scalar value. In the end, we close the connection with `end()`. - - node first.js - 5 - -This is the output. - -### The node-postgres column names - -In the following example, we get the columns names of a database. - -> column_names.js - - const pg = require('pg'); - - const cs = 'postgres://postgres:s$cret@localhost:5432/ydb'; - - const client = new pg.Client(cs); - - client.connect(); - - client.query('SELECT * FROM cars').then(res => { - - const fields = res.fields.map(field => field.name); - - console.log(fields); - - }).catch(err => { - console.log(err.stack); - }).finally(() => { - client.end() - }); - -The column names are retrieved with `res.fields` attribute. We also use the `catch` clause to output potential errors. - - node column_names.js - 'id', 'name', 'price'′id′,′name′,′price′ - -The output shows three column names of the `cars` table. - -### Selecting all rows - -In the next example, we select all rows from the database table. - -> all_rows.js - - const pg = require('pg'); - const R = require('ramda'); - - const cs = 'postgres://postgres:s$cret@localhost:5432/ydb'; - - const client = new pg.Client(cs); - - client.connect(); - - client.query('SELECT * FROM cars').then(res => { - - const data = res.rows; - - console.log('all data'); - data.forEach(row => { - console.log(\`Id: ${row.id} Name: ${row.name} Price: ${row.price}\`); - }) - - console.log('Sorted prices:'); - const prices = R.pluck('price', R.sortBy(R.prop('price'), data)); - console.log(prices); - - }).finally(() => { - client.end() - }); - -**TBC…** - -#### If you found this guide helpful feel free to checkout my github/gists where I host similar content: - -bgoonz's gists · GitHub - -bgoonz — Overview -
    - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
    - -Or Checkout my personal Resource Site: - -Stackbit Web-Dev-HubTheme -
    - -Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…bgoonz-blog.netlify.app
    - -By Bryan Guner on [March 6, 2021](https://medium.com/p/801672ab7089). - -Canonical link - -August 31, 2021. diff --git a/notes/articles/medium/markdown/PostgreSQL-Setup-For-Windows---WSL.md b/notes/articles/medium/markdown/PostgreSQL-Setup-For-Windows---WSL.md deleted file mode 100644 index c25b857785..0000000000 --- a/notes/articles/medium/markdown/PostgreSQL-Setup-For-Windows---WSL.md +++ /dev/null @@ -1,324 +0,0 @@ -# PostgreSQL Setup For Windows & WSL/Ubuntu - -If you follow this guide to a tee… you will install PostgreSQL itself on your Windows installation. Then, you will install psql in your… - ---- - -### PostgreSQL Setup For Windows & WSL/Ubuntu - -
    If you follow this guide to a tee… you will install PostgreSQL itself on your Windows installation. Then, you will install `psql` in your Ubuntu installation. Then you will also install Postbird, a cross-platform graphical user interface that makes working with SQL and PostgreSQL 'allegedly' …(personally I prefer to just use the command line but PG Admin makes for an immeasurably more complicated tutorial than postbird)… better than just using the **command line tool** `psql`**.** - -### Important Distinction: PSQL is the frontend interface for PostgreSQL … they are not synonymous! - -**Postgres**, is a free and open-source relational database management system (RDBMS) - -**PSQL:** - -The primary front-end for PostgreSQL is the `psql` command-line program, which can be used to enter SQL queries directly, or execute them from a file. - -In addition, psql provides a number of meta-commands and various shell-like features to facilitate writing scripts and automating a wide variety of tasks; for example tab completion of object names and SQL syntax. - -**pgAdmin:** - -The pgAdmin package is a free and open-source graphical user interface (GUI) administration tool for PostgreSQL. - -When you read "installation", that means the actual OS that's running on your machine. So, you have a Windows installation, Windows 10, that's running when you boot your computer. Then, when you start the Ubuntu installation, it's as if there's a completely separate computer running inside your computer. It's like having two completely different laptops. - -### Other Noteworthy Distinctions: - -
    ### Installing PostgreSQL 12 - -To install PostgreSQL 12, you need to download the installer from the Internet. PostgreSQL's commercial company, Enterprise DB, offers installers for PostgreSQL for every major platform. - -Open https://www.enterprisedb.com/downloads/postgres-postgresql-downloads. Click the link for PostgreSQL 12 for Windows x86-64. - -
    Once that installer downloads, run it. You need to go through the normal steps of installing software. - -- Yes, Windows, let the installer make changes to _my_ device. -- Thanks for the welcome. Next. -- Yeah, that's a good place to install it. Next. -- I don't want that pgAdmin nor the Stack Builder things. Uncheck. Uncheck. Next. - -
    - Also, great looking directory. Thanks. Next. - -### Oooh! A password! I'll enter **\*\*\*\***. I sure won't forget that because, if I do, I'll have to uninstall and reinstall PostgreSQL and lose all of my hard work. **Seriously, write down this password or use one you will not forget!!!!!!!!!!!!!!!** - -### I REALLY CANNOT STRESS THE ABOVE POINT ENOUGH… Experience is a great teacher but in this case … it's not worth it. - -- Sure. 5432. Good to go. Next. -- Not even sure what that means. Default! Next. -- Yep. Looks good. Next. - -Insert pop culture reference to pass the time - -### Installing PostgreSQL Client Tools on Ubuntu - -Now, to install the PostgreSQL Client tools for Ubuntu. You need to do this so that the Node.js (and later Python) programs running on your Ubuntu installation can access the PostgreSQL server running on your Windows installation. You need to tell `apt`, the package manager, that you want it to go find the PostgreSQL 12 client tools from PostgreSQL itself rather than the common package repositories. You do that by issuing the following two commands. Copy and paste them one at a time into your shell. (If your Ubuntu shell isn't running, start one.) - -**Pro-tip**: Copy those commands because you're not going to type them, right? After you copy one of them, you can just right-click on the Ubuntu shell. That should paste them in there for you. - - wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add - - -If prompted for your password, type it. - - echo "deb http://apt.postgresql.org/pub/repos/apt/ `lsb_release -cs`-pgdg main" | sudo tee /etc/apt/sources.list.d/pgdg.list - -The last line of output of those two commands running should read "OK". If it does not, try copying and pasting them one at a time. - -Now that you've registered the PostgreSQL repositories as a source to look for PostgreSQL, you need to update the `apt` registry. You should do this before you install _any_ software on Ubuntu. - - sudo apt update - -Once that's finished running, the new entries for PostgreSQL 12 should be in the repository. Now, you can install them with the following command. - - sudo apt install postgresql-client-12 postgresql-common - -If it asks you if you want to install them, please tell it "Y". - -Test that it installed by typing `psql --version`. You should see it print out information about the version of the installed tools. If it tells you that it can't find the command, try these instructions over. - -### Configuring the client tools - -Since you're going to be accessing the PosgreSQL installation from your Ubuntu installation on your Windows installation, you're going to have to type that you want to access it over and over, which means extra typing. To prevent you from having to do this, you can customize your shell to always add the extra commands for you. - -This assumes you're still using Bash. If you changed the shell that your Ubuntu installation uses, please follow that shell's directions for adding an alias to its startup file. - -Make sure you're in your Ubuntu home directory. You can do that by typing `cd` and hitting enter. Use `ls` to find out if you have a `.bashrc` file. Type `ls .bashrc`. If it shows you that one exists, that's the one you will add the alias to. If it tells you that there is no file named that, then type `ls .profile`. If it shows you that one exists, that's the one you will add the alias to. If it shows you that it does not exist, then use the file name `.bashrc` in the following section. - -Now that you know which profile file to use, type `code «profile file name»` where "profile file name" is the name of the file you determined from the last section. Once Visual Studio Code starts up with your file, at the end of it (or if you've already added aliases, in that section), type the following. - - alias psql="psql -h localhost" - -When you run `psql` from the command line, it will now always add the part about wanting to connect to _localhost_ every time. You would have to type that each time, otherwise. - -To make sure that you set that up correctly, type `psql -U postgres postgres`. This tells the `psql` client that you want to connect as the user "postgres" (`-U postgres`) to the database postgres (`postgres` at the end), which is the default database created when PostgreSQL is installed. It will prompt you for a password. Type the password that you used when you installed PostgrSQL, earlier. If the alias works correctly and you type the correct password, then you should see something like the following output. - - psql (12.2 (Ubuntu 12.2-2.pgdg18.04+1)) - Type "help" for help. - - postgres=# - -Type `\q` and hit Enter to exit the PostgreSQL client tool. - -Now, you will add a user for your Ubuntu identity so that you don't have to specify it all the time. Then, you will create a file that PostgreSQL will use to automatically send your password every time. - -Copy and paste the following into your Ubuntu shell. Think of a password that you want to use for your user. **Replace the password in the single quotes in the command with the password that you want.** It _has_ to be a non-empty string. PostgreSQL doesn't like it when it's not. - - psql -U postgres -c "CREATE USER `whoami` WITH PASSWORD 'password' SUPERUSER" - -It should prompt you for a password. Type the password that you created when you installed PostgreSQL. Once you type the correct password, you should see "CREATE ROLE". - -Now you will create your PostgreSQL password file. Type the following into your Ubuntu shell to open Visual Studio Code and create a new file. - - code ~/.pgpass - -In that file, you will add this line, which tells it that on localhost for port 5432 (where PostgreSQL is running), for all databases (\*), **use your Ubuntu user name and the password that you just created for that user with the** `psql` **command you just typed.** (If you have forgotten your Ubuntu user name, type `whoami` on the command line.) Your entry in the file should have this format. - - localhost:5432:*:«your Ubuntu user name»:«the password you just used» - -Once you have that information in the file, save it, and close Visual Studio Code. - -The last step you have to take is change the permission on that file so that it is only readable by your user. PostgreSQL will ignore it if just anyone can read and write to it. This is for _your_ security. Change the file permissions so only you can read and write to it. You did this once upon a time. Here's the command. - - chmod go-rw ~/.pgpass - -You can confirm that only you have read/write permission by typing `ls -al ~/.pgpass`. That should return output that looks like this, **with your Ubuntu user name instead of "web-dev-hub".** - - -rw------- 1 web-dev-hub web-dev-hub 37 Mar 28 21:20 /home/web-dev-hub/.pgpass - -Now, try connecting to PostreSQL by typing `psql postgres`. Because you added the alias to your startup script, and because you created your **.pgpass** file, it should now connect without prompting you for any credentials! Type `\q` and press Enter to exit the PostgreSQL command line client. - -### Installing Postbird - -Head over to the Postbird releases page on GitHub. Click the installer for Windows which you can recognize because it's the only file in the list that ends with ".exe". - -
    After that installer downloads, run it. You will get a warning from Windows that this is from an unidentified developer. If you don't want to install this, find a PostgreSQL GUI client that you do trust and install it or do everything from the command line. - -
    You should get used to seeing this because many open-source applications aren't signed with the Microsoft Store for monetary and philosophical reasons. - -Otherwise, if you trust Paxa like web-dev-hub and tens of thousands of other developers do, then click the link that reads "More info" and the "Run anyway" button. - -
    When it's done installing, it will launch itself. Test it out by typing the "postgres" into the "Username" field and the password from your installation in the "Password" field. Click the Connect button. It should properly connect to the running - -You can close it for now. It also installed an icon on your desktop. You can launch it from there or your Start Menu at any time. - -### Now.. if you still have some gas in the tank… let's put our new tools to work: - -### The node-postgres - -The node-postgres is a collection of Node.js modules for interfacing with the PostgreSQL database. It has support for callbacks, promises, async/await, connection pooling, prepared statements, cursors, and streaming results. - -In our examples we also use the Ramda library. See Ramda tutorial for more information. - -### Setting up node-postgres - -First, we install node-postgres. - -$ node -v -v14.2 - -$ npm init -y - -We initiate a new Node application. - -npm i pg - -We install node-postgres with `nmp i pg`. - -npm i ramda - -In addition, we install Ramda for beautiful work with data. - -cars.sql - -DROP TABLE IF EXISTS cars; - -CREATE TABLE cars(id SERIAL PRIMARY KEY, name VARCHAR(255), price INT); -INSERT INTO cars(name, price) VALUES('Audi', 52642); -INSERT INTO cars(name, price) VALUES('Mercedes', 57127); -INSERT INTO cars(name, price) VALUES('Skoda', 9000); -INSERT INTO cars(name, price) VALUES('Volvo', 29000); -INSERT INTO cars(name, price) VALUES('Bentley', 350000); -INSERT INTO cars(name, price) VALUES('Citroen', 21000); -INSERT INTO cars(name, price) VALUES('Hummer', 41400); -INSERT INTO cars(name, price) VALUES('Volkswagen', 21600); - -In some of the examples, we use this `cars` table. - -### The node-postgres first example - -In the first example, we connect to the PostgreSQL database and return a simple SELECT query result. - -first.js - - const pg = require('pg'); - const R = require('ramda'); - const cs = 'postgres://postgres:s$cret@localhost:5432/ydb'; - const client = new pg.Client(cs); - client.connect(); - client.query('SELECT 1 + 4').then(res => { - - const result = R.head(R.values(R.head(res.rows))) - - console.log(result) - }).finally(() => client.end()); - -The example connects to the database and issues a SELECT statement. - - const pg = require('pg'); - const R = require('ramda'); - -We include the `pg` and `ramda` modules. - - const cs = 'postgres://postgres:s$cret@localhost:5432/ydb'; - -This is the PostgreSQL connection string. It is used to build a connection to the database. - - const client = new pg.Client(cs); - client.connect(); - -A client is created. We connect to the database with `connect()`. - - client.query('SELECT 1 + 4').then(res => { - - const result = R.head(R.values(R.head(res.rows))); - - console.log(result); - - }).finally(() => client.end()); - -We issue a simple SELECT query. We get the result and output it to the console. The `res.rows` is an array of objects; we use Ramda to get the returned scalar value. In the end, we close the connection with `end()`. - - node first.js - 5 - -This is the output. - -### The node-postgres column names - -In the following example, we get the columns names of a database. - -> column_names.js - - const pg = require('pg'); - - const cs = 'postgres://postgres:s$cret@localhost:5432/ydb'; - - const client = new pg.Client(cs); - - client.connect(); - - client.query('SELECT * FROM cars').then(res => { - - const fields = res.fields.map(field => field.name); - - console.log(fields); - - }).catch(err => { - console.log(err.stack); - }).finally(() => { - client.end() - }); - -The column names are retrieved with `res.fields` attribute. We also use the `catch` clause to output potential errors. - - node column_names.js - 'id', 'name', 'price'′id′,′name′,′price′ - -The output shows three column names of the `cars` table. - -### Selecting all rows - -In the next example, we select all rows from the database table. - -> all_rows.js - - const pg = require('pg'); - const R = require('ramda'); - - const cs = 'postgres://postgres:s$cret@localhost:5432/ydb'; - - const client = new pg.Client(cs); - - client.connect(); - - client.query('SELECT * FROM cars').then(res => { - - const data = res.rows; - - console.log('all data'); - data.forEach(row => { - console.log(\`Id: ${row.id} Name: ${row.name} Price: ${row.price}\`); - }) - - console.log('Sorted prices:'); - const prices = R.pluck('price', R.sortBy(R.prop('price'), data)); - console.log(prices); - - }).finally(() => { - client.end() - }); - -**TBC…** - -#### If you found this guide helpful feel free to checkout my github/gists where I host similar content: - -bgoonz's gists · GitHub - -bgoonz — Overview -
    - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
    - -Or Checkout my personal Resource Site: - -Stackbit Web-Dev-HubTheme -
    - -Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…bgoonz-blog.netlify.app
    - -By Bryan Guner on [March 6, 2021](https://medium.com/p/801672ab7089). - -Canonical link - -August 6, 2021. diff --git a/notes/articles/medium/markdown/Postgresql-Cheat-Sheet.md b/notes/articles/medium/markdown/Postgresql-Cheat-Sheet.md deleted file mode 100644 index 5605125efd..0000000000 --- a/notes/articles/medium/markdown/Postgresql-Cheat-Sheet.md +++ /dev/null @@ -1,497 +0,0 @@ -# Postgresql Cheat Sheet - -PostgreSQL commands - ---- - -#### CODEX - -### PostgreSQL Cheat Sheet - -#### **Each table is made up of rows and columns. If you think of a table as a grid, the column go from left to right across the grid and each entry of data is listed down as a row.** - -
    - -Each row in a relational is uniquely identified by a primary key. This can be by one or more sets of column values. In most scenarios it is a single column, such as employeeID. - -Every relational table has one primary key. Its purpose is to uniquely identify each row in the database. No two rows can have the same primary key value. The practical result of this is that you can select every single row by just knowing its primary key. - -SQL Server UNIQUE constraints allow you to ensure that the data stored in a column, or a group of columns, is unique among the rows in a table. - -Although both UNIQUE and PRIMARY KEY constraints enforce the uniqueness of data, you should use the UNIQUE constraint instead of PRIMARY KEY constraint when you want to enforce the uniqueness of a column, or a group of columns, that are not the primary key columns. - -Different from PRIMARY KEY constraints, UNIQUE constraints allow NULL. Moreover, UNIQUE constraints treat the NULL as a regular value, therefore, it only allows one NULL per column. - -
    Create a new role: - - CREATE ROLE role_name; - -Create a new role with a `username` and `password`: - - CREATE ROLE username NOINHERIT LOGIN PASSWORD password; - -Change role for the current session to the `new_role`: - - SET ROLE new_role; - -Allow `role_1` to set its role as `role_2:` - - GRANT role_2 TO role_1; - -### Managing databases - -Create a new database: - - CREATE DATABASE [IF NOT EXISTS] db_name; - -Delete a database permanently: - - DROP DATABASE [IF EXISTS] db_name; - -### Managing tables - -Create a new table or a temporary table - - CREATE [TEMP] TABLE [IF NOT EXISTS] table_name( - pk SERIAL PRIMARY KEY, - c1 type(size) NOT NULL, - c2 type(size) NULL, - ... - ); - -Add a new column to a table: - - ALTER TABLE table_name ADD COLUMN new_column_name TYPE; - -Drop a column in a table: - - ALTER TABLE table_name DROP COLUMN column_name; - -Rename a column: - - ALTER TABLE table_name RENAME column_name TO new_column_name; - -Set or remove a default value for a column: - - ALTER TABLE table_name ALTER COLUMN [SET DEFAULT value | DROP DEFAULT] - -Add a primary key to a table. - - ALTER TABLE table_name ADD PRIMARY KEY (column,...); - -Remove the primary key from a table. - - ALTER TABLE table_name - DROP CONSTRAINT primary_key_constraint_name; - -Rename a table. - - ALTER TABLE table_name RENAME TO new_table_name; - -Drop a table and its dependent objects: - - DROP TABLE [IF EXISTS] table_name CASCADE; - -### Managing views - -Create a view: - - CREATE OR REPLACE view_name AS - query; - -Create a recursive view: - - CREATE RECURSIVE VIEW view_name(column_list) AS - SELECT column_list; - -Create a materialized view: - - CREATE MATERIALIZED VIEW view_name - AS - query - WITH [NO] DATA; - -Refresh a materialized view: - - REFRESH MATERIALIZED VIEW CONCURRENTLY view_name; - -Drop a view: - - DROP VIEW [ IF EXISTS ] view_name; - -Drop a materialized view: - - DROP MATERIALIZED VIEW view_name; - -Rename a view: - - ALTER VIEW view_name RENAME TO new_name; - -### Managing indexes - -Creating an index with the specified name on a table - - CREATE [UNIQUE] INDEX index_name - ON table (column,...) - -Removing a specified index from a table - - DROP INDEX index_name; - -### Querying data from tables - -Query all data from a table: - - SELECT * FROM table_name; - -Query data from specified columns of all rows in a table: - - SELECT column_list - FROM table; - -Query data and select only unique rows: - - SELECT DISTINCT (column) - FROM table; - -Query data from a table with a filter: - - SELECT * - FROM table - WHERE condition; - -Assign an alias to a column in the result set: - - SELECT column_1 AS new_column_1, ... - FROM table; - -Query data using the `LIKE` operator: - - SELECT * FROM table_name - WHERE column LIKE '%value%' - -Query data using the `BETWEEN `operator: - - SELECT * FROM table_name - WHERE column BETWEEN low AND high; - -Query data using the `IN `operator: - - SELECT * FROM table_name - WHERE column IN (value1, value2,...); - -Constrain the returned rows with the `LIMIT` clause: - - SELECT * FROM table_name - LIMIT limit OFFSET offset - ORDER BY column_name; - -Query data from multiple using the inner join, left join, full outer join, cross join and natural join: - - SELECT * - FROM table1 - INNER JOIN table2 ON conditions - SELECT * - FROM table1 - LEFT JOIN table2 ON conditions - SELECT * - FROM table1 - FULL OUTER JOIN table2 ON conditions - SELECT * - FROM table1 - CROSS JOIN table2; - SELECT * - FROM table1 - NATURAL JOIN table2; - -Return the number of rows of a table. - - SELECT COUNT (*) - FROM table_name; - -Sort rows in ascending or descending order: - - SELECT select_list - FROM table - ORDER BY column ASC [DESC], column2 ASC [DESC],...; - -Group rows using `GROUP BY` clause. - - SELECT * - FROM table - GROUP BY column_1, column_2, ...; - -Filter groups using the `HAVING` clause. - - SELECT * - FROM table - GROUP BY column_1 - HAVING condition; - -### Set operations - -Combine the result set of two or more queries with `UNION` operator: - - SELECT * FROM table1 - UNION - SELECT * FROM table2; - -Minus a result set using `EXCEPT` operator: - - SELECT * FROM table1 - EXCEPT - SELECT * FROM table2; - -Get intersection of the result sets of two queries: - - SELECT * FROM table1 - INTERSECT - SELECT * FROM table2; - -### Modifying data - -Insert a new row into a table: - - INSERT INTO table(column1,column2,...) - VALUES(value_1,value_2,...); - -Insert multiple rows into a table: - - INSERT INTO table_name(column1,column2,...) - VALUES(value_1,value_2,...), - (value_1,value_2,...), - (value_1,value_2,...)... - -Update data for all rows: - - UPDATE table_name - SET column_1 = value_1, - ...; - -Update data for a set of rows specified by a condition in the `WHERE` clause. - - UPDATE table - SET column_1 = value_1, - ... - WHERE condition; - -Delete all rows of a table: - - DELETE FROM table_name; - -Delete specific rows based on a condition: - - DELETE FROM table_name - WHERE condition; - -### Performance - -Show the query plan for a query: - - EXPLAIN query; - -Show and execute the query plan for a query: - - EXPLAIN ANALYZE query; - -Collect statistics: - - ANALYZE table_name; - ---- - -### Postgres & JSON: - -### Creating the DB and the Table - - DROP DATABASE IF EXISTS books_db; - CREATE DATABASE books_db WITH ENCODING='UTF8' TEMPLATE template0; - - DROP TABLE IF EXISTS books; - - CREATE TABLE books ( - id SERIAL PRIMARY KEY, - client VARCHAR NOT NULL, - data JSONb NOT NULL - ); - -### Populating the DB - - INSERT INTO books(client, data) values( 'Joe', '{ "title": "Siddhartha", "author": { "first_name": "Herman", "last_name": "Hesse" } }' ); INSERT INTO books(client, data) values('Jenny', '{ "title": "Bryan Guner", "author": { "first_name": "Jack", "last_name": "Kerouac" } }'); INSERT INTO books(client, data) values('Jenny', '{ "title": "100 años de soledad", "author": { "first_name": "Gabo", "last_name": "Marquéz" } }'); - -Lets see everything inside the table books: - - SELECT * FROM books; - -Output: - -
    ### `->` operator returns values out of JSON columns - -Selecting 1 column: - - SELECT client, - data->'title' AS title - FROM books; - -Output: - -
    Selecting 2 columns: - - SELECT client, - data->'title' AS title, data->'author' AS author - FROM books; - -Output: - -
    ### `->` vs `->>` - -The `->` operator returns the original JSON type (which might be an object), whereas `->>` returns text. - -### Return NESTED objects - -You can use the `->` to return a nested object and thus chain the operators: - - SELECT client, - data->'author'->'last_name' AS author - FROM books; - -Output: - -
    ### Filtering - -Select rows based on a value inside your JSON: - - SELECT - client, - data->'title' AS title - FROM books - WHERE data->'title' = '"Bryan Guner"'; - -Notice WHERE uses `->` so we must compare to JSON `'"Bryan Guner"'` - -Or we could use `->>` and compare to `'Bryan Guner'` - -Output: - -
    ### Nested filtering - -Find rows based on the value of a nested JSON object: - - SELECT - client, - data->'title' AS title - FROM books - WHERE data->'author'->>'last_name' = 'Kerouac'; - -Output: - -
    ### A real world example - - CREATE TABLE events ( - name varchar(200), - visitor_id varchar(200), - properties json, - browser json - ); - -We're going to store events in this table, like pageviews. Each event has properties, which could be anything (e.g. current page) and also sends information about the browser (like OS, screen resolution, etc). Both of these are completely free form and could change over time (as we think of extra stuff to track). - - INSERT INTO events VALUES ( - 'pageview', '1', - '{ "page": "/" }', - '{ "name": "Chrome", "os": "Mac", "resolution": { "x": 1440, "y": 900 } }' - ); - INSERT INTO events VALUES ( - 'pageview', '2', - '{ "page": "/" }', - '{ "name": "Firefox", "os": "Windows", "resolution": { "x": 1920, "y": 1200 } }' - ); - INSERT INTO events VALUES ( - 'pageview', '1', - '{ "page": "/account" }', - '{ "name": "Chrome", "os": "Mac", "resolution": { "x": 1440, "y": 900 } }' - ); - INSERT INTO events VALUES ( - 'purchase', '5', - '{ "amount": 10 }', - '{ "name": "Firefox", "os": "Windows", "resolution": { "x": 1024, "y": 768 } }' - ); - INSERT INTO events VALUES ( - 'purchase', '15', - '{ "amount": 200 }', - '{ "name": "Firefox", "os": "Windows", "resolution": { "x": 1280, "y": 800 } }' - ); - INSERT INTO events VALUES ( - 'purchase', '15', - '{ "amount": 500 }', - '{ "name": "Firefox", "os": "Windows", "resolution": { "x": 1280, "y": 800 } }' - ); - -Now lets select everything: - - SELECT * FROM events; - -Output: - -
    ### JSON operators + PostgreSQL aggregate functions - -Using the JSON operators, combined with traditional PostgreSQL aggregate functions, we can pull out whatever we want. You have the full might of an RDBMS at your disposal. - -- Lets see browser usage: -- `SELECT browser->>'name' AS browser, count(browser) FROM events GROUP BY browser->>'name';` - -Output: - -
    - Total revenue per visitor: - -`SELECT visitor_id, SUM(CAST(properties->>'amount' AS integer)) AS total FROM events WHERE CAST(properties->>'amount' AS integer) > 0 GROUP BY visitor_id;` - -Output: - -
    - Average screen resolution -- `SELECT AVG(CAST(browser->'resolution'->>'x' AS integer)) AS width, AVG(CAST(browser->'resolution'->>'y' AS integer)) AS height FROM events;` - -Output: - -
    #### If you found this guide helpful feel free to checkout my github/gists where I host similar content: - -bgoonz's gists · GitHub - -bgoonz — Overview -
    - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
    - -Or Checkout my personal Resource Site: - -a/A-Student-Resources -
    - -Edit descriptiongoofy-euclid-1cd736.netlify.app
    - -### If you found this guide helpful feel free to checkout my GitHub/gists where I host similar content: - -bgoonz's gists -
    - -Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…gist.github.com
    - -bgoonz — Overview -
    - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
    - -### Or Checkout my personal Resource Site: - -### Discover More: - -Web-Dev-Hub -
    - -Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…bgoonz-blog.netlify.app
    - -By Bryan Guner on [March 5, 2021](https://medium.com/p/718b813d3e31). - -Canonical link - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Postgresql-Cheat.md b/notes/articles/medium/markdown/Postgresql-Cheat.md deleted file mode 100644 index 0af5932156..0000000000 --- a/notes/articles/medium/markdown/Postgresql-Cheat.md +++ /dev/null @@ -1,497 +0,0 @@ -# Postgresql Cheat Sheet - -PostgreSQL commands - ---- - -#### CODEX - -### PostgreSQL Cheat Sheet - -#### **Each table is made up of rows and columns. If you think of a table as a grid, the column go from left to right across the grid and each entry of data is listed down as a row.** - -
    - -Each row in a relational is uniquely identified by a primary key. This can be by one or more sets of column values. In most scenarios it is a single column, such as employeeID. - -Every relational table has one primary key. Its purpose is to uniquely identify each row in the database. No two rows can have the same primary key value. The practical result of this is that you can select every single row by just knowing its primary key. - -SQL Server UNIQUE constraints allow you to ensure that the data stored in a column, or a group of columns, is unique among the rows in a table. - -Although both UNIQUE and PRIMARY KEY constraints enforce the uniqueness of data, you should use the UNIQUE constraint instead of PRIMARY KEY constraint when you want to enforce the uniqueness of a column, or a group of columns, that are not the primary key columns. - -Different from PRIMARY KEY constraints, UNIQUE constraints allow NULL. Moreover, UNIQUE constraints treat the NULL as a regular value, therefore, it only allows one NULL per column. - -
    Create a new role: - - CREATE ROLE role_name; - -Create a new role with a `username` and `password`: - - CREATE ROLE username NOINHERIT LOGIN PASSWORD password; - -Change role for the current session to the `new_role`: - - SET ROLE new_role; - -Allow `role_1` to set its role as `role_2:` - - GRANT role_2 TO role_1; - -### Managing databases - -Create a new database: - - CREATE DATABASE [IF NOT EXISTS] db_name; - -Delete a database permanently: - - DROP DATABASE [IF EXISTS] db_name; - -### Managing tables - -Create a new table or a temporary table - - CREATE [TEMP] TABLE [IF NOT EXISTS] table_name( - pk SERIAL PRIMARY KEY, - c1 type(size) NOT NULL, - c2 type(size) NULL, - ... - ); - -Add a new column to a table: - - ALTER TABLE table_name ADD COLUMN new_column_name TYPE; - -Drop a column in a table: - - ALTER TABLE table_name DROP COLUMN column_name; - -Rename a column: - - ALTER TABLE table_name RENAME column_name TO new_column_name; - -Set or remove a default value for a column: - - ALTER TABLE table_name ALTER COLUMN [SET DEFAULT value | DROP DEFAULT] - -Add a primary key to a table. - - ALTER TABLE table_name ADD PRIMARY KEY (column,...); - -Remove the primary key from a table. - - ALTER TABLE table_name - DROP CONSTRAINT primary_key_constraint_name; - -Rename a table. - - ALTER TABLE table_name RENAME TO new_table_name; - -Drop a table and its dependent objects: - - DROP TABLE [IF EXISTS] table_name CASCADE; - -### Managing views - -Create a view: - - CREATE OR REPLACE view_name AS - query; - -Create a recursive view: - - CREATE RECURSIVE VIEW view_name(column_list) AS - SELECT column_list; - -Create a materialized view: - - CREATE MATERIALIZED VIEW view_name - AS - query - WITH [NO] DATA; - -Refresh a materialized view: - - REFRESH MATERIALIZED VIEW CONCURRENTLY view_name; - -Drop a view: - - DROP VIEW [ IF EXISTS ] view_name; - -Drop a materialized view: - - DROP MATERIALIZED VIEW view_name; - -Rename a view: - - ALTER VIEW view_name RENAME TO new_name; - -### Managing indexes - -Creating an index with the specified name on a table - - CREATE [UNIQUE] INDEX index_name - ON table (column,...) - -Removing a specified index from a table - - DROP INDEX index_name; - -### Querying data from tables - -Query all data from a table: - - SELECT * FROM table_name; - -Query data from specified columns of all rows in a table: - - SELECT column_list - FROM table; - -Query data and select only unique rows: - - SELECT DISTINCT (column) - FROM table; - -Query data from a table with a filter: - - SELECT * - FROM table - WHERE condition; - -Assign an alias to a column in the result set: - - SELECT column_1 AS new_column_1, ... - FROM table; - -Query data using the `LIKE` operator: - - SELECT * FROM table_name - WHERE column LIKE '%value%' - -Query data using the `BETWEEN `operator: - - SELECT * FROM table_name - WHERE column BETWEEN low AND high; - -Query data using the `IN `operator: - - SELECT * FROM table_name - WHERE column IN (value1, value2,...); - -Constrain the returned rows with the `LIMIT` clause: - - SELECT * FROM table_name - LIMIT limit OFFSET offset - ORDER BY column_name; - -Query data from multiple using the inner join, left join, full outer join, cross join and natural join: - - SELECT * - FROM table1 - INNER JOIN table2 ON conditions - SELECT * - FROM table1 - LEFT JOIN table2 ON conditions - SELECT * - FROM table1 - FULL OUTER JOIN table2 ON conditions - SELECT * - FROM table1 - CROSS JOIN table2; - SELECT * - FROM table1 - NATURAL JOIN table2; - -Return the number of rows of a table. - - SELECT COUNT (*) - FROM table_name; - -Sort rows in ascending or descending order: - - SELECT select_list - FROM table - ORDER BY column ASC [DESC], column2 ASC [DESC],...; - -Group rows using `GROUP BY` clause. - - SELECT * - FROM table - GROUP BY column_1, column_2, ...; - -Filter groups using the `HAVING` clause. - - SELECT * - FROM table - GROUP BY column_1 - HAVING condition; - -### Set operations - -Combine the result set of two or more queries with `UNION` operator: - - SELECT * FROM table1 - UNION - SELECT * FROM table2; - -Minus a result set using `EXCEPT` operator: - - SELECT * FROM table1 - EXCEPT - SELECT * FROM table2; - -Get intersection of the result sets of two queries: - - SELECT * FROM table1 - INTERSECT - SELECT * FROM table2; - -### Modifying data - -Insert a new row into a table: - - INSERT INTO table(column1,column2,...) - VALUES(value_1,value_2,...); - -Insert multiple rows into a table: - - INSERT INTO table_name(column1,column2,...) - VALUES(value_1,value_2,...), - (value_1,value_2,...), - (value_1,value_2,...)... - -Update data for all rows: - - UPDATE table_name - SET column_1 = value_1, - ...; - -Update data for a set of rows specified by a condition in the `WHERE` clause. - - UPDATE table - SET column_1 = value_1, - ... - WHERE condition; - -Delete all rows of a table: - - DELETE FROM table_name; - -Delete specific rows based on a condition: - - DELETE FROM table_name - WHERE condition; - -### Performance - -Show the query plan for a query: - - EXPLAIN query; - -Show and execute the query plan for a query: - - EXPLAIN ANALYZE query; - -Collect statistics: - - ANALYZE table_name; - ---- - -### Postgres & JSON: - -### Creating the DB and the Table - - DROP DATABASE IF EXISTS books_db; - CREATE DATABASE books_db WITH ENCODING='UTF8' TEMPLATE template0; - - DROP TABLE IF EXISTS books; - - CREATE TABLE books ( - id SERIAL PRIMARY KEY, - client VARCHAR NOT NULL, - data JSONb NOT NULL - ); - -### Populating the DB - - INSERT INTO books(client, data) values( 'Joe', '{ "title": "Siddhartha", "author": { "first_name": "Herman", "last_name": "Hesse" } }' ); INSERT INTO books(client, data) values('Jenny', '{ "title": "Bryan Guner", "author": { "first_name": "Jack", "last_name": "Kerouac" } }'); INSERT INTO books(client, data) values('Jenny', '{ "title": "100 años de soledad", "author": { "first_name": "Gabo", "last_name": "Marquéz" } }'); - -Lets see everything inside the table books: - - SELECT * FROM books; - -Output: - -
    ### `->` operator returns values out of JSON columns - -Selecting 1 column: - - SELECT client, - data->'title' AS title - FROM books; - -Output: - -
    Selecting 2 columns: - - SELECT client, - data->'title' AS title, data->'author' AS author - FROM books; - -Output: - -
    ### `->` vs `->>` - -The `->` operator returns the original JSON type (which might be an object), whereas `->>` returns text. - -### Return NESTED objects - -You can use the `->` to return a nested object and thus chain the operators: - - SELECT client, - data->'author'->'last_name' AS author - FROM books; - -Output: - -
    ### Filtering - -Select rows based on a value inside your JSON: - - SELECT - client, - data->'title' AS title - FROM books - WHERE data->'title' = '"Bryan Guner"'; - -Notice WHERE uses `->` so we must compare to JSON `'"Bryan Guner"'` - -Or we could use `->>` and compare to `'Bryan Guner'` - -Output: - -
    ### Nested filtering - -Find rows based on the value of a nested JSON object: - - SELECT - client, - data->'title' AS title - FROM books - WHERE data->'author'->>'last_name' = 'Kerouac'; - -Output: - -
    ### A real world example - - CREATE TABLE events ( - name varchar(200), - visitor_id varchar(200), - properties json, - browser json - ); - -We're going to store events in this table, like pageviews. Each event has properties, which could be anything (e.g. current page) and also sends information about the browser (like OS, screen resolution, etc). Both of these are completely free form and could change over time (as we think of extra stuff to track). - - INSERT INTO events VALUES ( - 'pageview', '1', - '{ "page": "/" }', - '{ "name": "Chrome", "os": "Mac", "resolution": { "x": 1440, "y": 900 } }' - ); - INSERT INTO events VALUES ( - 'pageview', '2', - '{ "page": "/" }', - '{ "name": "Firefox", "os": "Windows", "resolution": { "x": 1920, "y": 1200 } }' - ); - INSERT INTO events VALUES ( - 'pageview', '1', - '{ "page": "/account" }', - '{ "name": "Chrome", "os": "Mac", "resolution": { "x": 1440, "y": 900 } }' - ); - INSERT INTO events VALUES ( - 'purchase', '5', - '{ "amount": 10 }', - '{ "name": "Firefox", "os": "Windows", "resolution": { "x": 1024, "y": 768 } }' - ); - INSERT INTO events VALUES ( - 'purchase', '15', - '{ "amount": 200 }', - '{ "name": "Firefox", "os": "Windows", "resolution": { "x": 1280, "y": 800 } }' - ); - INSERT INTO events VALUES ( - 'purchase', '15', - '{ "amount": 500 }', - '{ "name": "Firefox", "os": "Windows", "resolution": { "x": 1280, "y": 800 } }' - ); - -Now lets select everything: - - SELECT * FROM events; - -Output: - -
    ### JSON operators + PostgreSQL aggregate functions - -Using the JSON operators, combined with traditional PostgreSQL aggregate functions, we can pull out whatever we want. You have the full might of an RDBMS at your disposal. - -- Lets see browser usage: -- `SELECT browser->>'name' AS browser, count(browser) FROM events GROUP BY browser->>'name';` - -Output: - -
    - Total revenue per visitor: - -`SELECT visitor_id, SUM(CAST(properties->>'amount' AS integer)) AS total FROM events WHERE CAST(properties->>'amount' AS integer) > 0 GROUP BY visitor_id;` - -Output: - -
    - Average screen resolution -- `SELECT AVG(CAST(browser->'resolution'->>'x' AS integer)) AS width, AVG(CAST(browser->'resolution'->>'y' AS integer)) AS height FROM events;` - -Output: - -
    #### If you found this guide helpful feel free to checkout my github/gists where I host similar content: - -bgoonz's gists · GitHub - -bgoonz — Overview -
    - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
    - -Or Checkout my personal Resource Site: - -a/A-Student-Resources -
    - -Edit descriptiongoofy-euclid-1cd736.netlify.app
    - -### If you found this guide helpful feel free to checkout my GitHub/gists where I host similar content: - -bgoonz's gists -
    - -Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…gist.github.com
    - -bgoonz — Overview -
    - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
    - -### Or Checkout my personal Resource Site: - -### Discover More: - -Web-Dev-Hub -
    - -Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…bgoonz-blog.netlify.app
    - -By Bryan Guner on [March 5, 2021](https://medium.com/p/718b813d3e31). - -Canonical link - -August 6, 2021. diff --git a/notes/articles/medium/markdown/Python-Problems---Solutions-For-Beginners.md b/notes/articles/medium/markdown/Python-Problems---Solutions-For-Beginners.md deleted file mode 100644 index d3ead177c3..0000000000 --- a/notes/articles/medium/markdown/Python-Problems---Solutions-For-Beginners.md +++ /dev/null @@ -1,194 +0,0 @@ -# Python Problems & Solutions For Beginners - -Introduction to python taught through example problems. Solutions are included in embedded repl.it at the bottom of this page for you to… - ---- - -### Python Problems & Solutions For Beginners - -#### Introduction to python taught through example problems. Solutions are included in embedded repl.it at the bottom of this page for you to practice and refactor. - -### Python Practice Problems - -
    - ---- - -#### Here are some other articles for reference if you need them: - -Beginners Guide To Python -
    - -My favorite language for maintainability is Python. It has simple, clean syntax, object encapsulation, good library…medium.com
    - -Python Study Guide for a JavaScript Programmer -
    - -A guide to commands in Python from what you know in JavaScriptlevelup.gitconnected.com
    - ---- - -### Here are the problems without solutions for you to practice with: - ---- - -### Problem 1 - -Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn `100` years old. - -The `datetime` module supplies classes for manipulating dates and times. - -While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation. - -datetime - Basic date and time types - Python 3.9.6 documentation -
    - -Only one concrete class, the class, is supplied by the module. The class can represent simple timezones with fixed…docs.python.org
    - -### Problem 2 - -Ask the user for a number. Depending on whether the number is `even` or `odd`, print out an appropriate message to the user. - -#### Bonus: - -1. If the number is a multiple of `4`, print out a different message. -2. Ask the user for two numbers: one number to check (call it num) and one number to divide by (check). If check divides evenly into num, tell that to the user. If not, print a different appropriate message. - -### Problem 3 - -Take a list and write a program that prints out all the elements of the list that are `less` than `5`. - -Extras: - -1. Instead of printing the elements one by one, make a new list that has all the elements less than `5` from this list in it and print out this new list. -2. Write this in one line of Python. -3. Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user. - -### Problem 4 - -Create a program that asks the user for a number and then prints out a list of all the divisors of that number. (If you don't know what a divisor is, it is a number that divides evenly into another number. - -For example, `13` is a divisor of `26` because `26 / 13` has no remainder.) - -### Problem 5 - -Take two lists, and write a program that returns a list that contains only the elements that are `common between the lists (without duplicates)`. Make sure your program works on two lists of different sizes. - -random - Generate pseudo-random numbers - Python 3.9.6 documentation -
    - -Source code: Lib/random.py This module implements pseudo-random number generators for various distributions. For…docs.python.org
    - -Bonus: - -1. Randomly generate two lists to test this. -2. Write this in one line of Python. - -### Problem 6 - -Ask the user for a string and print out whether this string is a `palindrome` or not. (A palindrome is a string that reads the same forwards and backwards.) - -> Here's 5 ways to reverse a string (courtesy of geeksforgeeks) - ---- - -### Problem 7 - -Let's say I give you a list saved in a variable: a = `[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]`. - -Write one line of Python that takes this list a and makes a new list that has only the `even` elements of this list in it. - -### Problem 8 - -Make a two-player `Rock-Paper-Scissors` game. - -**Hint:** -Ask for player plays (using input), compare them. Print out a message of congratulations to the winner, and ask if the players want to start a new game. - -
    ### Problem 9 - -Generate a random number between `1 and 100 (including 1 and 100)`. Ask the user to guess the number, then tell them whether they guessed `too low`, `too high`, or `exactly right`. - -> **Hint:** -> Remember to use the user input from the very first exercise. - -**Extras:** -Keep the game going until the user types `"exit"`. -Keep track of how many guesses the user has taken, and when the game ends, print this out. - -### Problem 10 - -Write a program that asks the user how many Fibonacci numbers to generate and then generates them. Take this opportunity to think about how you can use functions. Make sure to ask the user to enter the number of numbers in the sequence to generate. - -**Hint:** -The Fibonacci sequence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence. The sequence looks like this: `1, 1, 2, 3, 5, 8, 13, …` - -
    - ---- - -### Intermediate Problems: - -
    - ---- - -### Problem 11 - -In linear algebra, _a Toeplitz matrix is one in which the elements on any given diagonal from top left to bottom right are identical._ -Here is an example: - - 1 2 3 4 8 - 5 1 2 3 4 - 4 5 1 2 3 - 7 4 5 1 2 - -Write a program to determine whether a given input is a `Toeplitz` matrix. - -### Problem 12 - -Given a positive integer `N`, find the smallest number of steps it will take to reach `1`. - -There are two kinds of permitted steps: - — -> You may decrement N to N — 1. - — -> If `a * b = N`, you may decrement `N to the larger of a and b`. - -For example, given 100, you can reach 1 in 5 steps with the following route: -`100 -> 10 -> 9 -> 3 -> 2 -> 1.` - -### Problem 13 - -Consider the following scenario: there are `N` mice and `N` holes placed at integer points along a line. Given this, find a method that maps mice to holes such that the largest number of steps any mouse takes is minimized. - -Each move consists of moving one mouse `one` unit to the `left` or `right`, and only `one` mouse can fit inside each hole. - -For example, suppose the mice are positioned at `[1, 4, 9, 15]`, and the holes are located at `[10, -5, 0, 16]`. In this case, the best pairing would require us to send the mouse at `1` to the hole at `-5`, so our function should return `6`. - -### My Blog: - -Web-Dev-Hub -
    - -Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…master--bgoonz-blog.netlify.app
    - -A list of all of my articles to link to future posts -
    - -You should probably skip this one… seriously it's just for internal use! - ---- - -### Level Up Coding - -Thanks for being a part of our community! Subscribe to our YouTube channel or join the Skilled.dev coding interview course. - -Coding Interview Questions + Land Your Dev Job | Skilled.dev -
    - -Coding interview course taught in Pythonskilled.dev
    - -By Bryan Guner on [August 21, 2021](https://medium.com/p/dd631e9c3a9f). - -Canonical link - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Python-Study-Guide-for-a-JavaScript-Programmer.md b/notes/articles/medium/markdown/Python-Study-Guide-for-a-JavaScript-Programmer.md deleted file mode 100644 index f9a5fee40b..0000000000 --- a/notes/articles/medium/markdown/Python-Study-Guide-for-a-JavaScript-Programmer.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: React -excerpt: >- - To make it easy to write documentation in plain Markdown, most React are - styled using Markdown elements with few additional CSS classes. -seo: - title: React - description: This is the React page - extra: - - name: 'og:type' - value: website - keyName: property - - name: 'og:title' - value: React - keyName: property - - name: 'og:description' - value: This is the React page - keyName: property - - name: 'twitter:card' - value: summary - - name: 'twitter:title' - value: React - - name: 'twitter:description' - value: This is the React page -template: docs ---- - -# React - -# Examples - - - -### For more resources visit: - -[bgoonz/React_Notes_V3A JavaScript library for building user interfaces React makes it painless to create interactive UIs. Design simple…github.com](https://github.com/bgoonz/React_Notes_V3) - -[Use this appendix to get any prerequisite concepts and terminology under your belt:](https://gist.github.com/bgoonz/e07d9e7917ae9e98807358d1e7cc4a67) - -Here I will walk through a demo…. skip down below for more fundamental examples and resources… - -## Learn Redux - - - ---- - - - - - -## ALL CODE - -```jsx - -``` - -## React Cheat Sheet: - -React-Tutorial-1:[react-tutorial-1A React repl by bgoonzreplit.com](https://replit.com/@bgoonz/react-tutorial-1) - -React Boilerplate:[React.js + Babel + Webpack BoilerplateCreated by @eankeen | The ultimate trifecta - React, Babel, and Webpack - complete with hot module reloading and a…replit.com](https://replit.com/@bgoonz/Reactjs-Babel-Webpack-Boilerplate#index.js) diff --git a/notes/articles/medium/markdown/Python-Study-Guide-for-a-JavaScript.md b/notes/articles/medium/markdown/Python-Study-Guide-for-a-JavaScript.md deleted file mode 100644 index 121268051e..0000000000 --- a/notes/articles/medium/markdown/Python-Study-Guide-for-a-JavaScript.md +++ /dev/null @@ -1,954 +0,0 @@ -# Python Study Guide for a JavaScript Programmer - -A guide to commands in Python from what you know in JavaScript - ---- - -### Python Study Guide for a JavaScript Programmer - -
    ### Applications of Tutorial & Cheat Sheet Respectivley (At Bottom Of Tutorial): - -### Basics - -- **PEP8** : Python Enhancement Proposals, style-guide for Python. -- `print` is the equivalent of `console.log`. - -> 'print() == console.log()' - -### `#` is used to make comments in your code. - - def foo(): - """ - The foo function does many amazing things that you - should not question. Just accept that it exists and - use it with caution. - """ - secretThing() - -> _Python has a built in help function that let's you see a description of the source code without having to navigate to it… "-SickNasty … Autor Unknown"_ - ---- - -### Numbers - -- Python has three types of numbers: - -1. **Integer** -2. **Positive and Negative Counting Numbers.** - -No Decimal Point - -> Created by a literal non-decimal point number … **or** … with the `int()` constructor. - - print(3) # => 3 - print(int(19)) # => 19 - print(int()) # => 0 - -**3. Complex Numbers** - -> Consist of a real part and imaginary part. - -#### Boolean is a subtype of integer in Python.🤷‍♂️ - -> If you came from a background in JavaScript and learned to accept the premise(s) of the following meme… - -
    Than I am sure you will find the means to suspend your disbelief. - - print(2.24) # => 2.24 - print(2.) # => 2.0 - print(float()) # => 0.0 - print(27e-5) # => 0.00027 - -### KEEP IN MIND: - -> **The** `i` **is switched to a** `j` **in programming.** - -T\*his is because the letter i is common place as the de facto index for any and all enumerable entities so it just makes sense not to compete for name-\***_space_** _when there's another 25 letters that don't get used for every loop under the sun. My most medium apologies to Leonhard Euler._ - - print(7j) # => 7j - print(5.1+7.7j)) # => 5.1+7.7j - print(complex(3, 5)) # => 3+5j - print(complex(17)) # => 17+0j - print(complex()) # => 0j - -- **Type Casting** : The process of converting one number to another. - - - - # Using Float - print(17) # => 17 - print(float(17)) # => 17.0 - - # Using Int - print(17.0) # => 17.0 - print(int(17.0)) # => 17 - - # Using Str - print(str(17.0) + ' and ' + str(17)) # => 17.0 and 17 - -**The arithmetic operators are the same between JS and Python, with two additions:** - -- _"\*\*" : Double asterisk for exponent._ -- _"//" : Integer Division._ -- **There are no spaces between math operations in Python.** -- **Integer Division gives the other part of the number from Module; it is a way to do round down numbers replacing** `Math.floor()` **in JS.** -- **There are no** `++` **and** `--` **in Python, the only shorthand operators are:** - -
    - ---- - -### Strings - -- Python uses both single and double quotes. -- You can escape strings like so `'Jodi asked, "What\'s up, Sam?"'` -- Multiline strings use triple quotes. - - - - print('''My instructions are very long so to make them - more readable in the code I am putting them on - more than one line. I can even include "quotes" - of any kind because they won't get confused with - the end of the string!''') - -**Use the** `len()` **function to get the length of a string.** - - print(len("Spaghetti")) # => 9 - -### **Python uses** `zero-based indexing` - -#### Python allows negative indexing (thank god!) - - print("Spaghetti"[-1]) # => i - - print("Spaghetti"[-4]) # => e - -- Python let's you use ranges - -You can think of this as roughly equivalent to the slice method called on a JavaScript object or string… _(mind you that in JS … strings are wrapped in an object (under the hood)… upon which the string methods are actually called. As a immutable privative type_ **\*by textbook definition\*\***, a string literal could not hope to invoke most of it's methods without violating the state it was bound to on initialization if it were not for this bit of syntactic sugar.)\* - - print("Spaghetti"[1:4]) # => pag - print("Spaghetti"[4:-1]) # => hett - print("Spaghetti"[4:4]) # => (empty string) - -- The end range is exclusive just like `slice` in JS. - - - - # Shortcut to get from the beginning of a string to a certain index. - print("Spaghetti"[:4]) # => Spag - print("Spaghetti"[:-1]) # => Spaghett - - # Shortcut to get from a certain index to the end of a string. - print("Spaghetti"[1:]) # => paghetti - print("Spaghetti"[-4:]) # => etti - -- The `index` string function is the equiv. of `indexOf()` in JS - - - - print("Spaghetti".index("h")) # => 4 - print("Spaghetti".index("t")) # => 6 - -- The `count` function finds out how many times a substring appears in a string… pretty nifty for a hard coded feature of the language. - - - - print("Spaghetti".count("h")) # => 1 - print("Spaghetti".count("t")) # => 2 - print("Spaghetti".count("s")) # => 0 - print('''We choose to go to the moon in this decade and do the other things, - not because they are easy, but because they are hard, because that goal will - serve to organize and measure the best of our energies and skills, because that - challenge is one that we are willing to accept, one we are unwilling to - postpone, and one which we intend to win, and the others, too. - '''.count('the ')) # => 4 - -- **You can use** `+` **to concatenate strings, just like in JS.** -- **You can also use "\*" to repeat strings or multiply strings.** -- **Use the** `format()` **function to use placeholders in a string to input values later on.** - - - - first_name = "Billy" - last_name = "Bob" - print('Your name is {0} {1}'.format(first_name, last_name)) # => Your name is Billy Bob - -- _Shorthand way to use format function is: - _`print(f'Your name is {first_name} {last_name}')` - -#### Some useful string methods. - -- **Note that in JS** `join` **is used on an Array, in Python it is used on String.** - -
    - There are also many handy testing methods. - -
    - ---- - -### Variables and Expressions - -- **Duck-Typing** : Programming Style which avoids checking an object's type to figure out what it can do. -- Duck Typing is the fundamental approach of Python. -- Assignment of a value automatically declares a variable. - - - - a = 7 - b = 'Marbles' - print(a) # => 7 - print(b) # => Marbles - -- **_You can chain variable assignments to give multiple var names the same value._** - -#### Use with caution as this is highly unreadable - - count = max = min = 0 - print(count) # => 0 - print(max) # => 0 - print(min) # => 0 - -#### The value and type of a variable can be re-assigned at any time. - - a = 17 - print(a) # => 17 - a = 'seventeen' - print(a) # => seventeen - -- `NaN` _does not exist in Python, but you can 'create' it like so: - _`print(float("nan"))` -- _Python replaces_ `null` _with_ `none`_._ -- `none` **_is an object_** _and can be directly assigned to a variable._ - -> Using none is a convenient way to check to see why an action may not be operating correctly in your program. - ---- - -### Boolean Data Type - -- One of the biggest benefits of Python is that it reads more like English than JS does. - -
    # Logical AND - print(True and True) # => True - print(True and False) # => False - print(False and False) # => False - - # Logical OR - print(True or True) # => True - print(True or False) # => True - print(False or False) # => False - - # Logical NOT - print(not True) # => False - print(not False and True) # => True - print(not True or False) # => False - -- By default, Python considers an object to be true UNLESS it is one of the following: -- Constant `None` or `False` -- Zero of any numeric type. -- Empty Sequence or Collection. -- `True` and `False` must be capitalized - ---- - -### Comparison Operators - -- Python uses all the same equality operators as JS. -- In Python, equality operators are processed from left to right. -- Logical operators are processed in this order: - -1. **NOT** -2. **AND** -3. **OR** - -> Just like in JS, you can use `parentheses` to change the inherent order of operations. - -> **Short Circuit** : Stopping a program when a `true` or `false` has been reached. - -
    - ---- - -### Identity vs Equality - - print (2 == '2') # => False - print (2 is '2') # => False - - print ("2" == '2') # => True - print ("2" is '2') # => True - - # There is a distinction between the number types. - print (2 == 2.0) # => True - print (2 is 2.0) # => False - -- In the Python community it is better to use `is` and `is not` over `==` or `!=` - ---- - -### If Statements - - if name == 'Monica': - print('Hi, Monica.') - - if name == 'Monica': - print('Hi, Monica.') - else: - print('Hello, stranger.') - - if name == 'Monica': - print('Hi, Monica.') - elif age < 12: - print('You are not Monica, kiddo.') - elif age > 2000: - print('Unlike you, Monica is not an undead, immortal vampire.') - elif age > 100: - print('You are not Monica, grannie.') - -> Remember the order of `elif` statements matter. - ---- - -### While Statements - - spam = 0 - while spam < 5: - print('Hello, world.') - spam = spam + 1 - -- `Break` statement also exists in Python. - - - - spam = 0 - while True: - print('Hello, world.') - spam = spam + 1 - if spam >= 5: - break - -- As are `continue` statements - - - - spam = 0 - while True: - print('Hello, world.') - spam = spam + 1 - if spam < 5: - continue - break - ---- - -### Try/Except Statements - -- Python equivalent to `try/catch` - - - - a = 321 - try: - print(len(a)) - except: - print('Silently handle error here') - - # Optionally include a correction to the issue - a = str(a) - print(len(a) - - a = '321' - try: - print(len(a)) - except: - print('Silently handle error here') - - # Optionally include a correction to the issue - a = str(a) - print(len(a)) - -- You can name an error to give the output more specificity. - - - - a = 100 - b = 0 - try: - c = a / b - except ZeroDivisionError: - c = None - print(c) - -- You can also use the `pass` commmand to by pass a certain error. - - - - a = 100 - b = 0 - try: - print(a / b) - except ZeroDivisionError: - pass - -- The `pass` method won't allow you to bypass every single error so you can chain an exception series like so: - - - - a = 100 - # b = "5" - try: - print(a / b) - except ZeroDivisionError: - pass - except (TypeError, NameError): - print("ERROR!") - -- You can use an `else` statement to end a chain of `except` statements. - - - - # tuple of file names - files = ('one.txt', 'two.txt', 'three.txt') - - # simple loop - for filename in files: - try: - # open the file in read mode - f = open(filename, 'r') - except OSError: - # handle the case where file does not exist or permission is denied - print('cannot open file', filename) - else: - # do stuff with the file object (f) - print(filename, 'opened successfully') - print('found', len(f.readlines()), 'lines') - f.close() - -- `finally` is used at the end to clean up all actions under any circumstance. - - - - def divide(x, y): - try: - result = x / y - except ZeroDivisionError: - print("Cannot divide by zero") - else: - print("Result is", result) - finally: - print("Finally...") - -- Using duck typing to check to see if some value is able to use a certain method. - - - - # Try a number - nothing will print out - a = 321 - if hasattr(a, '__len__'): - print(len(a)) - - # Try a string - the length will print out (4 in this case) - b = "5555" - if hasattr(b, '__len__'): - print(len(b)) - ---- - -### Pass - -- Pass Keyword is required to write the JS equivalent of : - - - - if (true) { - } - - while (true) {} - - if True: - pass - - while True: - pass - ---- - -### Functions - -- **Function definition includes:** -- **The** `def` **keyword** -- **The name of the function** -- **A list of parameters enclosed in parentheses.** -- **A colon at the end of the line.** -- **One tab indentation for the code to run.** -- **You can use default parameters just like in JS** - - - - def greeting(name, saying="Hello"): - print(saying, name) - - greeting("Monica") - # Hello Monica - - greeting("Barry", "Hey") - # Hey Barry - -#### **Keep in mind, default parameters must always come after regular parameters.** - - # THIS IS BAD CODE AND WILL NOT RUN - def increment(delta=1, value): - return delta + value - -- _You can specify arguments by name without destructuring in Python._ - - - - def greeting(name, saying="Hello"): - print(saying, name) - - # name has no default value, so just provide the value - # saying has a default value, so use a keyword argument - greeting("Monica", saying="Hi") - -- The `lambda` keyword is used to create anonymous functions and are supposed to be `one-liners`. - -`toUpper = lambda s: s.upper()` - ---- - -### Notes - -#### Formatted Strings - -> Remember that in Python join() is called on a string with an array/list passed in as the argument. -> Python has a very powerful formatting engine. -> format() is also applied directly to strings. - - shopping_list = ['bread','milk','eggs'] - print(','.join(shopping_list)) - -### Comma Thousands Separator - - print('{:,}'.format(1234567890)) - '1,234,567,890' - -### Date and Time - - d = datetime.datetime(2020, 7, 4, 12, 15, 58) - print('{:%Y-%m-%d %H:%M:%S}'.format(d)) - '2020-07-04 12:15:58' - -### Percentage - - points = 190 - total = 220 - print('Correct answers: {:.2%}'.format(points/total)) - Correct answers: 86.36% - -### Data Tables - - width=8 - print(' decimal hex binary') - print('-'*27) - for num in range(1,16): - for base in 'dXb': - print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ') - print() - Getting Input from the Command Line - Python runs synchronously, all programs and processes will stop when listening for a user input. - The input function shows a prompt to a user and waits for them to type 'ENTER'. - Scripts vs Programs - Programming Script : A set of code that runs in a linear fashion. - The largest difference between scripts and programs is the level of complexity and purpose. Programs typically have many UI's. - -**Python can be used to display html, css, and JS.** -_It is common to use Python as an API (Application Programming Interface)_ - -#### Structured Data - -#### Sequence : The most basic data structure in Python where the index determines the order. - -> List -> Tuple -> Range -> Collections : Unordered data structures, hashable values. - ---- - -#### Dictionaries Sets - -#### Iterable : Generic name for a sequence or collection; any object that can be iterated through. - -#### Can be mutable or immutable. Built In Data Types - ---- - -### Lists are the python equivalent of arrays. - - empty_list = [] - departments = ['HR','Development','Sales','Finance','IT','Customer Support'] - -### You can instantiate - - specials = list() - -#### Test if a value is in a list. - - print(1 in [1, 2, 3]) #> True - print(4 in [1, 2, 3]) #> False - # Tuples : Very similar to lists, but they are immutable - -#### Instantiated with parentheses - - time_blocks = ('AM','PM') - -#### Sometimes instantiated without - - colors = 'red','blue','green' - numbers = 1, 2, 3 - -#### Tuple() built in can be used to convert other data into a tuple - - tuple('abc') # returns ('a', 'b', 'c') - tuple([1,2,3]) # returns (1, 2, 3) - # Think of tuples as constant variables. - -#### Ranges : A list of numbers which can't be changed; often used with for loops. - -**Declared using one to three parameters**. - -> Start : opt. default 0, first \# in sequence. -> Stop : required next number past the last number in the sequence. -> Step : opt. default 1, difference between each number in the sequence. - - range(5) # [0, 1, 2, 3, 4] - range(1,5) # [1, 2, 3, 4] - range(0, 25, 5) # [0, 5, 10, 15, 20] - range(0) # [ ] - for let (i = 0; i < 5; i++) - for let (i = 1; i < 5; i++) - for let (i = 0; i < 25; i+=5) - for let(i = 0; i = 0; i++) - # Keep in mind that stop is not included in the range. - -#### Dictionaries : Mappable collection where a hashable value is used as a key to ref. an object stored in the dictionary. - -#### Mutable. - - a = {'one':1, 'two':2, 'three':3} - b = dict(one=1, two=2, three=3) - c = dict([('two', 2), ('one', 1), ('three', 3)]) - # a, b, and c are all equal - -**_Declared with curly braces of the built in dict()_** - -> _Benefit of dictionaries in Python is that it doesn't matter how it is defined, if the keys and values are the same the dictionaries are considered equal._ - -**Use the in operator to see if a key exists in a dictionary.** - -S**ets : Unordered collection of distinct objects; objects that need to be hashable.** - -> _Always be unique, duplicate items are auto dropped from the set._ - -#### Common Uses: - -> Removing Duplicates -> Membership Testing -> Mathematical Operators: Intersection, Union, Difference, Symmetric Difference. - -**Standard Set is mutable, Python has a immutable version called frozenset. -Sets created by putting comma seperated values inside braces:** - - school_bag = {'book','paper','pencil','pencil','book','book','book','eraser'} - print(school_bag) - -#### Also can use set constructor to automatically put it into a set. - - letters = set('abracadabra') - print(letters) - #Built-In Functions - #Functions using iterables - -**filter(function, iterable) : creates new iterable of the same type which includes each item for which the function returns true.** - -**map(function, iterable) : creates new iterable of the same type which includes the result of calling the function on every item of the iterable.** - -**sorted(iterable, key=None, reverse=False) : creates a new sorted list from the items in the iterable.** - -**Output is always a list** - -**key: opt function which coverts and item to a value to be compared.** - -**reverse: optional boolean.** - -**enumerate(iterable, start=0) : starts with a sequence and converts it to a series of tuples** - - quarters = ['First', 'Second', 'Third', 'Fourth'] - print(enumerate(quarters)) - print(enumerate(quarters, start=1)) - -#### (0, 'First'), (1, 'Second'), (2, 'Third'), (3, 'Fourth') - -#### (1, 'First'), (2, 'Second'), (3, 'Third'), (4, 'Fourth') - -> zip(\*iterables) : creates a zip object filled with tuples that combine 1 to 1 the items in each provided iterable. -> Functions that analyze iterable - -**len(iterable) : returns the count of the number of items.** - -**max(\*args, key=None) : returns the largest of two or more arguments.** - -**max(iterable, key=None) : returns the largest item in the iterable.** - -_key optional function which converts an item to a value to be compared. -min works the same way as max_ - -**sum(iterable) : used with a list of numbers to generate the total.** - -_There is a faster way to concatenate an array of strings into one string, so do not use sum for that._ - -**any(iterable) : returns True if any items in the iterable are true.** - -**all(iterable) : returns True is all items in the iterable are true.** - -### Working with dictionaries - -**dir(dictionary) : returns the list of keys in the dictionary. -Working with sets** - -**Union : The pipe | operator or union(\*sets) function can be used to produce a new set which is a combination of all elements in the provided set.** - - a = {1, 2, 3} - b = {2, 4, 6} - print(a | b) # => {1, 2, 3, 4, 6} - -#### Intersection : The & operator ca be used to produce a new set of only the elements that appear in all sets. - - a = {1, 2, 3} - b = {2, 4, 6} - print(a & b) # => {2} - Difference : The — operator can be used to produce a new set of only the elements that appear in the first set and NOT the others. - -**Symmetric Difference : The ^ operator can be used to produce a new set of only the elements that appear in exactly one set and not in both.** - - a = {1, 2, 3} - b = {2, 4, 6} - print(a — b) # => {1, 3} - print(b — a) # => {4, 6} - print(a ^ b) # => {1, 3, 4, 6} - ---- - -### **For Statements In python, there is only one for loop.** - -Always Includes: - -> 1. The for keyword -> 2. A variable name -> 3. The 'in' keyword -> 4. An iterable of some kid -> 5. A colon -> 6. On the next line, an indented block of code called the for clause. - -**You can use break and continue statements inside for loops as well.** - -**You can use the range function as the iterable for the for loop.** - - print('My name is') - for i in range(5): - print('Carlita Cinco (' + str(i) + ')') - - total = 0 - for num in range(101): - total += num - print(total) - Looping over a list in Python - for c in ['a', 'b', 'c']: - print(c) - - lst = [0, 1, 2, 3] - for i in lst: - print(i) - -**_Common technique is to use the len() on a pre-defined list with a for loop to iterate over the indices of the list._** - - supplies = ['pens', 'staplers', 'flame-throwers', 'binders'] - for i in range(len(supplies)): - print('Index ' + str(i) + ' in supplies is: ' + supplies[i]) - -**You can loop and destructure at the same time.** - - l = 1, 2], [3, 4], [5, 6 - for a, b in l: - print(a, ', ', b) - -> Prints 1, 2 - -> Prints 3, 4 - -> Prints 5, 6 - -**You can use values() and keys() to loop over dictionaries.** - - spam = {'color': 'red', 'age': 42} - for v in spam.values(): - print(v) - -_Prints red_ - -_Prints 42_ - - for k in spam.keys(): - print(k) - -_Prints color_ - -_Prints age_ - -**For loops can also iterate over both keys and values.** - -**Getting tuples** - - for i in spam.items(): - print(i) - -_Prints ('color', 'red')_ - -_Prints ('age', 42)_ - -_Destructuring to values_ - - for k, v in spam.items(): - print('Key: ' + k + ' Value: ' + str(v)) - -_Prints Key: age Value: 42_ - -_Prints Key: color Value: red_ - -**Looping over string** - - for c in "abcdefg": - print(c) - -**When you order arguments within a function or function call, the args need to occur in a particular order:** - -_formal positional args._ - -\*args - -_keyword args with default values_ - -\*\*kwargs - - def example(arg_1, arg_2, *args, **kwargs): - pass - - def example2(arg_1, arg_2, *args, kw_1="shark", kw_2="blowfish", **kwargs): - pass - ---- - -### **Importing in Python** - -**Modules are similar to packages in Node.js** -Come in different types: - -Built-In, - -Third-Party, - -Custom. - -**All loaded using import statements.** - ---- - -### **Terms** - -> module : Python code in a separate file. -> package : Path to a directory that contains modules. -> init.py : Default file for a package. -> submodule : Another file in a module's folder. -> function : Function in a module. - -**A module can be any file but it is usually created by placing a special file init.py into a folder. pic** - -_Try to avoid importing with wildcards in Python._ - -_Use multiple lines for clarity when importing._ - - from urllib.request import ( - HTTPDefaultErrorHandler as ErrorHandler, - HTTPRedirectHandler as RedirectHandler, - Request, - pathname2url, - url2pathname, - urlopen, - ) - ---- - -### Watching Out for Python 2 - -**Python 3 removed <> and only uses !=** - -**format() was introduced with P3** - -**All strings in P3 are unicode and encoded. -md5 was removed.** - -**ConfigParser was renamed to configparser -sets were killed in favor of set() class.** - -#### **print was a statement in P2, but is a function in P3.** - -### Topics revisited (in python syntax) - -### Cheat Sheet: - -#### If you found this guide helpful feel free to checkout my github/gists where I host similar content: - -bgoonz's gists · GitHub - -bgoonz — Overview -
    - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
    - -Or Checkout my personal Resource Site: - -a/A-Student-Resources -
    - -Edit descriptiongoofy-euclid-1cd736.netlify.app
    - -### Python Cheat Sheet: - -### If you found this guide helpful feel free to checkout my GitHub/gists where I host similar content: - -bgoonz's gists -
    - -Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…gist.github.com
    - -bgoonz — Overview -
    - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
    - -### Or Checkout my personal Resource Site: - -### Discover More: - -Web-Dev-Hub -
    - -Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…bgoonz-blog.netlify.app
    - -By Bryan Guner on [March 6, 2021](https://medium.com/p/5cfdf3d2bdfb). - -Canonical link - -August 6, 2021. diff --git a/notes/articles/medium/markdown/Quick-Web-Developers-Website-Checklist---A-List-Of-Tools-For-Improvement.md b/notes/articles/medium/markdown/Quick-Web-Developers-Website-Checklist---A-List-Of-Tools-For-Improvement.md deleted file mode 100644 index 7cc7dcfbc2..0000000000 --- a/notes/articles/medium/markdown/Quick-Web-Developers-Website-Checklist---A-List-Of-Tools-For-Improvement.md +++ /dev/null @@ -1,884 +0,0 @@ -# Quick Web Developers Website Checklist & A List Of Tools For Improvement - -A set of questions you should use before handing off your application to the client. - ---- - -### Quick Web Developers Website Checklist & A List Of Tools For Improvement - -#### A set of questions you should use before handing off your application to the client. - -
    First off… download this developer checklist extension for chrome that literally evaluates the checkpoints on any webpage you activate it on.. it also provides advice and html validation so that you can improve your site and it's SEO rankings! - -Web Developer Checklist -
    - -Analyses any web page for violations of best practiceschrome.google.com
    - -#### Here it is in action : - -
    ### Remainder of tool list is below this checklist: - ---- - -### Usefulness & Relevance: - -> _Does the content meet user needs, goals, and interests?_ - -> _Does the content meet business goals?_ - -> _For how long will the content be useful? When should it expire? Has its usefulness already expired?_ - -> _Is the content timely and relevant?_ - ---- - -### Clarity & Accuracy: - -> **Is the content understandable to customers?** - -> **Is the content organized logically & coherently?** - -> **Is the content correct?** - -> **Does the content contain factual errors, typos, or grammatical errors?** - -> **Do images, video, and audio meet technical standards, so they are clear?** - ---- - -### Influence & Engagement: - -> Does the content use the most appropriate techniques to influence or engage customers? - -> Does the content execute those techniques effectively? - -> Does the content use too many or too few techniques for the context? - ---- - -### Completeness: - -> Does the content include all of the information customers need or might want about a topic? - -> Does the content include too much or too little information about a topic for the context? - -### Voice & Style: - -> Does the content consistently reflect the editorial or brand voice? - -> Does its tone adjust appropriately to the context — for example, sales versus customer service? - -> Does the content convey the appropriate editorial and brand qualities? - -> Does the content seem to have a style? If so, does the content adhere to it consistently? - -> Does the content read, look, or sound as though it's professionally crafted? - ---- - -### Usability & Findability: - -> Is the content easy to scan or read? - -> Is the content in a usable format, including headings, bulleted lists, tables, white space, or similar techniques, as appropriate to the content? - -> Does the content have the appropriate metadata? - -> Does the content follow search engine optimization (SEO) guidelines — such as using keywords — without sacrificing quality in other areas? - -> Can customers find the content when searching using relevant keywords? - ---- - -### SEO Advice From Google: - -### Help Google find your pages - -- Ensure that all pages on the site can be reached by a link from another findable page. The referring link should include either text or, for images, an alt attribute, that is relevant to the target page. Crawlable links are `` tags with an href attribute. -- Provide a sitemap file with links that point to the important pages on your site. Also provide a page with a human-readable list of links to these pages (sometimes called a site index or site map page). -- Limit the number of links on a page to a reasonable number (a few thousand at most). -- Make sure that your web server correctly supports the `If-Modified-Since` HTTP header. This feature directs your web server to tell Google if your content has changed since we last crawled your site. Supporting this feature saves you bandwidth and overhead. -- Use the robots.txt file on your web server to manage your crawling budget by preventing crawling of infinite spaces such as search result pages. Keep your robots.txt file up to date. Learn how to manage crawling with the robots.txt file. Test the coverage and syntax of your robots.txt file using the robots.txt Tester. - -**Ways to help Google find your site:** - -- Ask Google to crawl your pages. -- Make sure that any sites that should know about your pages are aware your site is online. - -### Help Google understand your pages - -- Create a useful, information-rich site, and write pages that clearly and accurately describe your content. -- Think about the words users would type to find your pages, and make sure that your site actually includes those words within it. -- Ensure that your `` elements and `alt` attributes are descriptive, specific, and accurate.</span> -- <span id="86c8">Design your site to have a clear conceptual page hierarchy.</span> -- <span id="aed5">Follow our recommended best practices for <a href="https://developers.google.com/search/docs/advanced/guidelines/google-images" class="markup--anchor markup--li-anchor">images</a>, <a href="https://developers.google.com/search/docs/advanced/guidelines/video" class="markup--anchor markup--li-anchor">video</a>, and <a href="https://developers.google.com/search/docs/guides/intro-structured-data" class="markup--anchor markup--li-anchor">structured data</a>.</span> -- <span id="67f4">When using a content management system (for example, Wix or WordPress), make sure that it creates pages and links that search engines can crawl.</span> -- <span id="5fcd">To help Google fully understand your site's contents, allow all site assets that would significantly affect page rendering to be crawled: for example, CSS and JavaScript files that affect the understanding of the pages. The Google indexing system renders a web page as the user would see it, including images, CSS, and JavaScript files. To see which page assets that Googlebot cannot crawl use the <a href="https://support.google.com/webmasters/answer/9012289" class="markup--anchor markup--li-anchor">URL Inspection tool</a>; to debug directives in your robots.txt file, use the <a href="https://support.google.com/webmasters/answer/6062598" class="markup--anchor markup--li-anchor">robots.txt Tester</a> tool.</span> -- <span id="b8ef">Allow search bots to crawl your site without session IDs or URL parameters that track their path through the site. These techniques are useful for tracking individual user behavior, but the access pattern of bots is entirely different. Using these techniques may result in incomplete indexing of your site, as bots may not be able to eliminate URLs that look different but actually point to the same page.</span> -- <span id="e5c6">Make your site's important content visible by default. Google is able to crawl HTML content hidden inside navigational elements such as tabs or expanding sections, however we consider this content less accessible to users, and believe that you should make your most important information visible in the default page view.</span> -- <span id="58bf">Make a reasonable effort to ensure that advertisement links on your pages do not affect search engine rankings. For example, use <a href="https://developers.google.com/search/docs/advanced/robots/intro" class="markup--anchor markup--li-anchor">robots.txt</a>, `rel="nofollow"`, or `rel="sponsored"` to prevent advertisement links from being followed by a crawler.</span> - -### Help visitors use your pages - -- <span id="76dc">Try to use text instead of images to display important names, content, or links. If you must use images for textual content, use the `alt` attribute to include a few words of descriptive text.</span> -- <span id="d45e">Ensure that all links go to live web pages. Use <a href="https://validator.w3.org/" class="markup--anchor markup--li-anchor">valid HTML</a>.</span> -- <span id="8b66">Optimize your page loading times. Fast sites make users happy and improve the overall quality of the web (especially for those users with slow Internet connections). Google recommends that you use tools like <a href="https://developers.google.com/speed/pagespeed/insights/" class="markup--anchor markup--li-anchor">PageSpeed Insights</a> and <a href="https://www.webpagetest.org/" class="markup--anchor markup--li-anchor">Webpagetest.org</a> to test the performance of your page.</span> -- <span id="5f39">Design your site for all device types and sizes, including desktops, tablets, and smartphones. Use the <a href="https://search.google.com/test/mobile-friendly" class="markup--anchor markup--li-anchor">Mobile-Friendly Test</a> to test how well your pages work on mobile devices, and get feedback on what needs to be fixed.</span> -- <span id="5f9b">Ensure that your site <a href="https://developers.google.com/search/docs/advanced/guidelines/browser-compatibility" class="markup--anchor markup--li-anchor">appears correctly in different browsers</a>.</span> -- <span id="717b">If possible, <a href="https://developers.google.com/search/docs/advanced/security/https" class="markup--anchor markup--li-anchor">secure your site's connections</a> with HTTPS. Encrypting interactions between the user and your website is a good practice for communication on the web.</span> -- <span id="4156">Ensure that your pages are useful for readers with visual impairments, for example, by testing usability with a screen-reader.</span> - -### Basic principles - -- <span id="0251">Make pages primarily for users, not for search engines.</span> -- <span id="f565">Don't deceive your users.</span> -- <span id="5f8a">Avoid tricks intended to improve search engine rankings. A good rule of thumb is whether you'd feel comfortable explaining what you've done to a website that competes with you, or to a Google employee. Another useful test is to ask, "Does this help my users? Would I do this if search engines didn't exist?"</span> -- <span id="9acc">Think about what makes your website unique, valuable, or engaging. Make your website stand out from others in your field.</span> - -### Specific guidelines - -**Avoid** the following techniques: - -- <span id="2686"><a href="https://developers.google.com/search/docs/advanced/guidelines/auto-gen-content" class="markup--anchor markup--li-anchor">Automatically generated content</a></span> -- <span id="a921">Participating in <a href="https://developers.google.com/search/docs/advanced/guidelines/link-schemes" class="markup--anchor markup--li-anchor">link schemes</a></span> -- <span id="bbd9">Creating pages with <a href="https://support.google.com/webmasters/answer/66361" class="markup--anchor markup--li-anchor">little or no original content</a></span> -- <span id="7ddf"><a href="https://developers.google.com/search/docs/advanced/guidelines/cloaking" class="markup--anchor markup--li-anchor">Cloaking</a></span> -- <span id="e9b8"><a href="https://developers.google.com/search/docs/advanced/guidelines/sneaky-redirects" class="markup--anchor markup--li-anchor">Sneaky redirects</a></span> -- <span id="47d2"><a href="https://developers.google.com/search/docs/advanced/guidelines/hidden-text-links" class="markup--anchor markup--li-anchor">Hidden text or links</a></span> -- <span id="7ae2"><a href="https://developers.google.com/search/docs/advanced/guidelines/doorway-pages" class="markup--anchor markup--li-anchor">Doorway pages</a></span> -- <span id="98d8"><a href="https://developers.google.com/search/docs/advanced/guidelines/scraped-content" class="markup--anchor markup--li-anchor">Scraped content</a></span> -- <span id="156f">Participating in <a href="https://developers.google.com/search/docs/advanced/guidelines/affiliate-programs" class="markup--anchor markup--li-anchor">affiliate programs without adding sufficient value</a></span> -- <span id="42e4">Loading pages with <a href="https://developers.google.com/search/docs/advanced/guidelines/irrelevant-keywords" class="markup--anchor markup--li-anchor">irrelevant keywords</a></span> -- <span id="f583">Creating pages with <a href="https://developers.google.com/search/docs/advanced/guidelines/malicious-behavior" class="markup--anchor markup--li-anchor">malicious behavior</a>, such as phishing or installing viruses, trojans, or other badware</span> -- <span id="777a">Abusing <a href="https://developers.google.com/search/docs/guides/sd-policies" class="markup--anchor markup--li-anchor">structured data</a> markup</span> -- <span id="6c9f">Sending <a href="https://developers.google.com/search/docs/advanced/guidelines/automated-queries" class="markup--anchor markup--li-anchor">automated queries</a> to Google</span> - -**Follow** good practices: - -- <span id="68a7">Monitoring your site for <a href="https://developers.google.com/search/docs/advanced/security/what-is-hacked" class="markup--anchor markup--li-anchor">hacking</a> and removing hacked content as soon as it appears</span> -- <span id="8141">Preventing and removing <a href="https://developers.google.com/search/docs/advanced/guidelines/user-gen-spam" class="markup--anchor markup--li-anchor">user-generated spam</a> on your site</span> - -If your site violates one or more of these guidelines, then Google may take <a href="https://support.google.com/webmasters/answer/9044175" class="markup--anchor markup--p-anchor">manual action</a> against it. Once you have remedied the problem, you can <a href="https://support.google.com/webmasters/answer/35843" class="markup--anchor markup--p-anchor">submit your site for reconsideration</a>. - ---- - -### Website Launch Checklist: - -### Website design checklist - -It's all too easy to miss (or break) something during the many back-and-forths, client feedback sessions, and other design iterations you go through. That's why we created the design checklist below will help you go back and check for any design mistakes. - -To start, be sure to check your: - -- <span id="1b13">Spacing: Is spacing consistent across the site (i.e., did you stick to that 8px grid, or let a rogue 18px in there)? Do all elements have enough breathing room?</span> -- <span id="589b">Colors: Have you stuck to a consistent, harmonious color palette? Are all instances of the brand blue _actually_ the brand blue?</span> -- <span id="dcfc">Shadows: If you used drop shadows, is the light source consistent for each and every one? Did you use the same blur, opacity, and spread values?</span> -- <span id="021b">Typography: Is your font stack logical and consistent (i.e., is there a reason that element is set in a sans)? Are your heading sizes consistent? Have you used proper (not faux) italics and bolding? Do all text links look right? Is all text both legible and readable?</span> -- <span id="fbb2">Imagery: Do any images look blurry, pixelated, or otherwise funky? Are any images broken or crazily heavy in terms of file size? Do all _non-decorative_ images have alt tags?</span> -- <span id="4760">Logo: It's (usually) just another image, but it's so important it warrants its own step. Is it the latest version? Is it crisp (not blurry or pixelated)?</span> - -Once you've made these initial visual checks, you'll want to ensure that your site's appearance is consistent and functional on any screen. - -### Cross-browser appearance - -Different browsers may render your website in different ways, so it's important to test your site in different browsers. Take a look at <a href="http://www.w3schools.com/browsers/browsers_stats.asp" class="markup--anchor markup--p-anchor">W3's browser stats</a> to see where you should focus your testing. (Though if you're working on a redesign, browser-usage stats will be more useful.) - -During this process (and the next, in multi-device testing) you'll want to make sure your layouts, typography, navigation, and other design elements are displaying properly. - -The elements that tend to vary most across browsers, and therefore are most important to check, are: - -- <span id="f7ff">Fonts</span> -- <span id="32b8">Colors/gradients</span> -- <span id="5871">Images</span> -- <span id="be77">Logo</span> - -### Cross-device appearance - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*zXLmWvXkMI5Wv2LF.jpeg" class="graf-image" /></figure>Make sure your site looks and performs beautifully on any device. - -There have never been more web-capable devices around, and with that comes a staggering array of screen sizes. Done right, your site _should_ perform well on any screen size, but be sure to double check. (You are a perfectionist after all, right?) - -This is also where mobile navigation is crucial. Be sure to test out the user's ability to navigate around the website on a touchscreen device, and make sure nothing gets lost in device transition. - -In Webflow, we make it easy for you to test the most popular devices and preview your website on almost any size, streamlining the process of cross-device testing all in one place. Of course, nothing replaces real-world testing on a variety of devices as small details may differ on the real device. - -### Image optimization - -Images and graphics are an important element of many websites, so you'll want to make sure they display properly, especially on all those ultra-high-definition devices (like Apple's Retina screens) out there. - -The rule of thumb is to upload your image at twice the size it'll display on your site. In some cases, you can upload two images: an actual-size version for lower-res devices, and another that's twice the size for high-res devices. - -Why? Because the heavier the image, the slower your page will load, and the worse your user experience will be (which also negatively affects SEO, which we'll cover later on). - -In Webflow, we automatically scale, compress, and optimize images for every device. Learn more about our <a href="https://webflow.com/feature/responsive-images" class="markup--anchor markup--p-anchor">responsive images feature or check out our more detailed</a> article on <a href="https://webflow.com/blog/how-to-boost-your-sites-performance" class="markup--anchor markup--p-anchor">image optimization</a>. - -### Website functionality testing - -Design and functionality go hand in hand, but I like to isolate the two to make sure the website both _looks_ the way it was designed to and that it _performs_ as intended. - -### Integration testing - -This one is super important, and can range from a quick task to a giant one, depending on how many integrations you have. Typically, I'll create a list of integrations _as I add them_ so I don't forget later on. - -Some common integrations to test might be: - -- <span id="54e1">Web forms (check that the forms work _and_ that submitted information goes to the right place)</span> -- <span id="5ad2">Autoresponders</span> -- <span id="1079">Marketing emails (MailChimp, Constant Contact, HubSpot, drip campaigns, etc.)</span> -- <span id="10e0">RSS feeds</span> -- <span id="fe8e">Ecommerce</span> -- <span id="5f3d">CRM</span> -- <span id="dc4a">CMS</span> - -### Link testing - -This one can be a doozy, simply because most sites have dozens (if not hundreds) of links. More often than not, there's a link or two that goes nowhere, and it's important to find them before your end-users do. - -Some of the most important links to check are: - -- <span id="fd34">Top navigation links</span> -- <span id="88d4">Footer links</span> -- <span id="d42d">Social media links (Facebook, Twitter, etc.)</span> -- <span id="cde4">Logo (typically links to the home page)</span> - -Rather than doing all this manually, I'd suggest trying a link crawler like the <a href="https://validator.w3.org/checklink" class="markup--anchor markup--p-anchor">W3C Link Checker</a>, the Chrome plugin <a href="https://chrome.google.com/webstore/detail/check-my-links/ojkcdipcgfaekbeaelaapakgnjflfglf?hl=en-GB" class="markup--anchor markup--p-anchor">Check My Links</a>, or <a href="http://www.screamingfrog.co.uk/seo-spider/" class="markup--anchor markup--p-anchor">Screaming Frog</a> (which is excellent for SEO audits, too). - -### Content editing - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*HxnVQM9RoqyuTlLP.jpeg" class="graf-image" /></figure>Give the king its due. - -Content is king, and the testing process should be fit for one. Typically this involves making sure that all content has been updated and approved. I can't tell you how many websites I've found that _still_ have a l*orem ipsum* paragraph somewhere. - -Now, if you practice <a href="https://webflow.com/blog/content-first-design" class="markup--anchor markup--p-anchor">content-first design</a>, you should have final content already in place, so you can focus on more fine-toothed-comb review, like proofing for spelling and grammatical errors. - -It's also important to note here that it's okay for content to be changed later on. Clients, team members, or you can always adjust text through a CMS. The main goal here is to ensure that your website content isn't complete gibberish. - -### Search engine optimization (SEO) - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*Ukayn_ZyXfN-Wg-M.jpeg" class="graf-image" /></figure>Analyzing and optimizing your website *after* publishing is a never-ending process. And you need to consider semantic site structure from the get-go. But that doesn't mean you won't benefit from an SEO review before you hit publish. - -There are multiple things that can be done to optimize your website for search engines. - -### 1. Use proper semantic structure - -Web crawlers (like Google's bots) read through your website to get an understanding of your content, so that search engines know to display your website when people search for it. To help them crawl your site, you need to use language they'll understand. - -Historically, this has meant using the following semantic tags: - -- <span id="93f0">h1-h6 (heading tags)</span> -- <span id="f999">p (paragraph tags)</span> -- <span id="c0ab">ul/ol (unordered and ordered Lists)</span> - -You can also go above and beyond with some new <a href="https://webflow.com/blog/html5-semantic-elements-and-webflow-the-essential-guide" class="markup--anchor markup--p-anchor">HTML5 semantic tags</a>: - -- <span id="4d08"><article></span> -- <span id="8074"><aside></span> -- <span id="9b75"><details></span> -- <span id="0652"><figcaption></span> -- <span id="721c"><figure></span> -- <span id="0cc5"><footer></span> -- <span id="2e07"><header></span> -- <span id="0e37"><main></span> -- <span id="6be6"><mark></span> -- <span id="1656"><nav></span> -- <span id="e390"><section></span> -- <span id="2858"><summary></span> -- <span id="d970"><time></span> - -These tags are important because they let you identify the content that's most relevant to users. In short: making it easy for search engines makes it easier for users to find you. - -### 2. Meta SEO tags - -Aside from on-page structure, you can also help web crawlers understand your site by titling and describing your pages as a whole. We outline a few tips <a href="https://webflow.com/blog/website-seo" class="markup--anchor markup--p-anchor">on website SEO on our blog</a>, narrowed down to 2 main considerations below. - -#### Meta title - -Your page's meta title translates to the linked text people will see on search engine result pages (SERPs). It also displays on the browser tab when people click through to your page. Some best practices include: - -- <span id="ed19">Define the page's central topic</span> -- <span id="c50a">Keep it under 70 characters in length (including spaces)</span> -- <span id="e656">Use relevant keywords</span> -- <span id="c74d">Put important keywords in the front of the title</span> - -#### Meta description - -The meta description is a short sentence (or two) that describes what your website has to offer. It will (sometimes) show up below your meta title in search results. - -Some best practices include: - -- <span id="aec5">Include keywords that describe the page</span> -- <span id="022c">Don't go over 160 characters</span> -- <span id="13ac">Write your description for people, not robots. (Google doesn't use descriptions in web rankings).</span> - -### 3. Open Graph settings - -Social media has become a key element of SEO, so it's crucial that you amplify this process by providing effective Open Graph information. Open Graph settings include three pieces of content: title, description, and an image. - -The title and description follow the same rules as their SEO counterparts, but instead of showing up in search results, they appear as the default title and description on social media platforms when shared. - -This is hugely beneficial because it lets you determine what the messaging (and image) will be when others share your website, helping you keep control of your brand. - ---- - ---- - -### Tool List: - -### Update: - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*8luiRPwHqkyfqJfb" class="graf-image" /></figure><a href="https://caniuse.com/" class="markup--anchor markup--p-anchor">Can I UseProvides browser support information of front-end web technologies. Enter a search term to find out which browsers support it. <em>caniuse.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*t50QcwzBkwFuth4o" class="graf-image" /></figure><a href="https://html-online.com/editor/" class="markup--anchor markup--p-anchor">Online HTML EditorFree online HTML editor with WYSIWYG and source composer and instant preview and many useful built-in features <em>html-online.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*SnFMpz919DboGmr-" class="graf-image" /></figure><a href="https://html-cleaner.com/" class="markup--anchor markup--p-anchor">Web CleanerOnline HTML, CSS and JavaScript cleaner and code editors with syntax highlighting and customizable cleaning features. <em>html-cleaner.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*2KRsAowQaufNBiSs" class="graf-image" /></figure><a href="https://wordhtml.com/" class="markup--anchor markup--p-anchor">Word HTMLFree online Word and other rich text editor and HTML converter. Copy-paste your document in the editor and switch to HTML view to get the code. <em>wordhtml.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*A_wBLhhToeFlXuLg" class="graf-image" /></figure><a href="https://htmlcheatsheet.com/" class="markup--anchor markup--p-anchor">HTML Cheat SheetHTML, CSS, JavaScript and other web technology cheat sheet with interactive user interface. Grab the code you're looking for quickly. <em>htmlcheatsheet.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*393SncqM14lxdAYX" class="graf-image" /></figure><a href="https://stackoverflow.com/" class="markup--anchor markup--p-anchor">Stack OverflowHuge programmer community where you usually don't have to ask for help because probably someone has already answered the same question. <em>stackoverflow.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*veTjmob-9SlcsbfY" class="graf-image" /></figure><a href="https://www.w3schools.com/" class="markup--anchor markup--p-anchor">w3schoolsThe place to learn web technologies. There's a big chance that this site gives the first search result when you're looking for a HTML term. <em>w3schools.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*mcOcJb9_CRucZ8Hi" class="graf-image" /></figure><a href="https://developer.mozilla.org/" class="markup--anchor markup--p-anchor">Mozzilla Developer NetworkAn evolving learning platform for web technologies. Providing tutorials, developer tools and the information to easily build projects. <em>developer.mozilla.org</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*1A0zYmYhuNwVv-JD" class="graf-image" /></figure><a href="https://validator.w3.org/" class="markup--anchor markup--p-anchor">Markup ValidatorEnter the link of a webpage and the online tool will highlight the errors and warnings to fix in the source code. <em>validator.w3.org</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*qkBfaTWhlKlbtmsf" class="graf-image" /></figure><a href="https://github.com/" class="markup--anchor markup--p-anchor">GitHubCollaborate with other developers. Fork, send pull requests and manage all your public and private git repositories. <em>github.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*xuAlgMUU6yPrTp-y" class="graf-image" /></figure><a href="https://bitbucket.org/" class="markup--anchor markup--p-anchor">BitbucketWeb-based hosting service for development projects with version control system that makes it easy for you to collaborate with your team. <em>bitbucket.org</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*XiFbqTuL0zs0ZeWn" class="graf-image" /></figure><a href="https://dribbble.com/" class="markup--anchor markup--p-anchor">DribbleTell others what are you working on! Dribbble is a community of designers sharing screenshots of their work, process, and projects. <em>dribbble.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*Z7rf2N2ZanFTyC24" class="graf-image" /></figure><a href="https://builtwith.com/" class="markup--anchor markup--p-anchor">Built WithEnter a domain name to find out who is hosting it, what CMS and framework is used and many other insights. <em>builtwith.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*JAKvGWN_Sd05kCwa" class="graf-image" /></figure><a href="https://htmltidy.net/" class="markup--anchor markup--p-anchor">HTML TidyAn online tool for checking and cleaning up HTML source files. Useful for finding and correcting errors in deeply nested HTML. <em>htmltidy.net</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*NobceO9h1WGoiAh5" class="graf-image" /></figure><a href="https://divtable.com/" class="markup--anchor markup--p-anchor">Div TableCreate or convert tables to responsive div tags with a few clicks. Use the provided CSS code to render the divs as table cells. <em>divtable.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*NFqBo-YVX2D2dtFh" class="graf-image" /></figure><a href="https://getbootstrap.com/" class="markup--anchor markup--p-anchor">BootstrapThe most popular free and open-source HTML, CSS, and JS framework makes front-end development easier and faster. <em>getbootstrap.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*rHGXn1mVlS3XJNCV" class="graf-image" /></figure><a href="https://htmlg.com/html-editor/" class="markup--anchor markup--p-anchor">HTMLGProfessional HTML editor. The free version is enough to do magic with your markup. Tag and attribute manager filter etc. <em>htmlg.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*zzrT9kYMdxxAHwb8" class="graf-image" /></figure><a href="https://developers.facebook.com/" class="markup--anchor markup--p-anchor">Facebook DevelopersDeveloper tools for login, share widget, analytics, monetization, messenger platform and more from the biggest social media site. <em>developers.facebook.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*CmpW2L4pVbESIh5J" class="graf-image" /></figure><a href="https://search.google.com/test/mobile-friendly" class="markup--anchor markup--p-anchor">Google Mobile-Friendly TestCheck if Google considers your web page mobile-friendly and adjust the deficiencies if there is any. <em>google.com/mobile-friendly</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*mKshXXHbzoStzvjr" class="graf-image" /></figure><a href="https://www.webpagetest.org/" class="markup--anchor markup--p-anchor">Webpage Speed TestAnalize the loading speed of a website from many available servers. The website creates a detailed analysis with screenshot and waterfall view. <em>webpagetest.org</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*sYIvpZGnkNhf-_XC" class="graf-image" /></figure><a href="https://netrenderer.com/" class="markup--anchor markup--p-anchor">NetRendererRenders quickly a webpage with the selected version of the old Internet Explorer web browser. NetRenderer goes back to IE version 5.5. <em>netrenderer.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*unIWXerRzCuxrzng" class="graf-image" /></figure><a href="http://browsershots.org/" class="markup--anchor markup--p-anchor">Browser ShotsCreate the screenshot of a webpage with many available browsers in various operating systems. <em>browsershots.org</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*bX3AIaYOSzadB8t6" class="graf-image" /></figure><a href="https://developers.google.com/speed/pagespeed/insights/" class="markup--anchor markup--p-anchor">PageSpeed InsightsThis tool by Google analyzes the submitted link from mobile and desktop to suggest you what to consider optimizing. <em>developers.google.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*v1hxqLrwUWL2dbBX" class="graf-image" /></figure><a href="https://fonts.google.com/" class="markup--anchor markup--p-anchor">Google FontsAn interactive directory of over 800 free hosted web fonts. It allows to optimize loading speed by including only what you need. <em>fonts.google.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*n4slofmCAW3PUOTn" class="graf-image" /></figure><a href="https://fontawesome.com/" class="markup--anchor markup--p-anchor">Font AwesomeThe most popular icon set based on CSS and LESS. The vector icons can be customized as text — size, color, drop shadow <em>fontawesome.io</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*_k2GQpr-IXMCfCbD" class="graf-image" /></figure><a href="https://rgbcolorcode.com/" class="markup--anchor markup--p-anchor">RGB Color CodesSearch and save color codes. Search by name or mix the RGB, HSV or CMYK values. Use the generated HTML/CSS codes. <em>rgbcolorcode.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*IH19Lh2SggZ5fNd_" class="graf-image" /></figure><a href="https://www.freepik.com/" class="markup--anchor markup--p-anchor">FreePicBrowse the large directory of free photos, vector arts, icons, illustrations, PSD files at FreePic. <em>freepik.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*g9YcUHOEU2oybdxl" class="graf-image" /></figure><a href="https://placehold.it/" class="markup--anchor markup--p-anchor">Placehold.it/Image placeholders with customizable size. Just add the image resolution after the domain name, for example placehold.it/400x250 <em>placehold.it</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*PSn8d5FL7_ngjJtU" class="graf-image" /></figure><a href="https://www.xml-sitemaps.com/" class="markup--anchor markup--p-anchor">XML SitemapsGenerate XML sitemaps and URL list of a website. The crawl limit is 500 pages. <em>xml-sitemaps.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*673487vh2n0o7Ub6" class="graf-image" /></figure><a href="http://www.brokenlinkcheck.com/" class="markup--anchor markup--p-anchor">Broken Link CheckerCrawl a domain for dead links. Locates both internal and external links pointing to 404 error pages. <em>brokenlinkcheck.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*NrZDjNLAdMcfK8Hy" class="graf-image" /></figure><a href="https://codepen.io/" class="markup--anchor markup--p-anchor">CodepenRegister to create, save and share HTML-CSS-JS code snippets and run them online. <em>codepen.io</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*1EEf11CeSLOOAAyu" class="graf-image" /></figure><a href="https://jsfiddle.net/" class="markup--anchor markup--p-anchor">JSFiddleSimilar to Codepen but this one doesn't require registration. Test HTML-CSS-JS code online and save your small project in a shareable URL. <em>jsfiddle.net</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*2Aq8QOCznCo11ypk" class="graf-image" /></figure><a href="https://wordpress.org/" class="markup--anchor markup--p-anchor">WordPress.OrgMore than 10 million websites use this free and open-source content management system based on PHP-MySql. <em>wordpress.org</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*CJX2RwykNQ9O0RbL" class="graf-image" /></figure><a href="https://www.theblogstarter.com/" class="markup--anchor markup--p-anchor">Blog StarterA free guide that shows beginners how to start a blog using WordPress.org <em>theblogstarter.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*QSwvNaVB8SOgyDqp" class="graf-image" /></figure><a href="https://websitesetup.org/" class="markup--anchor markup--p-anchor">Website SetupA friendly guide about how to make a website, discussing the hosting, the CMS, domain name and promotion. <em>websitesetup.org</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*m7_ugygIICt4VLea" class="graf-image" /></figure><a href="https://www.expireddomains.net/" class="markup--anchor markup--p-anchor">Expired DomainsHunt for expired domain names or get inspiration for your next project. It's worth registering for an account on this free website. <em>expireddomains.net</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*PNRVuj1GX-jgppng" class="graf-image" /></figure><a href="https://badhtml.com/" class="markup--anchor markup--p-anchor">Bad HTMLThe ugliest website on the internet, collecting bad UI/UX practices. A deterrent example about how not to build a website. <em>badhtml.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*66ncH3hioTVPIr2l" class="graf-image" /></figure><a href="https://1stwebdesigner.com/" class="markup--anchor markup--p-anchor">1st Web DesignerFollow this web design blog to find out what's new in freelance, marketing, UX etc. categories. <em>1stwebdesigner.com</em></a> - ---- - -<a href="http://toptal.com/developers" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://toptal.com/developers"><strong>Hire Freelance Developers from the Top 3% - Toptal®</strong> -<br/> - -<em>Toptal is a marketplace for top developers, engineers, programmers, coders, architects, and consultants. Top companies…</em>toptal.com</a><a href="http://toptal.com/developers" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://chrome.google.com/webstore/detail/web-developer-checklist/iahamcpedabephpcgkeikbclmaljebjp?hl=en-US" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://chrome.google.com/webstore/detail/web-developer-checklist/iahamcpedabephpcgkeikbclmaljebjp?hl=en-US"><strong>Web Developer Checklist</strong> -<br/> - -<em>Analyses any web page for violations of best practices</em>chrome.google.com</a><a href="https://chrome.google.com/webstore/detail/web-developer-checklist/iahamcpedabephpcgkeikbclmaljebjp?hl=en-US" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://addons.mozilla.org/en-US/firefox/addon/webdeveloperchecklist/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://addons.mozilla.org/en-US/firefox/addon/webdeveloperchecklist/"><strong>Web Developer Checklist - Get this Extension for 🦊 Firefox (en-US)</strong> -<br/> - -<em>Download Web Developer Checklist for Firefox. Analyzes any web page for violations of best practices.</em>addons.mozilla.org</a><a href="https://addons.mozilla.org/en-US/firefox/addon/webdeveloperchecklist/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://validator.w3.org/checklink" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://validator.w3.org/checklink"><strong>Link Checker</strong> -<br/> - -<em>Check links and anchors in Web pages or full Web sites This Link Checker looks for issues in links, anchors and…</em>validator.w3.org</a><a href="https://validator.w3.org/checklink" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://en.wikipedia.org/wiki/Capitalization" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://en.wikipedia.org/wiki/Capitalization"><strong>Capitalization - Wikipedia</strong> -<br/> - -<em>Capitalization ( American English) or capitalisation ( British English) is writing a word with its first letter as a…</em>en.wikipedia.org</a><a href="https://en.wikipedia.org/wiki/Capitalization" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://en.wikipedia.org/wiki/Writing_style" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://en.wikipedia.org/wiki/Writing_style"><strong>Writing style - Wikipedia</strong> -<br/> - -<em>In literature, writing style is the manner of expressing thought in language characteristic of an individual, period…</em>en.wikipedia.org</a><a href="https://en.wikipedia.org/wiki/Writing_style" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://en.wikipedia.org/wiki/American_and_British_English_spelling_differences" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://en.wikipedia.org/wiki/American_and_British_English_spelling_differences"><strong>American and British English spelling differences - Wikipedia</strong> -<br/> - -<em>Despite the various English dialects spoken from country to country and within different regions of the same country…</em>en.wikipedia.org</a><a href="https://en.wikipedia.org/wiki/American_and_British_English_spelling_differences" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="http://browsershots.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://browsershots.org/"><strong>Check Browser Compatibility, Cross Platform Browser Test - Browsershots</strong> -<br/> - -<em>Browsershots makes screenshots of your web design in different operating systems and browsers. It is a free open-source…</em>browsershots.org</a><a href="http://browsershots.org/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://browserling.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://browserling.com/"><strong>Online cross-browser testing</strong> -<br/> - -<em>Browserling did a custom cross-browser testing solution for UK's National Health Service. Our application needs to…</em>browserling.com</a><a href="https://browserling.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.browserstack.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.browserstack.com/"><strong>Most Reliable App & Cross Browser Testing Platform | BrowserStack</strong> -<br/> - -<em>Just played around with BrowserStack: Quite cool, instant access to a browser in a VM with dev tools. Big thanks to…</em>www.browserstack.com</a><a href="https://www.browserstack.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.lambdatest.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.lambdatest.com/"><strong>Most Powerful Cross Browser Testing Tool Online | LambdaTest</strong> -<br/> - -<em>Perform Live Interactive and Automated Cross Browser Testing on 2000+ Real Browsers and Operating Systems Online Run…</em>www.lambdatest.com</a><a href="https://www.lambdatest.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://crossbrowsertesting.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://crossbrowsertesting.com/"><strong>Cross Browser Testing Tool: 2050+ Real Browsers & Devices</strong> -<br/> - -<em>We have estimated that by transitioning to automated front-end visual testing and by having easy access to so many…</em>crossbrowsertesting.com</a><a href="https://crossbrowsertesting.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="http://no-www.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://no-www.org/"><strong>www. is deprecated.</strong> -<br/> - -<em>Stay in touch! Dec 21, 2012 No-WWW now hasa a social media presence! Check us out on Twitter at @www_deprecated . We…</em>no-www.org</a><a href="http://no-www.org/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://www.yes-www.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.yes-www.org/"><strong>www. is not deprecated</strong> -<br/> - -<em>Ever since the first traditional media ads began to appear with Web site addresses in them 25 years ago, people have…</em>www.yes-www.org</a><a href="https://www.yes-www.org/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="http://madskristensen.net/post/url-rewrite-and-the-www-subdomain" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://madskristensen.net/post/url-rewrite-and-the-www-subdomain"><strong>URL rewrite and the www subdomain</strong> -<br/> - -<em>What's the address of your website? www.domain.com or domain.com? There are two camps on the subject of the www…</em>madskristensen.net</a><a href="http://madskristensen.net/post/url-rewrite-and-the-www-subdomain" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://www.google.com/webmasters/tools/mobile-friendly/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.google.com/webmasters/tools/mobile-friendly/"><strong>Mobile-Friendly Test - Google Search Console</strong> -<br/> - -<em>Is your web page mobile-friendly? Test how easily a visitor can use your page on a mobile device. Just enter a page URL…</em>www.google.com</a><a href="https://www.google.com/webmasters/tools/mobile-friendly/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://webdesign.tutsplus.com/articles/quick-tip-dont-forget-the-viewport-meta-tag--webdesign-5972" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://webdesign.tutsplus.com/articles/quick-tip-dont-forget-the-viewport-meta-tag--webdesign-5972"><strong>Quick Tip: Don't Forget the Viewport Meta Tag</strong> -<br/> - -<em>I remember my maiden voyage into responsive web design; I'd used a classic grid, wrestled with a flexible layout, and…</em>webdesign.tutsplus.com</a><a href="https://webdesign.tutsplus.com/articles/quick-tip-dont-forget-the-viewport-meta-tag--webdesign-5972" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://html5tutorial.info/html5-contact.php" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://html5tutorial.info/html5-contact.php"><strong>Input Type : Email,URL,Phone</strong> -<br/> - -<em>Email, Phone number and Website url are the three most commonly used contact detail which has its unique input…</em>html5tutorial.info</a><a href="https://html5tutorial.info/html5-contact.php" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="http://diveintohtml5.info/forms.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://diveintohtml5.info/forms.html"><strong>Web Forms - Dive Into HTML5</strong> -<br/> - -<em>Edit description</em>diveintohtml5.info</a><a href="http://diveintohtml5.info/forms.html" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.browserstack.com/responsive" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.browserstack.com/responsive"><strong>Responsive Testing On 2000+ Real Devices & Browsers | BrowserStack</strong> -<br/> - -<em>Frequently Asked Questions Why is responsive testing critical for your website? Responsive design enables a website to…</em>www.browserstack.com</a><a href="https://www.browserstack.com/responsive" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.uptimerobot.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.uptimerobot.com/"><strong>UptimeRobot | Free Website Monitoring</strong> -<br/> - -<em>Get up to 50 website, port or heartbeat monitors for free. When something happens, we'll notify you via email, SMS…</em>www.uptimerobot.com</a><a href="https://www.uptimerobot.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.statuscake.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.statuscake.com/"><strong>StatusCake: Website Monitoring with Uptime Monitoring solution</strong> -<br/> - -<em>Website Monitoring solution that drives revenue & keeps you online. Track your uptime, page speed, domain, server, &…</em>www.statuscake.com</a><a href="https://www.statuscake.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.google.com/analytics" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.google.com/analytics"><strong>Analytics Tools & Solutions for Your Business - Google Analytics</strong> -<br/> - -<em>Easily access data from other Google solutions while working in Analytics, for a seamless workflow that saves you time…</em>www.google.com</a><a href="https://www.google.com/analytics" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://statcounter.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://statcounter.com/"><strong>Statcounter - Web Analytics Made Easy</strong> -<br/> - -<em>Watch in real time as visitors navigate through your website. Are they flowing through your site the way you expect…</em>statcounter.com</a><a href="https://statcounter.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://clicky.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://clicky.com/"><strong>Real Time Web Analytics</strong> -<br/> - -<em>Clicky Web Analytics is simply the best way to monitor, analyze, and react to your blog or web site's traffic in real…</em>clicky.com</a><a href="https://clicky.com/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://matomo.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://matomo.org/"><strong>Matomo - The Google Analytics alternative that protects your data</strong> -<br/> - -<em>Matomo's the Google Analytics alternative that protects your data and your customer's privacy. A powerful web analytics…</em>matomo.org</a><a href="https://matomo.org/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://developers.google.com/speed/pagespeed/insights/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://developers.google.com/speed/pagespeed/insights/"><strong>PageSpeed Insights</strong> -<br/> - -<em>Have specific, answerable questions about using PageSpeed Insights? Ask your question on Stack Overflow. For general…</em>developers.google.com</a><a href="https://developers.google.com/speed/pagespeed/insights/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://redbot.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://redbot.org/"><strong>REDbot</strong> -<br/> - -<em>Lint for your HTTP resources</em>redbot.org</a><a href="https://redbot.org/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://pageweight.imgix.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://pageweight.imgix.com/"><strong>imgix Page Weight Tool \* Learn how to improve your site or app's speed.</strong> -<br/> - -<em>imgix Page Weight Tool measures the resources on your site and then recommends how to improve your site's load time.</em>pageweight.imgix.com</a><a href="https://pageweight.imgix.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://tinypng.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://tinypng.com/"><strong>TinyPNG - Compress PNG images while preserving transparency</strong> -<br/> - -<em>Excellent question! Let me give you a side by side comparison. Below are two photos of my cousin. The left image is…</em>tinypng.com</a><a href="https://tinypng.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://kraken.io/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://kraken.io/"><strong>Kraken.io Image Optimizer</strong> -<br/> - -<em>Kraken.io is a robust, ultra-fast image optimizer. Thanks to its vast array of optimization algorithms Kraken.io is a…</em>kraken.io</a><a href="https://kraken.io/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://squoosh.app/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://squoosh.app/"><strong>Squoosh</strong> -<br/> - -<em>Compress and compare images with different codecs, right in your browser</em>squoosh.app</a><a href="https://squoosh.app/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="http://pnggauntlet.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://pnggauntlet.com/"><strong>PNGGauntlet - PNG Compression Software</strong> -<br/> - -<em>PNGGauntlet 3.1.2 is a minor update that resolves some bugs, and adds a much-requested option. First, the bugfixes …</em>pnggauntlet.com</a><a href="http://pnggauntlet.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://imageoptim.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://imageoptim.com/"><strong>ImageOptim - better Save for Web</strong> -<br/> - -<em>Reduces image file sizes - so they take up less disk space and down­load faster - by applying advanced compression…</em>imageoptim.com</a><a href="https://imageoptim.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://caniuse.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://caniuse.com/"><strong>Can I use... Support tables for HTML5, CSS3, etc</strong> -<br/> - -<em>Test a feature Our partnership with BrowserStack now lets you test your website for compatibility across 2,000+ real…</em>caniuse.com</a><a href="https://caniuse.com/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://modernizr.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://modernizr.com/"><strong>Modernizr: the feature detection library for HTML5/CSS3</strong> -<br/> - -<em>All web developers come up against differences between browsers and devices. That's largely due to different feature…</em>modernizr.com</a><a href="https://modernizr.com/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://validator.w3.org/i18n-checker/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://validator.w3.org/i18n-checker/"><strong>W3C I18n Checker</strong> -<br/> - -<em>This checker performs various tests on a Web Page to determine its level of internationalisation-friendliness. It also…</em>validator.w3.org</a><a href="https://validator.w3.org/i18n-checker/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.alistapart.com/articles/amoreuseful404/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.alistapart.com/articles/amoreuseful404/"><strong>A More Useful 404</strong> -<br/> - -<em>Encountering 404 errors is not new. Often, developers provide custom 404 pages to make the experience a little less…</em>www.alistapart.com</a><a href="https://www.alistapart.com/articles/amoreuseful404/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://realfavicongenerator.net/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://realfavicongenerator.net/"><strong>Favicon Generator for perfect icons on all browsers</strong> -<br/> - -<em>The ultimate favicon generator. Design your icons platform per platform and make them look great everywhere. Including…</em>realfavicongenerator.net</a><a href="https://realfavicongenerator.net/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://github.com/audreyr/favicon-cheat-sheet" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://github.com/audreyr/favicon-cheat-sheet"><strong>audreyfeldroy/favicon-cheat-sheet</strong> -<br/> - -<em>A painfully obsessive cheat sheet to favicon sizes/types. Compiled from: For the main favicon itself, it's best for…</em>github.com</a><a href="https://github.com/audreyr/favicon-cheat-sheet" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://moz.com/learn/seo/url" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://moz.com/learn/seo/url"><strong>URL Structure [2021 SEO]</strong> -<br/> - -<em>Keeping URLs as simple, relevant, compelling, and accurate as possible is key to getting both your users and search…</em>moz.com</a><a href="https://moz.com/learn/seo/url" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://docs.microsoft.com/en-us/iis/extensions/url-rewrite-module/url-rewrite-module-configuration-reference" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://docs.microsoft.com/en-us/iis/extensions/url-rewrite-module/url-rewrite-module-configuration-reference"><strong>URL Rewrite Module Configuration Reference</strong> -<br/> - -<em>by Ruslan Yakushev This article provides an overview of the URL Rewrite Module and explains the configuration concepts…</em>docs.microsoft.com</a><a href="https://docs.microsoft.com/en-us/iis/extensions/url-rewrite-module/url-rewrite-module-configuration-reference" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://httpd.apache.org/docs/current/mod/mod_rewrite.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://httpd.apache.org/docs/current/mod/mod_rewrite.html"><strong>mod_rewrite - Apache HTTP Server Version 2.4</strong> -<br/> - -<em>The mod_rewrite module uses a rule-based rewriting engine, based on a PCRE regular-expression parser, to rewrite…</em>httpd.apache.org</a><a href="https://httpd.apache.org/docs/current/mod/mod_rewrite.html" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.nginx.com/blog/creating-nginx-rewrite-rules/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.nginx.com/blog/creating-nginx-rewrite-rules/"><strong>How to Create NGINX Rewrite Rules | NGINX</strong> -<br/> - -<em>In this blog post, we discuss how to create NGINX rewrite rules (the same methods work for both NGINX Plus and the open…</em>www.nginx.com</a><a href="https://www.nginx.com/blog/creating-nginx-rewrite-rules/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.smashingmagazine.com/2011/11/how-to-set-up-a-print-style-sheet/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.smashingmagazine.com/2011/11/how-to-set-up-a-print-style-sheet/"><strong>How To Set Up A Print Style Sheet - Smashing Magazine</strong> -<br/> - -<em>In a time when everyone seems to have a tablet, which makes it possible to consume everything digitally, and the only…</em>www.smashingmagazine.com</a><a href="https://www.smashingmagazine.com/2011/11/how-to-set-up-a-print-style-sheet/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.google.com/cse/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.google.com/cse/"><strong>Programmable Search Engine by Google</strong> -<br/> - -<em>Decide if you want users to search only your website, or include other sites on the web. Match the design to your site…</em>www.google.com</a><a href="https://www.google.com/cse/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://github.com/dewitt/opensearch" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://github.com/dewitt/opensearch"><strong>dewitt/opensearch</strong> -<br/> - -<em>OpenSearch is a collection of simple formats for the sharing of search results. The most recent version of the…</em>github.com</a><a href="https://github.com/dewitt/opensearch" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html"><strong>Configuring Web Applications</strong> -<br/> - -<em>A web application is designed to look and behave in a way similar to a native application-for example, it is scaled to…</em>developer.apple.com</a><a href="https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/dev-guides/hh781490%28v=vs.85%29" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/dev-guides/hh781490(v=vs.85)"><strong>Windows 8 integration (Windows)</strong> -<br/> - -<em>This section details the ways in which web developers can take advantage of the tight integration of Windows 8 and…</em>docs.microsoft.com</a><a href="https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/dev-guides/hh781490%28v=vs.85%29" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://schema.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://schema.org/"><strong>Schema.org - Schema.org</strong> -<br/> - -<em>Schema.org is a collaborative, community activity with a mission to create, maintain, and promote schemas for…</em>schema.org</a><a href="https://schema.org/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://seoscout.com/tools/schema-generator" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://seoscout.com/tools/schema-generator"><strong>Schema Markup Generator & Structured Data Testing Tool (inc JSON-LD)</strong> -<br/> - -<em>By adding the JSON-LD this tool generates to your pages you help Google better understand their purpose.Make it easy…</em>seoscout.com</a><a href="https://seoscout.com/tools/schema-generator" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://search.google.com/structured-data/testing-tool/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://search.google.com/structured-data/testing-tool/"><strong>Structured Data Testing Tool</strong> -<br/> - -<em>Edit description</em>search.google.com</a><a href="https://search.google.com/structured-data/testing-tool/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://developers.facebook.com/tools/debug/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://developers.facebook.com/tools/debug/"><strong>Sharing Debugger - Facebook for Developers</strong> -<br/> - -<em>Sharing Debugger lets you preview how your content will look when it's shared to Facebook and debug any issues with…</em>developers.facebook.com</a><a href="https://developers.facebook.com/tools/debug/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://cards-dev.twitter.com/validator" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://cards-dev.twitter.com/validator"><strong>JavaScript is not available.</strong> -<br/> - -<em>Edit description</em>cards-dev.twitter.com</a><a href="https://cards-dev.twitter.com/validator" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://search.google.com/test/rich-results" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://search.google.com/test/rich-results"><strong>Rich Results Test - Google Search Console</strong> -<br/> - -<em>Does your page support rich results? What are rich results? Rich results are experiences on Google surfaces, such as…</em>search.google.com</a><a href="https://search.google.com/test/rich-results" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://schema.org/docs/gs.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://schema.org/docs/gs.html"><strong>Getting Started - schema.org</strong> -<br/> - -<em>Most webmasters are familiar with HTML tags on their pages. Usually, HTML tags tell the browser how to display the…</em>schema.org</a><a href="https://schema.org/docs/gs.html" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="http://tools.seobook.com/robots-txt/" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://tools.seobook.com/robots-txt/"><strong>Robots.txt Tutorial</strong> -<br/> - -<em>Use our Robots.txt generator to create a robots.txt file. Use our Robots.txt analyzer to analyze your robots.txt file…</em>tools.seobook.com</a><a href="http://tools.seobook.com/robots-txt/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="http://www.robotsgenerator.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://www.robotsgenerator.com/"><strong>Robots Generator | Generate robots.txt Files Instantly - RobotsGenerator.com</strong> -<br/> - -<em>Select folders and/or files If there are areas of your page you do not wish made public, simply indicate the…</em>www.robotsgenerator.com</a><a href="http://www.robotsgenerator.com/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://www.xml-sitemaps.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.xml-sitemaps.com/"><strong>Create your Google Sitemap Online - XML Sitemaps Generator</strong> -<br/> - -<em>Free Online Google Sitemap Generator. XML-sitemaps.com provides free online sitemap generator service, creating an XML…</em>www.xml-sitemaps.com</a><a href="https://www.xml-sitemaps.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://validator.w3.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://validator.w3.org/"><strong>Markup Validation Service</strong> -<br/> - -<em>W3C's easy-to-use markup validation service, based on SGML and XML parsers.</em>validator.w3.org</a><a href="https://validator.w3.org/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://html5.validator.nu/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://html5.validator.nu/"><strong>Validator.nu (X)HTML5 Validator</strong> -<br/> - -<em>Edit description</em>html5.validator.nu</a><a href="https://html5.validator.nu/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://jigsaw.w3.org/css-validator/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://jigsaw.w3.org/css-validator/"><strong>CSS Validation Service</strong> -<br/> - -<em>Check Cascading Style Sheets (CSS) and (X)HTML documents with style sheets</em>jigsaw.w3.org</a><a href="https://jigsaw.w3.org/css-validator/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="http://csslint.net/" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://csslint.net/"><strong>CSS Lint</strong> -<br/> - -<em>CSS lint found 0 errors and 0 warnings. How can you fix it? See the details below.</em>csslint.net</a><a href="http://csslint.net/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://jslint.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://jslint.com/"><strong>JSLint: The JavaScript Code Quality Tool</strong> -<br/> - -<em>JSLint, The JavaScript Code Quality Tool. This file allows JSLint to be run from a web browser. It can accept a source…</em>jslint.com</a><a href="https://jslint.com/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://jshint.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://jshint.com/"><strong>JSHint, a JavaScript Code Quality Tool</strong> -<br/> - -<em>Report Cyclomatic complexity Unused variables Undefined variables Warn About == null About debugging code About unsafe…</em>jshint.com</a><a href="https://jshint.com/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://www.w3.org/WAI/standards-guidelines/wcag/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.w3.org/WAI/standards-guidelines/wcag/"><strong>Web Content Accessibility Guidelines (WCAG) Overview</strong> -<br/> - -<em>Introducing the Web Content Accessibility Guidelines (WCAG), including WCAG 2.0 and WCAG 2.1. Quick links to resources…</em>www.w3.org</a><a href="https://www.w3.org/WAI/standards-guidelines/wcag/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility"><strong>Handling common accessibility problems - Learn web development | MDN</strong> -<br/> - -<em>Next we turn our attention to accessibility, providing information on common problems, how to do simple testing, and…</em>developer.mozilla.org</a><a href="https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://wave.webaim.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://wave.webaim.org/"><strong>WAVE Web Accessibility Evaluation Tool</strong> -<br/> - -<em>WAVE is a suite of evaluation tools that helps authors make their web content more accessible to individuals with…</em>wave.webaim.org</a><a href="https://wave.webaim.org/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.nvaccess.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.nvaccess.org/"><strong>NV Access</strong> -<br/> - -<em>Access to technology no matter your language, location or financial situation Quality over growth, access over profit…</em>www.nvaccess.org</a><a href="https://www.nvaccess.org/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://webaim.org/resources/contrastchecker/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://webaim.org/resources/contrastchecker/"><strong>Contrast Checker</strong> -<br/> - -<em>The five boxing wizards jump quickly. The five boxing wizards jump quickly. Enter a foreground and background color in…</em>webaim.org</a><a href="https://webaim.org/resources/contrastchecker/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://accessibility.oit.ncsu.edu/using-aria-landmarks-a-demonstration/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://accessibility.oit.ncsu.edu/using-aria-landmarks-a-demonstration/"><strong>Using ARIA Landmarks - A Demonstration</strong> -<br/> - -<em>ARIA landmarks are attributes you add to elements to create semantically defined sections of a page that allow users of…</em>accessibility.oit.ncsu.edu</a><a href="https://accessibility.oit.ncsu.edu/using-aria-landmarks-a-demonstration/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://alistapart.com/article/the-accessibility-of-wai-aria/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://alistapart.com/article/the-accessibility-of-wai-aria/"><strong>The Accessibility of WAI-ARIA</strong> -<br/> - -<em>Web developers interested in accessibility issues often discuss WAI-ARIA, an upcoming W3C candidate recommendation…</em>alistapart.com</a><a href="https://alistapart.com/article/the-accessibility-of-wai-aria/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="http://www.punkchip.com/2010/11/aria-basic-findings/" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://www.punkchip.com/2010/11/aria-basic-findings/"><strong>WAI-ARIA states and properties: Practical examples</strong> -<br/> - -<em>I've been trying to include some WAI-ARIA into the project I'm currently working on. Luckily for me I'm using jQuery's…</em>www.punkchip.com</a><a href="http://www.punkchip.com/2010/11/aria-basic-findings/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://observatory.mozilla.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://observatory.mozilla.org/"><strong>Mozilla Observatory</strong> -<br/> - -<em>The Mozilla Observatory is a project designed to help developers, system administrators, and security professionals…</em>observatory.mozilla.org</a><a href="https://observatory.mozilla.org/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html"><strong>Cross Site Scripting Prevention - OWASP Cheat Sheet Series</strong> -<br/> - -<em>This article provides a simple positive model for preventing XSS using output encoding properly. While there are a huge…</em>cheatsheetseries.owasp.org</a><a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html"><strong>DOM based XSS Prevention - OWASP Cheat Sheet Series</strong> -<br/> - -<em>When looking at XSS (Cross-Site Scripting), there are three generally recognized forms of XSS: The XSS Prevention…</em>cheatsheetseries.owasp.org</a><a href="https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://blog.codinghorror.com/cross-site-request-forgeries-and-you/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://blog.codinghorror.com/cross-site-request-forgeries-and-you/"><strong>Cross-Site Request Forgeries and You</strong> -<br/> - -<em>As the web becomes more and more pervasive, so do web-based security vulnerabilities. I talked a little bit about the…</em>blog.codinghorror.com</a><a href="https://blog.codinghorror.com/cross-site-request-forgeries-and-you/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html"><strong>Cross-Site Request Forgery Prevention - OWASP Cheat Sheet Series</strong> -<br/> - -<em>Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious web site, email, blog, instant…</em>cheatsheetseries.owasp.org</a><a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://letsencrypt.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://letsencrypt.org/"><strong>Let's Encrypt</strong> -<br/> - -<em>Let's Encrypt is a free, automated, and open certificate authority brought to you by the nonprofit Internet Security…</em>letsencrypt.org</a><a href="https://letsencrypt.org/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://support.microsoft.com/en-gb/help/299875/how-to-implement-ssl-in-iis" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://support.microsoft.com/en-gb/help/299875/how-to-implement-ssl-in-iis"><strong>How to Set Up SSL on IIS 7</strong> -<br/> - -<em>by Saad Ladki The steps for configuring Secure Sockets Layer (SSL) for a site are the same in IIS 7 and above and IIS…</em>support.microsoft.com</a><a href="https://support.microsoft.com/en-gb/help/299875/how-to-implement-ssl-in-iis" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.digicert.com/kb/csr-ssl-installation/apache-openssl.htm#ssl_certificate_install" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.digicert.com/kb/csr-ssl-installation/apache-openssl.htm#ssl_certificate_install"><strong>Apache: CSR & SSL Installation (OpenSSL)</strong> -<br/> - -<em>Use the instructions on this page to use OpenSSL to create your certificate signing request (CSR) and then to install…</em>www.digicert.com</a><a href="https://www.digicert.com/kb/csr-ssl-installation/apache-openssl.htm#ssl_certificate_install" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://nginx.org/en/docs/http/configuring_https_servers.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://nginx.org/en/docs/http/configuring_https_servers.html"><strong>Configuring HTTPS servers</strong> -<br/> - -<em>To configure an HTTPS server, the ssl parameter must be enabled on listening sockets in the server block, and the…</em>nginx.org</a><a href="https://nginx.org/en/docs/http/configuring_https_servers.html" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://www.ssllabs.com/ssltest/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.ssllabs.com/ssltest/"><strong>SSL Server Test</strong> -<br/> - -<em>This free online service performs a deep analysis of the configuration of any SSL web server on the public Internet…</em>www.ssllabs.com</a><a href="https://www.ssllabs.com/ssltest/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security"><strong>Strict-Transport-Security - HTTP | MDN</strong> -<br/> - -<em>The HTTP Strict-Transport-Security response header (often abbreviated as HSTS) lets a web site tell browsers that it…</em>developer.mozilla.org</a><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Strict_Transport_Security_Cheat_Sheet.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Strict_Transport_Security_Cheat_Sheet.html"><strong>HTTP Strict Transport Security - OWASP Cheat Sheet Series</strong> -<br/> - -<em>HTTP Strict Transport Security (also named HSTS) is an opt-in security enhancement that is specified by a web…</em>cheatsheetseries.owasp.org</a><a href="https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Strict_Transport_Security_Cheat_Sheet.html" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://www.html5rocks.com/en/tutorials/security/content-security-policy/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.html5rocks.com/en/tutorials/security/content-security-policy/"><strong>Content Security Policy | Web Fundamentals | Google Developers</strong> -<br/> - -<em>The web's security model is rooted in the same-origin policy . Code from https://mybank.com should only have access to…</em>www.html5rocks.com</a><a href="https://www.html5rocks.com/en/tutorials/security/content-security-policy/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP"><strong>Content Security Policy (CSP) - HTTP | MDN</strong> -<br/> - -<em>Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks…</em>developer.mozilla.org</a><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://csp-evaluator.withgoogle.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://csp-evaluator.withgoogle.com/"><strong>CSP Evaluator</strong> -<br/> - -<em>CSP Evaluator allows developers and security experts to check if a Content Security Policy (CSP) serves as a strong…</em>csp-evaluator.withgoogle.com</a><a href="https://csp-evaluator.withgoogle.com/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://developers.google.com/search/docs/guides/intro-structured-data" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://developers.google.com/search/docs/guides/intro-structured-data"><strong>Understand How Structured Data Works | Google Search Central</strong> -<br/> - -<em>Google Search works hard to understand the content of a page. You can help us by providing explicit clues about the…</em>developers.google.com</a><a href="https://developers.google.com/search/docs/guides/intro-structured-data" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://ogp.me/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://ogp.me/"><strong>Open Graph protocol</strong> -<br/> - -<em>The Open Graph protocol enables any web page to become a rich object in a social graph. For instance, this is used on…</em>ogp.me</a><a href="https://ogp.me/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://developer.twitter.com/en/docs/tweets/optimize-with-cards/overview/abouts-cards" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://developer.twitter.com/en/docs/tweets/optimize-with-cards/overview/abouts-cards"><strong>About Twitter Cards</strong> -<br/> - -<em>With Twitter Cards, you can attach rich photos, videos and media experiences to Tweets, helping to drive traffic to…</em>developer.twitter.com</a><a href="https://developer.twitter.com/en/docs/tweets/optimize-with-cards/overview/abouts-cards" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://developers.facebook.com/docs/sharing/webmasters#markup" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://developers.facebook.com/docs/sharing/webmasters#markup"><strong>Webmasters - Sharing - Documentation - Facebook for Developers</strong> -<br/> - -<em>Most content is shared to Facebook as a URL, so it's important that you mark up your website with Open Graph tags to…</em>developers.facebook.com</a><a href="https://developers.facebook.com/docs/sharing/webmasters#markup" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="http://humanstxt.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://humanstxt.org/"><strong>Humans TXT: We Are People, Not Machines.</strong> -<br/> - -<em>It's an initiative for knowing the people behind a website. It's a TXT file that contains information about the…</em>humanstxt.org</a><a href="http://humanstxt.org/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -### Discover More: - -<a href="https://bgoonz-blog.netlify.app/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://bgoonz-blog.netlify.app/"><strong>Stackbit Web-Dev-HubTheme</strong> -<br/> - -<em>Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…</em>bgoonz-blog.netlify.app</a><a href="https://bgoonz-blog.netlify.app/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [June 24, 2021](https://medium.com/p/9a52e11c8ee1). - -<a href="https://medium.com/@bryanguner/quick-web-developers-website-checklist-a-list-of-tools-for-improvement-9a52e11c8ee1" class="p-canonical">Canonical link</a> - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Quick-Web-Developers-Website-Checklist---A-List-Of-Tools-For.md b/notes/articles/medium/markdown/Quick-Web-Developers-Website-Checklist---A-List-Of-Tools-For.md deleted file mode 100644 index 3f6e0d1111..0000000000 --- a/notes/articles/medium/markdown/Quick-Web-Developers-Website-Checklist---A-List-Of-Tools-For.md +++ /dev/null @@ -1,882 +0,0 @@ -# Quick Web Developers Website Checklist & A List Of Tools For Improvement - -A set of questions you should use before handing off your application to the client. - ---- - -### Quick Web Developers Website Checklist & A List Of Tools For Improvement - -#### A set of questions you should use before handing off your application to the client. - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*QD7rah374uFotVYN.jpg" class="graf-image" /></figure>First off… download this developer checklist extension for chrome that literally evaluates the checkpoints on any webpage you activate it on.. it also provides advice and html validation so that you can improve your site and it's SEO rankings! - -<a href="https://chrome.google.com/webstore/detail/web-developer-checklist/iahamcpedabephpcgkeikbclmaljebjp?hl=en-US" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://chrome.google.com/webstore/detail/web-developer-checklist/iahamcpedabephpcgkeikbclmaljebjp?hl=en-US"><strong>Web Developer Checklist</strong> -<br/> - -<em>Analyses any web page for violations of best practices</em>chrome.google.com</a><a href="https://chrome.google.com/webstore/detail/web-developer-checklist/iahamcpedabephpcgkeikbclmaljebjp?hl=en-US" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -#### Here it is in action : - -<figure><img src="https://cdn-images-1.medium.com/max/800/1*Qh8BZUzF7nRISPrwDTz05Q.png" class="graf-image" /></figure>### Remainder of tool list is below this checklist: - ---- - -### Usefulness & Relevance: - -> _Does the content meet user needs, goals, and interests?_ - -> _Does the content meet business goals?_ - -> _For how long will the content be useful? When should it expire? Has its usefulness already expired?_ - -> _Is the content timely and relevant?_ - ---- - -### Clarity & Accuracy: - -> **Is the content understandable to customers?** - -> **Is the content organized logically & coherently?** - -> **Is the content correct?** - -> **Does the content contain factual errors, typos, or grammatical errors?** - -> **Do images, video, and audio meet technical standards, so they are clear?** - ---- - -### Influence & Engagement: - -> Does the content use the most appropriate techniques to influence or engage customers? - -> Does the content execute those techniques effectively? - -> Does the content use too many or too few techniques for the context? - ---- - -### Completeness: - -> Does the content include all of the information customers need or might want about a topic? - -> Does the content include too much or too little information about a topic for the context? - -### Voice & Style: - -> Does the content consistently reflect the editorial or brand voice? - -> Does its tone adjust appropriately to the context — for example, sales versus customer service? - -> Does the content convey the appropriate editorial and brand qualities? - -> Does the content seem to have a style? If so, does the content adhere to it consistently? - -> Does the content read, look, or sound as though it's professionally crafted? - ---- - -### Usability & Findability: - -> Is the content easy to scan or read? - -> Is the content in a usable format, including headings, bulleted lists, tables, white space, or similar techniques, as appropriate to the content? - -> Does the content have the appropriate metadata? - -> Does the content follow search engine optimization (SEO) guidelines — such as using keywords — without sacrificing quality in other areas? - -> Can customers find the content when searching using relevant keywords? - ---- - -### SEO Advice From Google: - -### Help Google find your pages - -- <span id="6fe9">Ensure that all pages on the site can be reached by a link from another findable page. The referring link should include either text or, for images, an alt attribute, that is relevant to the target page. Crawlable links are `<a>` <a href="https://developers.google.com/search/docs/advanced/guidelines/links-crawlable" class="markup--anchor markup--li-anchor">tags with an href attribute</a>.</span> -- <span id="f878">Provide a <a href="http://sitemaps.org/" class="markup--anchor markup--li-anchor">sitemap file</a> with links that point to the important pages on your site. Also provide a page with a human-readable list of links to these pages (sometimes called a site index or site map page).</span> -- <span id="2ee0">Limit the number of links on a page to a reasonable number (a few thousand at most).</span> -- <span id="9235">Make sure that your web server correctly supports the `If-Modified-Since` HTTP header. This feature directs your web server to tell Google if your content has changed since we last crawled your site. Supporting this feature saves you bandwidth and overhead.</span> -- <span id="a839">Use the robots.txt file on your web server to manage your crawling budget by preventing crawling of infinite spaces such as search result pages. Keep your robots.txt file up to date. <a href="https://developers.google.com/search/docs/advanced/robots/robots-faq" class="markup--anchor markup--li-anchor">Learn how to manage crawling with the robots.txt file</a>. Test the coverage and syntax of your robots.txt file using the <a href="https://www.google.com/webmasters/tools/robots-testing-tool" class="markup--anchor markup--li-anchor">robots.txt Tester</a>.</span> - -**Ways to help Google find your site:** - -- <span id="417a"><a href="https://developers.google.com/search/docs/advanced/crawling/ask-google-to-recrawl" class="markup--anchor markup--li-anchor">Ask Google to crawl your pages</a>.</span> -- <span id="2ba7">Make sure that any sites that should know about your pages are aware your site is online.</span> - -### Help Google understand your pages - -- <span id="6069">Create a useful, information-rich site, and write pages that clearly and accurately describe your content.</span> -- <span id="16eb">Think about the words users would type to find your pages, and make sure that your site actually includes those words within it.</span> -- <span id="5f2b">Ensure that your `<title>` elements and `alt` attributes are descriptive, specific, and accurate.</span> -- <span id="86c8">Design your site to have a clear conceptual page hierarchy.</span> -- <span id="aed5">Follow our recommended best practices for <a href="https://developers.google.com/search/docs/advanced/guidelines/google-images" class="markup--anchor markup--li-anchor">images</a>, <a href="https://developers.google.com/search/docs/advanced/guidelines/video" class="markup--anchor markup--li-anchor">video</a>, and <a href="https://developers.google.com/search/docs/guides/intro-structured-data" class="markup--anchor markup--li-anchor">structured data</a>.</span> -- <span id="67f4">When using a content management system (for example, Wix or WordPress), make sure that it creates pages and links that search engines can crawl.</span> -- <span id="5fcd">To help Google fully understand your site's contents, allow all site assets that would significantly affect page rendering to be crawled: for example, CSS and JavaScript files that affect the understanding of the pages. The Google indexing system renders a web page as the user would see it, including images, CSS, and JavaScript files. To see which page assets that Googlebot cannot crawl use the <a href="https://support.google.com/webmasters/answer/9012289" class="markup--anchor markup--li-anchor">URL Inspection tool</a>; to debug directives in your robots.txt file, use the <a href="https://support.google.com/webmasters/answer/6062598" class="markup--anchor markup--li-anchor">robots.txt Tester</a> tool.</span> -- <span id="b8ef">Allow search bots to crawl your site without session IDs or URL parameters that track their path through the site. These techniques are useful for tracking individual user behavior, but the access pattern of bots is entirely different. Using these techniques may result in incomplete indexing of your site, as bots may not be able to eliminate URLs that look different but actually point to the same page.</span> -- <span id="e5c6">Make your site's important content visible by default. Google is able to crawl HTML content hidden inside navigational elements such as tabs or expanding sections, however we consider this content less accessible to users, and believe that you should make your most important information visible in the default page view.</span> -- <span id="58bf">Make a reasonable effort to ensure that advertisement links on your pages do not affect search engine rankings. For example, use <a href="https://developers.google.com/search/docs/advanced/robots/intro" class="markup--anchor markup--li-anchor">robots.txt</a>, `rel="nofollow"`, or `rel="sponsored"` to prevent advertisement links from being followed by a crawler.</span> - -### Help visitors use your pages - -- <span id="76dc">Try to use text instead of images to display important names, content, or links. If you must use images for textual content, use the `alt` attribute to include a few words of descriptive text.</span> -- <span id="d45e">Ensure that all links go to live web pages. Use <a href="https://validator.w3.org/" class="markup--anchor markup--li-anchor">valid HTML</a>.</span> -- <span id="8b66">Optimize your page loading times. Fast sites make users happy and improve the overall quality of the web (especially for those users with slow Internet connections). Google recommends that you use tools like <a href="https://developers.google.com/speed/pagespeed/insights/" class="markup--anchor markup--li-anchor">PageSpeed Insights</a> and <a href="https://www.webpagetest.org/" class="markup--anchor markup--li-anchor">Webpagetest.org</a> to test the performance of your page.</span> -- <span id="5f39">Design your site for all device types and sizes, including desktops, tablets, and smartphones. Use the <a href="https://search.google.com/test/mobile-friendly" class="markup--anchor markup--li-anchor">Mobile-Friendly Test</a> to test how well your pages work on mobile devices, and get feedback on what needs to be fixed.</span> -- <span id="5f9b">Ensure that your site <a href="https://developers.google.com/search/docs/advanced/guidelines/browser-compatibility" class="markup--anchor markup--li-anchor">appears correctly in different browsers</a>.</span> -- <span id="717b">If possible, <a href="https://developers.google.com/search/docs/advanced/security/https" class="markup--anchor markup--li-anchor">secure your site's connections</a> with HTTPS. Encrypting interactions between the user and your website is a good practice for communication on the web.</span> -- <span id="4156">Ensure that your pages are useful for readers with visual impairments, for example, by testing usability with a screen-reader.</span> - -### Basic principles - -- <span id="0251">Make pages primarily for users, not for search engines.</span> -- <span id="f565">Don't deceive your users.</span> -- <span id="5f8a">Avoid tricks intended to improve search engine rankings. A good rule of thumb is whether you'd feel comfortable explaining what you've done to a website that competes with you, or to a Google employee. Another useful test is to ask, "Does this help my users? Would I do this if search engines didn't exist?"</span> -- <span id="9acc">Think about what makes your website unique, valuable, or engaging. Make your website stand out from others in your field.</span> - -### Specific guidelines - -**Avoid** the following techniques: - -- <span id="2686"><a href="https://developers.google.com/search/docs/advanced/guidelines/auto-gen-content" class="markup--anchor markup--li-anchor">Automatically generated content</a></span> -- <span id="a921">Participating in <a href="https://developers.google.com/search/docs/advanced/guidelines/link-schemes" class="markup--anchor markup--li-anchor">link schemes</a></span> -- <span id="bbd9">Creating pages with <a href="https://support.google.com/webmasters/answer/66361" class="markup--anchor markup--li-anchor">little or no original content</a></span> -- <span id="7ddf"><a href="https://developers.google.com/search/docs/advanced/guidelines/cloaking" class="markup--anchor markup--li-anchor">Cloaking</a></span> -- <span id="e9b8"><a href="https://developers.google.com/search/docs/advanced/guidelines/sneaky-redirects" class="markup--anchor markup--li-anchor">Sneaky redirects</a></span> -- <span id="47d2"><a href="https://developers.google.com/search/docs/advanced/guidelines/hidden-text-links" class="markup--anchor markup--li-anchor">Hidden text or links</a></span> -- <span id="7ae2"><a href="https://developers.google.com/search/docs/advanced/guidelines/doorway-pages" class="markup--anchor markup--li-anchor">Doorway pages</a></span> -- <span id="98d8"><a href="https://developers.google.com/search/docs/advanced/guidelines/scraped-content" class="markup--anchor markup--li-anchor">Scraped content</a></span> -- <span id="156f">Participating in <a href="https://developers.google.com/search/docs/advanced/guidelines/affiliate-programs" class="markup--anchor markup--li-anchor">affiliate programs without adding sufficient value</a></span> -- <span id="42e4">Loading pages with <a href="https://developers.google.com/search/docs/advanced/guidelines/irrelevant-keywords" class="markup--anchor markup--li-anchor">irrelevant keywords</a></span> -- <span id="f583">Creating pages with <a href="https://developers.google.com/search/docs/advanced/guidelines/malicious-behavior" class="markup--anchor markup--li-anchor">malicious behavior</a>, such as phishing or installing viruses, trojans, or other badware</span> -- <span id="777a">Abusing <a href="https://developers.google.com/search/docs/guides/sd-policies" class="markup--anchor markup--li-anchor">structured data</a> markup</span> -- <span id="6c9f">Sending <a href="https://developers.google.com/search/docs/advanced/guidelines/automated-queries" class="markup--anchor markup--li-anchor">automated queries</a> to Google</span> - -**Follow** good practices: - -- <span id="68a7">Monitoring your site for <a href="https://developers.google.com/search/docs/advanced/security/what-is-hacked" class="markup--anchor markup--li-anchor">hacking</a> and removing hacked content as soon as it appears</span> -- <span id="8141">Preventing and removing <a href="https://developers.google.com/search/docs/advanced/guidelines/user-gen-spam" class="markup--anchor markup--li-anchor">user-generated spam</a> on your site</span> - -If your site violates one or more of these guidelines, then Google may take <a href="https://support.google.com/webmasters/answer/9044175" class="markup--anchor markup--p-anchor">manual action</a> against it. Once you have remedied the problem, you can <a href="https://support.google.com/webmasters/answer/35843" class="markup--anchor markup--p-anchor">submit your site for reconsideration</a>. - ---- - -### Website Launch Checklist: - -### Website design checklist - -It's all too easy to miss (or break) something during the many back-and-forths, client feedback sessions, and other design iterations you go through. That's why we created the design checklist below will help you go back and check for any design mistakes. - -To start, be sure to check your: - -- <span id="1b13">Spacing: Is spacing consistent across the site (i.e., did you stick to that 8px grid, or let a rogue 18px in there)? Do all elements have enough breathing room?</span> -- <span id="589b">Colors: Have you stuck to a consistent, harmonious color palette? Are all instances of the brand blue _actually_ the brand blue?</span> -- <span id="dcfc">Shadows: If you used drop shadows, is the light source consistent for each and every one? Did you use the same blur, opacity, and spread values?</span> -- <span id="021b">Typography: Is your font stack logical and consistent (i.e., is there a reason that element is set in a sans)? Are your heading sizes consistent? Have you used proper (not faux) italics and bolding? Do all text links look right? Is all text both legible and readable?</span> -- <span id="fbb2">Imagery: Do any images look blurry, pixelated, or otherwise funky? Are any images broken or crazily heavy in terms of file size? Do all _non-decorative_ images have alt tags?</span> -- <span id="4760">Logo: It's (usually) just another image, but it's so important it warrants its own step. Is it the latest version? Is it crisp (not blurry or pixelated)?</span> - -Once you've made these initial visual checks, you'll want to ensure that your site's appearance is consistent and functional on any screen. - -### Cross-browser appearance - -Different browsers may render your website in different ways, so it's important to test your site in different browsers. Take a look at <a href="http://www.w3schools.com/browsers/browsers_stats.asp" class="markup--anchor markup--p-anchor">W3's browser stats</a> to see where you should focus your testing. (Though if you're working on a redesign, browser-usage stats will be more useful.) - -During this process (and the next, in multi-device testing) you'll want to make sure your layouts, typography, navigation, and other design elements are displaying properly. - -The elements that tend to vary most across browsers, and therefore are most important to check, are: - -- <span id="f7ff">Fonts</span> -- <span id="32b8">Colors/gradients</span> -- <span id="5871">Images</span> -- <span id="be77">Logo</span> - -### Cross-device appearance - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*zXLmWvXkMI5Wv2LF.jpeg" class="graf-image" /></figure>Make sure your site looks and performs beautifully on any device. - -There have never been more web-capable devices around, and with that comes a staggering array of screen sizes. Done right, your site _should_ perform well on any screen size, but be sure to double check. (You are a perfectionist after all, right?) - -This is also where mobile navigation is crucial. Be sure to test out the user's ability to navigate around the website on a touchscreen device, and make sure nothing gets lost in device transition. - -In Webflow, we make it easy for you to test the most popular devices and preview your website on almost any size, streamlining the process of cross-device testing all in one place. Of course, nothing replaces real-world testing on a variety of devices as small details may differ on the real device. - -### Image optimization - -Images and graphics are an important element of many websites, so you'll want to make sure they display properly, especially on all those ultra-high-definition devices (like Apple's Retina screens) out there. - -The rule of thumb is to upload your image at twice the size it'll display on your site. In some cases, you can upload two images: an actual-size version for lower-res devices, and another that's twice the size for high-res devices. - -Why? Because the heavier the image, the slower your page will load, and the worse your user experience will be (which also negatively affects SEO, which we'll cover later on). - -In Webflow, we automatically scale, compress, and optimize images for every device. Learn more about our <a href="https://webflow.com/feature/responsive-images" class="markup--anchor markup--p-anchor">responsive images feature or check out our more detailed</a> article on <a href="https://webflow.com/blog/how-to-boost-your-sites-performance" class="markup--anchor markup--p-anchor">image optimization</a>. - -### Website functionality testing - -Design and functionality go hand in hand, but I like to isolate the two to make sure the website both _looks_ the way it was designed to and that it _performs_ as intended. - -### Integration testing - -This one is super important, and can range from a quick task to a giant one, depending on how many integrations you have. Typically, I'll create a list of integrations _as I add them_ so I don't forget later on. - -Some common integrations to test might be: - -- <span id="54e1">Web forms (check that the forms work _and_ that submitted information goes to the right place)</span> -- <span id="5ad2">Autoresponders</span> -- <span id="1079">Marketing emails (MailChimp, Constant Contact, HubSpot, drip campaigns, etc.)</span> -- <span id="10e0">RSS feeds</span> -- <span id="fe8e">Ecommerce</span> -- <span id="5f3d">CRM</span> -- <span id="dc4a">CMS</span> - -### Link testing - -This one can be a doozy, simply because most sites have dozens (if not hundreds) of links. More often than not, there's a link or two that goes nowhere, and it's important to find them before your end-users do. - -Some of the most important links to check are: - -- <span id="fd34">Top navigation links</span> -- <span id="88d4">Footer links</span> -- <span id="d42d">Social media links (Facebook, Twitter, etc.)</span> -- <span id="cde4">Logo (typically links to the home page)</span> - -Rather than doing all this manually, I'd suggest trying a link crawler like the <a href="https://validator.w3.org/checklink" class="markup--anchor markup--p-anchor">W3C Link Checker</a>, the Chrome plugin <a href="https://chrome.google.com/webstore/detail/check-my-links/ojkcdipcgfaekbeaelaapakgnjflfglf?hl=en-GB" class="markup--anchor markup--p-anchor">Check My Links</a>, or <a href="http://www.screamingfrog.co.uk/seo-spider/" class="markup--anchor markup--p-anchor">Screaming Frog</a> (which is excellent for SEO audits, too). - -### Content editing - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*HxnVQM9RoqyuTlLP.jpeg" class="graf-image" /></figure>Give the king its due. - -Content is king, and the testing process should be fit for one. Typically this involves making sure that all content has been updated and approved. I can't tell you how many websites I've found that _still_ have a l*orem ipsum* paragraph somewhere. - -Now, if you practice <a href="https://webflow.com/blog/content-first-design" class="markup--anchor markup--p-anchor">content-first design</a>, you should have final content already in place, so you can focus on more fine-toothed-comb review, like proofing for spelling and grammatical errors. - -It's also important to note here that it's okay for content to be changed later on. Clients, team members, or you can always adjust text through a CMS. The main goal here is to ensure that your website content isn't complete gibberish. - -### Search engine optimization (SEO) - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*Ukayn_ZyXfN-Wg-M.jpeg" class="graf-image" /></figure>Analyzing and optimizing your website *after* publishing is a never-ending process. And you need to consider semantic site structure from the get-go. But that doesn't mean you won't benefit from an SEO review before you hit publish. - -There are multiple things that can be done to optimize your website for search engines. - -### 1. Use proper semantic structure - -Web crawlers (like Google's bots) read through your website to get an understanding of your content, so that search engines know to display your website when people search for it. To help them crawl your site, you need to use language they'll understand. - -Historically, this has meant using the following semantic tags: - -- <span id="93f0">h1-h6 (heading tags)</span> -- <span id="f999">p (paragraph tags)</span> -- <span id="c0ab">ul/ol (unordered and ordered Lists)</span> - -You can also go above and beyond with some new <a href="https://webflow.com/blog/html5-semantic-elements-and-webflow-the-essential-guide" class="markup--anchor markup--p-anchor">HTML5 semantic tags</a>: - -- <span id="4d08"><article></span> -- <span id="8074"><aside></span> -- <span id="9b75"><details></span> -- <span id="0652"><figcaption></span> -- <span id="721c"><figure></span> -- <span id="0cc5"><footer></span> -- <span id="2e07"><header></span> -- <span id="0e37"><main></span> -- <span id="6be6"><mark></span> -- <span id="1656"><nav></span> -- <span id="e390"><section></span> -- <span id="2858"><summary></span> -- <span id="d970"><time></span> - -These tags are important because they let you identify the content that's most relevant to users. In short: making it easy for search engines makes it easier for users to find you. - -### 2. Meta SEO tags - -Aside from on-page structure, you can also help web crawlers understand your site by titling and describing your pages as a whole. We outline a few tips <a href="https://webflow.com/blog/website-seo" class="markup--anchor markup--p-anchor">on website SEO on our blog</a>, narrowed down to 2 main considerations below. - -#### Meta title - -Your page's meta title translates to the linked text people will see on search engine result pages (SERPs). It also displays on the browser tab when people click through to your page. Some best practices include: - -- <span id="ed19">Define the page's central topic</span> -- <span id="c50a">Keep it under 70 characters in length (including spaces)</span> -- <span id="e656">Use relevant keywords</span> -- <span id="c74d">Put important keywords in the front of the title</span> - -#### Meta description - -The meta description is a short sentence (or two) that describes what your website has to offer. It will (sometimes) show up below your meta title in search results. - -Some best practices include: - -- <span id="aec5">Include keywords that describe the page</span> -- <span id="022c">Don't go over 160 characters</span> -- <span id="13ac">Write your description for people, not robots. (Google doesn't use descriptions in web rankings).</span> - -### 3. Open Graph settings - -Social media has become a key element of SEO, so it's crucial that you amplify this process by providing effective Open Graph information. Open Graph settings include three pieces of content: title, description, and an image. - -The title and description follow the same rules as their SEO counterparts, but instead of showing up in search results, they appear as the default title and description on social media platforms when shared. - -This is hugely beneficial because it lets you determine what the messaging (and image) will be when others share your website, helping you keep control of your brand. - ---- - -### Tool List: - -### Update: - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*8luiRPwHqkyfqJfb" class="graf-image" /></figure><a href="https://caniuse.com/" class="markup--anchor markup--p-anchor">Can I UseProvides browser support information of front-end web technologies. Enter a search term to find out which browsers support it. <em>caniuse.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*t50QcwzBkwFuth4o" class="graf-image" /></figure><a href="https://html-online.com/editor/" class="markup--anchor markup--p-anchor">Online HTML EditorFree online HTML editor with WYSIWYG and source composer and instant preview and many useful built-in features <em>html-online.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*SnFMpz919DboGmr-" class="graf-image" /></figure><a href="https://html-cleaner.com/" class="markup--anchor markup--p-anchor">Web CleanerOnline HTML, CSS and JavaScript cleaner and code editors with syntax highlighting and customizable cleaning features. <em>html-cleaner.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*2KRsAowQaufNBiSs" class="graf-image" /></figure><a href="https://wordhtml.com/" class="markup--anchor markup--p-anchor">Word HTMLFree online Word and other rich text editor and HTML converter. Copy-paste your document in the editor and switch to HTML view to get the code. <em>wordhtml.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*A_wBLhhToeFlXuLg" class="graf-image" /></figure><a href="https://htmlcheatsheet.com/" class="markup--anchor markup--p-anchor">HTML Cheat SheetHTML, CSS, JavaScript and other web technology cheat sheet with interactive user interface. Grab the code you're looking for quickly. <em>htmlcheatsheet.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*393SncqM14lxdAYX" class="graf-image" /></figure><a href="https://stackoverflow.com/" class="markup--anchor markup--p-anchor">Stack OverflowHuge programmer community where you usually don't have to ask for help because probably someone has already answered the same question. <em>stackoverflow.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*veTjmob-9SlcsbfY" class="graf-image" /></figure><a href="https://www.w3schools.com/" class="markup--anchor markup--p-anchor">w3schoolsThe place to learn web technologies. There's a big chance that this site gives the first search result when you're looking for a HTML term. <em>w3schools.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*mcOcJb9_CRucZ8Hi" class="graf-image" /></figure><a href="https://developer.mozilla.org/" class="markup--anchor markup--p-anchor">Mozzilla Developer NetworkAn evolving learning platform for web technologies. Providing tutorials, developer tools and the information to easily build projects. <em>developer.mozilla.org</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*1A0zYmYhuNwVv-JD" class="graf-image" /></figure><a href="https://validator.w3.org/" class="markup--anchor markup--p-anchor">Markup ValidatorEnter the link of a webpage and the online tool will highlight the errors and warnings to fix in the source code. <em>validator.w3.org</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*qkBfaTWhlKlbtmsf" class="graf-image" /></figure><a href="https://github.com/" class="markup--anchor markup--p-anchor">GitHubCollaborate with other developers. Fork, send pull requests and manage all your public and private git repositories. <em>github.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*xuAlgMUU6yPrTp-y" class="graf-image" /></figure><a href="https://bitbucket.org/" class="markup--anchor markup--p-anchor">BitbucketWeb-based hosting service for development projects with version control system that makes it easy for you to collaborate with your team. <em>bitbucket.org</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*XiFbqTuL0zs0ZeWn" class="graf-image" /></figure><a href="https://dribbble.com/" class="markup--anchor markup--p-anchor">DribbleTell others what are you working on! Dribbble is a community of designers sharing screenshots of their work, process, and projects. <em>dribbble.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*Z7rf2N2ZanFTyC24" class="graf-image" /></figure><a href="https://builtwith.com/" class="markup--anchor markup--p-anchor">Built WithEnter a domain name to find out who is hosting it, what CMS and framework is used and many other insights. <em>builtwith.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*JAKvGWN_Sd05kCwa" class="graf-image" /></figure><a href="https://htmltidy.net/" class="markup--anchor markup--p-anchor">HTML TidyAn online tool for checking and cleaning up HTML source files. Useful for finding and correcting errors in deeply nested HTML. <em>htmltidy.net</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*NobceO9h1WGoiAh5" class="graf-image" /></figure><a href="https://divtable.com/" class="markup--anchor markup--p-anchor">Div TableCreate or convert tables to responsive div tags with a few clicks. Use the provided CSS code to render the divs as table cells. <em>divtable.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*NFqBo-YVX2D2dtFh" class="graf-image" /></figure><a href="https://getbootstrap.com/" class="markup--anchor markup--p-anchor">BootstrapThe most popular free and open-source HTML, CSS, and JS framework makes front-end development easier and faster. <em>getbootstrap.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*rHGXn1mVlS3XJNCV" class="graf-image" /></figure><a href="https://htmlg.com/html-editor/" class="markup--anchor markup--p-anchor">HTMLGProfessional HTML editor. The free version is enough to do magic with your markup. Tag and attribute manager filter etc. <em>htmlg.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*zzrT9kYMdxxAHwb8" class="graf-image" /></figure><a href="https://developers.facebook.com/" class="markup--anchor markup--p-anchor">Facebook DevelopersDeveloper tools for login, share widget, analytics, monetization, messenger platform and more from the biggest social media site. <em>developers.facebook.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*CmpW2L4pVbESIh5J" class="graf-image" /></figure><a href="https://search.google.com/test/mobile-friendly" class="markup--anchor markup--p-anchor">Google Mobile-Friendly TestCheck if Google considers your web page mobile-friendly and adjust the deficiencies if there is any. <em>google.com/mobile-friendly</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*mKshXXHbzoStzvjr" class="graf-image" /></figure><a href="https://www.webpagetest.org/" class="markup--anchor markup--p-anchor">Webpage Speed TestAnalize the loading speed of a website from many available servers. The website creates a detailed analysis with screenshot and waterfall view. <em>webpagetest.org</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*sYIvpZGnkNhf-_XC" class="graf-image" /></figure><a href="https://netrenderer.com/" class="markup--anchor markup--p-anchor">NetRendererRenders quickly a webpage with the selected version of the old Internet Explorer web browser. NetRenderer goes back to IE version 5.5. <em>netrenderer.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*unIWXerRzCuxrzng" class="graf-image" /></figure><a href="http://browsershots.org/" class="markup--anchor markup--p-anchor">Browser ShotsCreate the screenshot of a webpage with many available browsers in various operating systems. <em>browsershots.org</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*bX3AIaYOSzadB8t6" class="graf-image" /></figure><a href="https://developers.google.com/speed/pagespeed/insights/" class="markup--anchor markup--p-anchor">PageSpeed InsightsThis tool by Google analyzes the submitted link from mobile and desktop to suggest you what to consider optimizing. <em>developers.google.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*v1hxqLrwUWL2dbBX" class="graf-image" /></figure><a href="https://fonts.google.com/" class="markup--anchor markup--p-anchor">Google FontsAn interactive directory of over 800 free hosted web fonts. It allows to optimize loading speed by including only what you need. <em>fonts.google.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*n4slofmCAW3PUOTn" class="graf-image" /></figure><a href="https://fontawesome.com/" class="markup--anchor markup--p-anchor">Font AwesomeThe most popular icon set based on CSS and LESS. The vector icons can be customized as text — size, color, drop shadow <em>fontawesome.io</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*_k2GQpr-IXMCfCbD" class="graf-image" /></figure><a href="https://rgbcolorcode.com/" class="markup--anchor markup--p-anchor">RGB Color CodesSearch and save color codes. Search by name or mix the RGB, HSV or CMYK values. Use the generated HTML/CSS codes. <em>rgbcolorcode.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*IH19Lh2SggZ5fNd_" class="graf-image" /></figure><a href="https://www.freepik.com/" class="markup--anchor markup--p-anchor">FreePicBrowse the large directory of free photos, vector arts, icons, illustrations, PSD files at FreePic. <em>freepik.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*g9YcUHOEU2oybdxl" class="graf-image" /></figure><a href="https://placehold.it/" class="markup--anchor markup--p-anchor">Placehold.it/Image placeholders with customizable size. Just add the image resolution after the domain name, for example placehold.it/400x250 <em>placehold.it</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*PSn8d5FL7_ngjJtU" class="graf-image" /></figure><a href="https://www.xml-sitemaps.com/" class="markup--anchor markup--p-anchor">XML SitemapsGenerate XML sitemaps and URL list of a website. The crawl limit is 500 pages. <em>xml-sitemaps.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*673487vh2n0o7Ub6" class="graf-image" /></figure><a href="http://www.brokenlinkcheck.com/" class="markup--anchor markup--p-anchor">Broken Link CheckerCrawl a domain for dead links. Locates both internal and external links pointing to 404 error pages. <em>brokenlinkcheck.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*NrZDjNLAdMcfK8Hy" class="graf-image" /></figure><a href="https://codepen.io/" class="markup--anchor markup--p-anchor">CodepenRegister to create, save and share HTML-CSS-JS code snippets and run them online. <em>codepen.io</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*1EEf11CeSLOOAAyu" class="graf-image" /></figure><a href="https://jsfiddle.net/" class="markup--anchor markup--p-anchor">JSFiddleSimilar to Codepen but this one doesn't require registration. Test HTML-CSS-JS code online and save your small project in a shareable URL. <em>jsfiddle.net</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*2Aq8QOCznCo11ypk" class="graf-image" /></figure><a href="https://wordpress.org/" class="markup--anchor markup--p-anchor">WordPress.OrgMore than 10 million websites use this free and open-source content management system based on PHP-MySql. <em>wordpress.org</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*CJX2RwykNQ9O0RbL" class="graf-image" /></figure><a href="https://www.theblogstarter.com/" class="markup--anchor markup--p-anchor">Blog StarterA free guide that shows beginners how to start a blog using WordPress.org <em>theblogstarter.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*QSwvNaVB8SOgyDqp" class="graf-image" /></figure><a href="https://websitesetup.org/" class="markup--anchor markup--p-anchor">Website SetupA friendly guide about how to make a website, discussing the hosting, the CMS, domain name and promotion. <em>websitesetup.org</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*m7_ugygIICt4VLea" class="graf-image" /></figure><a href="https://www.expireddomains.net/" class="markup--anchor markup--p-anchor">Expired DomainsHunt for expired domain names or get inspiration for your next project. It's worth registering for an account on this free website. <em>expireddomains.net</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*PNRVuj1GX-jgppng" class="graf-image" /></figure><a href="https://badhtml.com/" class="markup--anchor markup--p-anchor">Bad HTMLThe ugliest website on the internet, collecting bad UI/UX practices. A deterrent example about how not to build a website. <em>badhtml.com</em></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*66ncH3hioTVPIr2l" class="graf-image" /></figure><a href="https://1stwebdesigner.com/" class="markup--anchor markup--p-anchor">1st Web DesignerFollow this web design blog to find out what's new in freelance, marketing, UX etc. categories. <em>1stwebdesigner.com</em></a> - ---- - -<a href="http://toptal.com/developers" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://toptal.com/developers"><strong>Hire Freelance Developers from the Top 3% - Toptal®</strong> -<br/> - -<em>Toptal is a marketplace for top developers, engineers, programmers, coders, architects, and consultants. Top companies…</em>toptal.com</a><a href="http://toptal.com/developers" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://chrome.google.com/webstore/detail/web-developer-checklist/iahamcpedabephpcgkeikbclmaljebjp?hl=en-US" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://chrome.google.com/webstore/detail/web-developer-checklist/iahamcpedabephpcgkeikbclmaljebjp?hl=en-US"><strong>Web Developer Checklist</strong> -<br/> - -<em>Analyses any web page for violations of best practices</em>chrome.google.com</a><a href="https://chrome.google.com/webstore/detail/web-developer-checklist/iahamcpedabephpcgkeikbclmaljebjp?hl=en-US" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://addons.mozilla.org/en-US/firefox/addon/webdeveloperchecklist/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://addons.mozilla.org/en-US/firefox/addon/webdeveloperchecklist/"><strong>Web Developer Checklist - Get this Extension for 🦊 Firefox (en-US)</strong> -<br/> - -<em>Download Web Developer Checklist for Firefox. Analyzes any web page for violations of best practices.</em>addons.mozilla.org</a><a href="https://addons.mozilla.org/en-US/firefox/addon/webdeveloperchecklist/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://validator.w3.org/checklink" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://validator.w3.org/checklink"><strong>Link Checker</strong> -<br/> - -<em>Check links and anchors in Web pages or full Web sites This Link Checker looks for issues in links, anchors and…</em>validator.w3.org</a><a href="https://validator.w3.org/checklink" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://en.wikipedia.org/wiki/Capitalization" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://en.wikipedia.org/wiki/Capitalization"><strong>Capitalization - Wikipedia</strong> -<br/> - -<em>Capitalization ( American English) or capitalisation ( British English) is writing a word with its first letter as a…</em>en.wikipedia.org</a><a href="https://en.wikipedia.org/wiki/Capitalization" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://en.wikipedia.org/wiki/Writing_style" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://en.wikipedia.org/wiki/Writing_style"><strong>Writing style - Wikipedia</strong> -<br/> - -<em>In literature, writing style is the manner of expressing thought in language characteristic of an individual, period…</em>en.wikipedia.org</a><a href="https://en.wikipedia.org/wiki/Writing_style" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://en.wikipedia.org/wiki/American_and_British_English_spelling_differences" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://en.wikipedia.org/wiki/American_and_British_English_spelling_differences"><strong>American and British English spelling differences - Wikipedia</strong> -<br/> - -<em>Despite the various English dialects spoken from country to country and within different regions of the same country…</em>en.wikipedia.org</a><a href="https://en.wikipedia.org/wiki/American_and_British_English_spelling_differences" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="http://browsershots.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://browsershots.org/"><strong>Check Browser Compatibility, Cross Platform Browser Test - Browsershots</strong> -<br/> - -<em>Browsershots makes screenshots of your web design in different operating systems and browsers. It is a free open-source…</em>browsershots.org</a><a href="http://browsershots.org/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://browserling.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://browserling.com/"><strong>Online cross-browser testing</strong> -<br/> - -<em>Browserling did a custom cross-browser testing solution for UK's National Health Service. Our application needs to…</em>browserling.com</a><a href="https://browserling.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.browserstack.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.browserstack.com/"><strong>Most Reliable App & Cross Browser Testing Platform | BrowserStack</strong> -<br/> - -<em>Just played around with BrowserStack: Quite cool, instant access to a browser in a VM with dev tools. Big thanks to…</em>www.browserstack.com</a><a href="https://www.browserstack.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.lambdatest.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.lambdatest.com/"><strong>Most Powerful Cross Browser Testing Tool Online | LambdaTest</strong> -<br/> - -<em>Perform Live Interactive and Automated Cross Browser Testing on 2000+ Real Browsers and Operating Systems Online Run…</em>www.lambdatest.com</a><a href="https://www.lambdatest.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://crossbrowsertesting.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://crossbrowsertesting.com/"><strong>Cross Browser Testing Tool: 2050+ Real Browsers & Devices</strong> -<br/> - -<em>We have estimated that by transitioning to automated front-end visual testing and by having easy access to so many…</em>crossbrowsertesting.com</a><a href="https://crossbrowsertesting.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="http://no-www.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://no-www.org/"><strong>www. is deprecated.</strong> -<br/> - -<em>Stay in touch! Dec 21, 2012 No-WWW now hasa a social media presence! Check us out on Twitter at @www_deprecated . We…</em>no-www.org</a><a href="http://no-www.org/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://www.yes-www.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.yes-www.org/"><strong>www. is not deprecated</strong> -<br/> - -<em>Ever since the first traditional media ads began to appear with Web site addresses in them 25 years ago, people have…</em>www.yes-www.org</a><a href="https://www.yes-www.org/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="http://madskristensen.net/post/url-rewrite-and-the-www-subdomain" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://madskristensen.net/post/url-rewrite-and-the-www-subdomain"><strong>URL rewrite and the www subdomain</strong> -<br/> - -<em>What's the address of your website? www.domain.com or domain.com? There are two camps on the subject of the www…</em>madskristensen.net</a><a href="http://madskristensen.net/post/url-rewrite-and-the-www-subdomain" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://www.google.com/webmasters/tools/mobile-friendly/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.google.com/webmasters/tools/mobile-friendly/"><strong>Mobile-Friendly Test - Google Search Console</strong> -<br/> - -<em>Is your web page mobile-friendly? Test how easily a visitor can use your page on a mobile device. Just enter a page URL…</em>www.google.com</a><a href="https://www.google.com/webmasters/tools/mobile-friendly/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://webdesign.tutsplus.com/articles/quick-tip-dont-forget-the-viewport-meta-tag--webdesign-5972" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://webdesign.tutsplus.com/articles/quick-tip-dont-forget-the-viewport-meta-tag--webdesign-5972"><strong>Quick Tip: Don't Forget the Viewport Meta Tag</strong> -<br/> - -<em>I remember my maiden voyage into responsive web design; I'd used a classic grid, wrestled with a flexible layout, and…</em>webdesign.tutsplus.com</a><a href="https://webdesign.tutsplus.com/articles/quick-tip-dont-forget-the-viewport-meta-tag--webdesign-5972" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://html5tutorial.info/html5-contact.php" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://html5tutorial.info/html5-contact.php"><strong>Input Type : Email,URL,Phone</strong> -<br/> - -<em>Email, Phone number and Website url are the three most commonly used contact detail which has its unique input…</em>html5tutorial.info</a><a href="https://html5tutorial.info/html5-contact.php" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="http://diveintohtml5.info/forms.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://diveintohtml5.info/forms.html"><strong>Web Forms - Dive Into HTML5</strong> -<br/> - -<em>Edit description</em>diveintohtml5.info</a><a href="http://diveintohtml5.info/forms.html" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.browserstack.com/responsive" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.browserstack.com/responsive"><strong>Responsive Testing On 2000+ Real Devices & Browsers | BrowserStack</strong> -<br/> - -<em>Frequently Asked Questions Why is responsive testing critical for your website? Responsive design enables a website to…</em>www.browserstack.com</a><a href="https://www.browserstack.com/responsive" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.uptimerobot.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.uptimerobot.com/"><strong>UptimeRobot | Free Website Monitoring</strong> -<br/> - -<em>Get up to 50 website, port or heartbeat monitors for free. When something happens, we'll notify you via email, SMS…</em>www.uptimerobot.com</a><a href="https://www.uptimerobot.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.statuscake.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.statuscake.com/"><strong>StatusCake: Website Monitoring with Uptime Monitoring solution</strong> -<br/> - -<em>Website Monitoring solution that drives revenue & keeps you online. Track your uptime, page speed, domain, server, &…</em>www.statuscake.com</a><a href="https://www.statuscake.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.google.com/analytics" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.google.com/analytics"><strong>Analytics Tools & Solutions for Your Business - Google Analytics</strong> -<br/> - -<em>Easily access data from other Google solutions while working in Analytics, for a seamless workflow that saves you time…</em>www.google.com</a><a href="https://www.google.com/analytics" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://statcounter.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://statcounter.com/"><strong>Statcounter - Web Analytics Made Easy</strong> -<br/> - -<em>Watch in real time as visitors navigate through your website. Are they flowing through your site the way you expect…</em>statcounter.com</a><a href="https://statcounter.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://clicky.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://clicky.com/"><strong>Real Time Web Analytics</strong> -<br/> - -<em>Clicky Web Analytics is simply the best way to monitor, analyze, and react to your blog or web site's traffic in real…</em>clicky.com</a><a href="https://clicky.com/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://matomo.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://matomo.org/"><strong>Matomo - The Google Analytics alternative that protects your data</strong> -<br/> - -<em>Matomo's the Google Analytics alternative that protects your data and your customer's privacy. A powerful web analytics…</em>matomo.org</a><a href="https://matomo.org/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://developers.google.com/speed/pagespeed/insights/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://developers.google.com/speed/pagespeed/insights/"><strong>PageSpeed Insights</strong> -<br/> - -<em>Have specific, answerable questions about using PageSpeed Insights? Ask your question on Stack Overflow. For general…</em>developers.google.com</a><a href="https://developers.google.com/speed/pagespeed/insights/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://redbot.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://redbot.org/"><strong>REDbot</strong> -<br/> - -<em>Lint for your HTTP resources</em>redbot.org</a><a href="https://redbot.org/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://pageweight.imgix.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://pageweight.imgix.com/"><strong>imgix Page Weight Tool \* Learn how to improve your site or app's speed.</strong> -<br/> - -<em>imgix Page Weight Tool measures the resources on your site and then recommends how to improve your site's load time.</em>pageweight.imgix.com</a><a href="https://pageweight.imgix.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://tinypng.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://tinypng.com/"><strong>TinyPNG - Compress PNG images while preserving transparency</strong> -<br/> - -<em>Excellent question! Let me give you a side by side comparison. Below are two photos of my cousin. The left image is…</em>tinypng.com</a><a href="https://tinypng.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://kraken.io/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://kraken.io/"><strong>Kraken.io Image Optimizer</strong> -<br/> - -<em>Kraken.io is a robust, ultra-fast image optimizer. Thanks to its vast array of optimization algorithms Kraken.io is a…</em>kraken.io</a><a href="https://kraken.io/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://squoosh.app/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://squoosh.app/"><strong>Squoosh</strong> -<br/> - -<em>Compress and compare images with different codecs, right in your browser</em>squoosh.app</a><a href="https://squoosh.app/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="http://pnggauntlet.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://pnggauntlet.com/"><strong>PNGGauntlet - PNG Compression Software</strong> -<br/> - -<em>PNGGauntlet 3.1.2 is a minor update that resolves some bugs, and adds a much-requested option. First, the bugfixes …</em>pnggauntlet.com</a><a href="http://pnggauntlet.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://imageoptim.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://imageoptim.com/"><strong>ImageOptim - better Save for Web</strong> -<br/> - -<em>Reduces image file sizes - so they take up less disk space and down­load faster - by applying advanced compression…</em>imageoptim.com</a><a href="https://imageoptim.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://caniuse.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://caniuse.com/"><strong>Can I use... Support tables for HTML5, CSS3, etc</strong> -<br/> - -<em>Test a feature Our partnership with BrowserStack now lets you test your website for compatibility across 2,000+ real…</em>caniuse.com</a><a href="https://caniuse.com/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://modernizr.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://modernizr.com/"><strong>Modernizr: the feature detection library for HTML5/CSS3</strong> -<br/> - -<em>All web developers come up against differences between browsers and devices. That's largely due to different feature…</em>modernizr.com</a><a href="https://modernizr.com/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://validator.w3.org/i18n-checker/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://validator.w3.org/i18n-checker/"><strong>W3C I18n Checker</strong> -<br/> - -<em>This checker performs various tests on a Web Page to determine its level of internationalisation-friendliness. It also…</em>validator.w3.org</a><a href="https://validator.w3.org/i18n-checker/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.alistapart.com/articles/amoreuseful404/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.alistapart.com/articles/amoreuseful404/"><strong>A More Useful 404</strong> -<br/> - -<em>Encountering 404 errors is not new. Often, developers provide custom 404 pages to make the experience a little less…</em>www.alistapart.com</a><a href="https://www.alistapart.com/articles/amoreuseful404/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://realfavicongenerator.net/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://realfavicongenerator.net/"><strong>Favicon Generator for perfect icons on all browsers</strong> -<br/> - -<em>The ultimate favicon generator. Design your icons platform per platform and make them look great everywhere. Including…</em>realfavicongenerator.net</a><a href="https://realfavicongenerator.net/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://github.com/audreyr/favicon-cheat-sheet" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://github.com/audreyr/favicon-cheat-sheet"><strong>audreyfeldroy/favicon-cheat-sheet</strong> -<br/> - -<em>A painfully obsessive cheat sheet to favicon sizes/types. Compiled from: For the main favicon itself, it's best for…</em>github.com</a><a href="https://github.com/audreyr/favicon-cheat-sheet" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://moz.com/learn/seo/url" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://moz.com/learn/seo/url"><strong>URL Structure [2021 SEO]</strong> -<br/> - -<em>Keeping URLs as simple, relevant, compelling, and accurate as possible is key to getting both your users and search…</em>moz.com</a><a href="https://moz.com/learn/seo/url" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://docs.microsoft.com/en-us/iis/extensions/url-rewrite-module/url-rewrite-module-configuration-reference" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://docs.microsoft.com/en-us/iis/extensions/url-rewrite-module/url-rewrite-module-configuration-reference"><strong>URL Rewrite Module Configuration Reference</strong> -<br/> - -<em>by Ruslan Yakushev This article provides an overview of the URL Rewrite Module and explains the configuration concepts…</em>docs.microsoft.com</a><a href="https://docs.microsoft.com/en-us/iis/extensions/url-rewrite-module/url-rewrite-module-configuration-reference" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://httpd.apache.org/docs/current/mod/mod_rewrite.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://httpd.apache.org/docs/current/mod/mod_rewrite.html"><strong>mod_rewrite - Apache HTTP Server Version 2.4</strong> -<br/> - -<em>The mod_rewrite module uses a rule-based rewriting engine, based on a PCRE regular-expression parser, to rewrite…</em>httpd.apache.org</a><a href="https://httpd.apache.org/docs/current/mod/mod_rewrite.html" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.nginx.com/blog/creating-nginx-rewrite-rules/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.nginx.com/blog/creating-nginx-rewrite-rules/"><strong>How to Create NGINX Rewrite Rules | NGINX</strong> -<br/> - -<em>In this blog post, we discuss how to create NGINX rewrite rules (the same methods work for both NGINX Plus and the open…</em>www.nginx.com</a><a href="https://www.nginx.com/blog/creating-nginx-rewrite-rules/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.smashingmagazine.com/2011/11/how-to-set-up-a-print-style-sheet/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.smashingmagazine.com/2011/11/how-to-set-up-a-print-style-sheet/"><strong>How To Set Up A Print Style Sheet - Smashing Magazine</strong> -<br/> - -<em>In a time when everyone seems to have a tablet, which makes it possible to consume everything digitally, and the only…</em>www.smashingmagazine.com</a><a href="https://www.smashingmagazine.com/2011/11/how-to-set-up-a-print-style-sheet/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.google.com/cse/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.google.com/cse/"><strong>Programmable Search Engine by Google</strong> -<br/> - -<em>Decide if you want users to search only your website, or include other sites on the web. Match the design to your site…</em>www.google.com</a><a href="https://www.google.com/cse/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://github.com/dewitt/opensearch" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://github.com/dewitt/opensearch"><strong>dewitt/opensearch</strong> -<br/> - -<em>OpenSearch is a collection of simple formats for the sharing of search results. The most recent version of the…</em>github.com</a><a href="https://github.com/dewitt/opensearch" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html"><strong>Configuring Web Applications</strong> -<br/> - -<em>A web application is designed to look and behave in a way similar to a native application-for example, it is scaled to…</em>developer.apple.com</a><a href="https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/dev-guides/hh781490%28v=vs.85%29" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/dev-guides/hh781490(v=vs.85)"><strong>Windows 8 integration (Windows)</strong> -<br/> - -<em>This section details the ways in which web developers can take advantage of the tight integration of Windows 8 and…</em>docs.microsoft.com</a><a href="https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/dev-guides/hh781490%28v=vs.85%29" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://schema.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://schema.org/"><strong>Schema.org - Schema.org</strong> -<br/> - -<em>Schema.org is a collaborative, community activity with a mission to create, maintain, and promote schemas for…</em>schema.org</a><a href="https://schema.org/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://seoscout.com/tools/schema-generator" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://seoscout.com/tools/schema-generator"><strong>Schema Markup Generator & Structured Data Testing Tool (inc JSON-LD)</strong> -<br/> - -<em>By adding the JSON-LD this tool generates to your pages you help Google better understand their purpose.Make it easy…</em>seoscout.com</a><a href="https://seoscout.com/tools/schema-generator" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://search.google.com/structured-data/testing-tool/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://search.google.com/structured-data/testing-tool/"><strong>Structured Data Testing Tool</strong> -<br/> - -<em>Edit description</em>search.google.com</a><a href="https://search.google.com/structured-data/testing-tool/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://developers.facebook.com/tools/debug/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://developers.facebook.com/tools/debug/"><strong>Sharing Debugger - Facebook for Developers</strong> -<br/> - -<em>Sharing Debugger lets you preview how your content will look when it's shared to Facebook and debug any issues with…</em>developers.facebook.com</a><a href="https://developers.facebook.com/tools/debug/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://cards-dev.twitter.com/validator" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://cards-dev.twitter.com/validator"><strong>JavaScript is not available.</strong> -<br/> - -<em>Edit description</em>cards-dev.twitter.com</a><a href="https://cards-dev.twitter.com/validator" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://search.google.com/test/rich-results" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://search.google.com/test/rich-results"><strong>Rich Results Test - Google Search Console</strong> -<br/> - -<em>Does your page support rich results? What are rich results? Rich results are experiences on Google surfaces, such as…</em>search.google.com</a><a href="https://search.google.com/test/rich-results" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://schema.org/docs/gs.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://schema.org/docs/gs.html"><strong>Getting Started - schema.org</strong> -<br/> - -<em>Most webmasters are familiar with HTML tags on their pages. Usually, HTML tags tell the browser how to display the…</em>schema.org</a><a href="https://schema.org/docs/gs.html" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="http://tools.seobook.com/robots-txt/" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://tools.seobook.com/robots-txt/"><strong>Robots.txt Tutorial</strong> -<br/> - -<em>Use our Robots.txt generator to create a robots.txt file. Use our Robots.txt analyzer to analyze your robots.txt file…</em>tools.seobook.com</a><a href="http://tools.seobook.com/robots-txt/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="http://www.robotsgenerator.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://www.robotsgenerator.com/"><strong>Robots Generator | Generate robots.txt Files Instantly - RobotsGenerator.com</strong> -<br/> - -<em>Select folders and/or files If there are areas of your page you do not wish made public, simply indicate the…</em>www.robotsgenerator.com</a><a href="http://www.robotsgenerator.com/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://www.xml-sitemaps.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.xml-sitemaps.com/"><strong>Create your Google Sitemap Online - XML Sitemaps Generator</strong> -<br/> - -<em>Free Online Google Sitemap Generator. XML-sitemaps.com provides free online sitemap generator service, creating an XML…</em>www.xml-sitemaps.com</a><a href="https://www.xml-sitemaps.com/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://validator.w3.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://validator.w3.org/"><strong>Markup Validation Service</strong> -<br/> - -<em>W3C's easy-to-use markup validation service, based on SGML and XML parsers.</em>validator.w3.org</a><a href="https://validator.w3.org/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://html5.validator.nu/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://html5.validator.nu/"><strong>Validator.nu (X)HTML5 Validator</strong> -<br/> - -<em>Edit description</em>html5.validator.nu</a><a href="https://html5.validator.nu/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://jigsaw.w3.org/css-validator/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://jigsaw.w3.org/css-validator/"><strong>CSS Validation Service</strong> -<br/> - -<em>Check Cascading Style Sheets (CSS) and (X)HTML documents with style sheets</em>jigsaw.w3.org</a><a href="https://jigsaw.w3.org/css-validator/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="http://csslint.net/" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://csslint.net/"><strong>CSS Lint</strong> -<br/> - -<em>CSS lint found 0 errors and 0 warnings. How can you fix it? See the details below.</em>csslint.net</a><a href="http://csslint.net/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://jslint.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://jslint.com/"><strong>JSLint: The JavaScript Code Quality Tool</strong> -<br/> - -<em>JSLint, The JavaScript Code Quality Tool. This file allows JSLint to be run from a web browser. It can accept a source…</em>jslint.com</a><a href="https://jslint.com/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://jshint.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://jshint.com/"><strong>JSHint, a JavaScript Code Quality Tool</strong> -<br/> - -<em>Report Cyclomatic complexity Unused variables Undefined variables Warn About == null About debugging code About unsafe…</em>jshint.com</a><a href="https://jshint.com/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://www.w3.org/WAI/standards-guidelines/wcag/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.w3.org/WAI/standards-guidelines/wcag/"><strong>Web Content Accessibility Guidelines (WCAG) Overview</strong> -<br/> - -<em>Introducing the Web Content Accessibility Guidelines (WCAG), including WCAG 2.0 and WCAG 2.1. Quick links to resources…</em>www.w3.org</a><a href="https://www.w3.org/WAI/standards-guidelines/wcag/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility"><strong>Handling common accessibility problems - Learn web development | MDN</strong> -<br/> - -<em>Next we turn our attention to accessibility, providing information on common problems, how to do simple testing, and…</em>developer.mozilla.org</a><a href="https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://wave.webaim.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://wave.webaim.org/"><strong>WAVE Web Accessibility Evaluation Tool</strong> -<br/> - -<em>WAVE is a suite of evaluation tools that helps authors make their web content more accessible to individuals with…</em>wave.webaim.org</a><a href="https://wave.webaim.org/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.nvaccess.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.nvaccess.org/"><strong>NV Access</strong> -<br/> - -<em>Access to technology no matter your language, location or financial situation Quality over growth, access over profit…</em>www.nvaccess.org</a><a href="https://www.nvaccess.org/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://webaim.org/resources/contrastchecker/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://webaim.org/resources/contrastchecker/"><strong>Contrast Checker</strong> -<br/> - -<em>The five boxing wizards jump quickly. The five boxing wizards jump quickly. Enter a foreground and background color in…</em>webaim.org</a><a href="https://webaim.org/resources/contrastchecker/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://accessibility.oit.ncsu.edu/using-aria-landmarks-a-demonstration/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://accessibility.oit.ncsu.edu/using-aria-landmarks-a-demonstration/"><strong>Using ARIA Landmarks - A Demonstration</strong> -<br/> - -<em>ARIA landmarks are attributes you add to elements to create semantically defined sections of a page that allow users of…</em>accessibility.oit.ncsu.edu</a><a href="https://accessibility.oit.ncsu.edu/using-aria-landmarks-a-demonstration/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://alistapart.com/article/the-accessibility-of-wai-aria/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://alistapart.com/article/the-accessibility-of-wai-aria/"><strong>The Accessibility of WAI-ARIA</strong> -<br/> - -<em>Web developers interested in accessibility issues often discuss WAI-ARIA, an upcoming W3C candidate recommendation…</em>alistapart.com</a><a href="https://alistapart.com/article/the-accessibility-of-wai-aria/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="http://www.punkchip.com/2010/11/aria-basic-findings/" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://www.punkchip.com/2010/11/aria-basic-findings/"><strong>WAI-ARIA states and properties: Practical examples</strong> -<br/> - -<em>I've been trying to include some WAI-ARIA into the project I'm currently working on. Luckily for me I'm using jQuery's…</em>www.punkchip.com</a><a href="http://www.punkchip.com/2010/11/aria-basic-findings/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://observatory.mozilla.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://observatory.mozilla.org/"><strong>Mozilla Observatory</strong> -<br/> - -<em>The Mozilla Observatory is a project designed to help developers, system administrators, and security professionals…</em>observatory.mozilla.org</a><a href="https://observatory.mozilla.org/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html"><strong>Cross Site Scripting Prevention - OWASP Cheat Sheet Series</strong> -<br/> - -<em>This article provides a simple positive model for preventing XSS using output encoding properly. While there are a huge…</em>cheatsheetseries.owasp.org</a><a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html"><strong>DOM based XSS Prevention - OWASP Cheat Sheet Series</strong> -<br/> - -<em>When looking at XSS (Cross-Site Scripting), there are three generally recognized forms of XSS: The XSS Prevention…</em>cheatsheetseries.owasp.org</a><a href="https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://blog.codinghorror.com/cross-site-request-forgeries-and-you/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://blog.codinghorror.com/cross-site-request-forgeries-and-you/"><strong>Cross-Site Request Forgeries and You</strong> -<br/> - -<em>As the web becomes more and more pervasive, so do web-based security vulnerabilities. I talked a little bit about the…</em>blog.codinghorror.com</a><a href="https://blog.codinghorror.com/cross-site-request-forgeries-and-you/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html"><strong>Cross-Site Request Forgery Prevention - OWASP Cheat Sheet Series</strong> -<br/> - -<em>Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious web site, email, blog, instant…</em>cheatsheetseries.owasp.org</a><a href="https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://letsencrypt.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://letsencrypt.org/"><strong>Let's Encrypt</strong> -<br/> - -<em>Let's Encrypt is a free, automated, and open certificate authority brought to you by the nonprofit Internet Security…</em>letsencrypt.org</a><a href="https://letsencrypt.org/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://support.microsoft.com/en-gb/help/299875/how-to-implement-ssl-in-iis" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://support.microsoft.com/en-gb/help/299875/how-to-implement-ssl-in-iis"><strong>How to Set Up SSL on IIS 7</strong> -<br/> - -<em>by Saad Ladki The steps for configuring Secure Sockets Layer (SSL) for a site are the same in IIS 7 and above and IIS…</em>support.microsoft.com</a><a href="https://support.microsoft.com/en-gb/help/299875/how-to-implement-ssl-in-iis" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://www.digicert.com/kb/csr-ssl-installation/apache-openssl.htm#ssl_certificate_install" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.digicert.com/kb/csr-ssl-installation/apache-openssl.htm#ssl_certificate_install"><strong>Apache: CSR & SSL Installation (OpenSSL)</strong> -<br/> - -<em>Use the instructions on this page to use OpenSSL to create your certificate signing request (CSR) and then to install…</em>www.digicert.com</a><a href="https://www.digicert.com/kb/csr-ssl-installation/apache-openssl.htm#ssl_certificate_install" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://nginx.org/en/docs/http/configuring_https_servers.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://nginx.org/en/docs/http/configuring_https_servers.html"><strong>Configuring HTTPS servers</strong> -<br/> - -<em>To configure an HTTPS server, the ssl parameter must be enabled on listening sockets in the server block, and the…</em>nginx.org</a><a href="https://nginx.org/en/docs/http/configuring_https_servers.html" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://www.ssllabs.com/ssltest/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.ssllabs.com/ssltest/"><strong>SSL Server Test</strong> -<br/> - -<em>This free online service performs a deep analysis of the configuration of any SSL web server on the public Internet…</em>www.ssllabs.com</a><a href="https://www.ssllabs.com/ssltest/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security"><strong>Strict-Transport-Security - HTTP | MDN</strong> -<br/> - -<em>The HTTP Strict-Transport-Security response header (often abbreviated as HSTS) lets a web site tell browsers that it…</em>developer.mozilla.org</a><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Strict_Transport_Security_Cheat_Sheet.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Strict_Transport_Security_Cheat_Sheet.html"><strong>HTTP Strict Transport Security - OWASP Cheat Sheet Series</strong> -<br/> - -<em>HTTP Strict Transport Security (also named HSTS) is an opt-in security enhancement that is specified by a web…</em>cheatsheetseries.owasp.org</a><a href="https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Strict_Transport_Security_Cheat_Sheet.html" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://www.html5rocks.com/en/tutorials/security/content-security-policy/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://www.html5rocks.com/en/tutorials/security/content-security-policy/"><strong>Content Security Policy | Web Fundamentals | Google Developers</strong> -<br/> - -<em>The web's security model is rooted in the same-origin policy . Code from https://mybank.com should only have access to…</em>www.html5rocks.com</a><a href="https://www.html5rocks.com/en/tutorials/security/content-security-policy/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP"><strong>Content Security Policy (CSP) - HTTP | MDN</strong> -<br/> - -<em>Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks…</em>developer.mozilla.org</a><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://csp-evaluator.withgoogle.com/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://csp-evaluator.withgoogle.com/"><strong>CSP Evaluator</strong> -<br/> - -<em>CSP Evaluator allows developers and security experts to check if a Content Security Policy (CSP) serves as a strong…</em>csp-evaluator.withgoogle.com</a><a href="https://csp-evaluator.withgoogle.com/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -<a href="https://developers.google.com/search/docs/guides/intro-structured-data" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://developers.google.com/search/docs/guides/intro-structured-data"><strong>Understand How Structured Data Works | Google Search Central</strong> -<br/> - -<em>Google Search works hard to understand the content of a page. You can help us by providing explicit clues about the…</em>developers.google.com</a><a href="https://developers.google.com/search/docs/guides/intro-structured-data" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://ogp.me/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://ogp.me/"><strong>Open Graph protocol</strong> -<br/> - -<em>The Open Graph protocol enables any web page to become a rich object in a social graph. For instance, this is used on…</em>ogp.me</a><a href="https://ogp.me/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://developer.twitter.com/en/docs/tweets/optimize-with-cards/overview/abouts-cards" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://developer.twitter.com/en/docs/tweets/optimize-with-cards/overview/abouts-cards"><strong>About Twitter Cards</strong> -<br/> - -<em>With Twitter Cards, you can attach rich photos, videos and media experiences to Tweets, helping to drive traffic to…</em>developer.twitter.com</a><a href="https://developer.twitter.com/en/docs/tweets/optimize-with-cards/overview/abouts-cards" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://developers.facebook.com/docs/sharing/webmasters#markup" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://developers.facebook.com/docs/sharing/webmasters#markup"><strong>Webmasters - Sharing - Documentation - Facebook for Developers</strong> -<br/> - -<em>Most content is shared to Facebook as a URL, so it's important that you mark up your website with Open Graph tags to…</em>developers.facebook.com</a><a href="https://developers.facebook.com/docs/sharing/webmasters#markup" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="http://humanstxt.org/" class="markup--anchor markup--mixtapeEmbed-anchor" title="http://humanstxt.org/"><strong>Humans TXT: We Are People, Not Machines.</strong> -<br/> - -<em>It's an initiative for knowing the people behind a website. It's a TXT file that contains information about the…</em>humanstxt.org</a><a href="http://humanstxt.org/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -### Discover More: - -<a href="https://bgoonz-blog.netlify.app/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://bgoonz-blog.netlify.app/"><strong>Stackbit Web-Dev-HubTheme</strong> -<br/> - -<em>Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…</em>bgoonz-blog.netlify.app</a><a href="https://bgoonz-blog.netlify.app/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [June 24, 2021](https://medium.com/p/9a52e11c8ee1). - -<a href="https://medium.com/@bryanguner/quick-web-developers-website-checklist-a-list-of-tools-for-improvement-9a52e11c8ee1" class="p-canonical">Canonical link</a> - -August 6, 2021. diff --git a/notes/articles/medium/markdown/React-State.md b/notes/articles/medium/markdown/React-State.md deleted file mode 100644 index d8bc6b99bf..0000000000 --- a/notes/articles/medium/markdown/React-State.md +++ /dev/null @@ -1,564 +0,0 @@ -# React State - -Demystified - ---- - -### React State - -#### Demystified - -### Here's a gist containing most of the below react components: - -<a href="https://gist.github.com/bgoonz/216025f38eed1dd451df356e4085fa5a" class="markup--anchor markup--p-anchor">https://gist.github.com/bgoonz/216025f38eed1dd451df356e4085fa5a</a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*IzkDVQXDDiVofRlH.gif" class="graf-image" /></figure>### React Class Components - -**Class Components** - -- <span id="3d48">You can write React components using ES2015 Classes: - **Function Component**</span> - -<a href="https://gist.github.com/bgoonz/8223ee9f84bbc0fe7ad504efb3dc860d" class="markup--anchor markup--p-anchor">https://gist.github.com/bgoonz/8223ee9f84bbc0fe7ad504efb3dc860d</a> - -**ES2015 Version** - - // ./src/Message.js - - import React from "react"; - - class Message extends React.Component { - render() { - return <div>{this.props.text}</div>; - } - } - - export default Message; - -- <span id="59c4">We can access props within a `class component` by using `this.props`</span> -- <span id="5e06">Keep in mind Class Components are used just like function components.</span> - -<!-- --> - - // ./src/index.js - - import React from "react"; - import ReactDOM from "react-dom"; - import Message from "./Message"; - - ReactDOM.render( - <React.StrictMode> - <Message text="Hello world!" /> - </React.StrictMode>, - document.getElementById("root") - ); - -**Setting and accessing props** - - class Message extends React.Component { - constructor(props) { - super(props); - - // TODO Initialize state, etc. - } - - render() { - return <div>{this.props.text}</div>; - } - } - -- <span id="7853">If we define a constructor method in our Class Component, we have to define the `super` method with `props` passed through it.</span> -- <span id="058c">Side Note: Before React used ES2015 Classes, it used `React.createclass` function, if you ever need to use this antiquated method make sure you install a module called `create-react-class`</span> - -**Stateful components** - -- <span id="1ecc">One of the major reasons why you would choose to use a **Class Component** over a Function Component is to add and manage local or internal state to your component.</span> -- <span id="c4cd">Second of the major reasons is to be able to use a Class Component's lifecycle methods.</span> - -**What is state?** - -- <span id="2b2a">Props are data that are provided by the consumer or caller of the component.</span> -- <span id="d150">Not meant to be changed by a component.</span> -- <span id="2316">State is data that is `internal` to the component.</span> -- <span id="cea0">Intended to be updated or mutated.</span> - -**When to use state** - -- <span id="0936">_Only Use State when it is absolutely necessary_</span> -- <span id="2052">If the data never changes, or if it's needed through an entire application use props instead.</span> -- <span id="04ff">State is more often used when creating components that retrieve data from APIs or render forms.</span> -- <span id="5a9f">**The general rule of thumb**: If a component doesn't need to use state or Lifecyle methods, it should be prioritized as a `function component`.</span> -- <span id="412f">Functional:Stateless || Class:Stateful</span> - -**Initializing state** - -- <span id="5783">Use a class constructor method to initialize `this.state` object.</span> - -#### Application Entry Point - - // ./src/index.js - import React from 'react' - import ReactDOM from 'react-dom'; - import RandomQuote from './RandomQuote'; - - ReactDOM.render( - <React.StrictMode> - <RandomQuote /> - </React.StrictMode> - document.getElementById('root'); - ) - -#### Class Component: RandomQuote - - import React from "react"; - - class RandomQuote extends React.Component { - constructor() { - super(); - - const quotes = [ - "May the Force be with you.", - "There's no place like home.", - "I'm the king of the world!", - "My mama always said life was like a box of chocolates.", - "I'll be back.", - ]; - - this.state = { - quotes, - currentQuoteIndex: this.getRandomInt(quotes.length); - } - } - - getRandomInt(max) { - return Math.floor(Math.random() * Math.floor(max)); - } - - render() { - return ( - <div> - <h2>Random Quote</h2> - <p>{this.state.quotes[this.state.currentQuoteIndex]}</p> - </div> - ) - } - } - - export default RandomQuote; - -**Updating State** - -- <span id="e560">Let's say we want to update our state with a new quote.</span> -- <span id="ead5">We can set up event listeners in React similarly to how we did them before.</span> -- <span id="b7c7"><button type="button" onClick={this.changeQuote}> Change Quote </button></span> -- <span id="270b">`onClick` is the event listener.</span> -- <span id="10c4">`{this.changeQuote}` is the event handler method.</span> -- <span id="99e8">Our Class Component File should now look like this with the new additions:</span> - -<!-- --> - - import React from "react"; - - class RandomQuote extends React.Component { - constructor() { - super(); - - const quotes = [ - "May the Force be with you.", - "There's no place like home.", - "I'm the king of the world!", - "My mama always said life was like a box of chocolates.", - "I'll be back.", - ]; - - this.state = { - quotes, - currentQuoteIndex: this.getRandomInt(quotes.length); - } - } - - changeQuote = () => { - const newIndex = this.getRandomInt(this.state.quotes.length); - - // Setting the 'new state' of currentQuoteIndex state property - // to newly generated random index #. - this.setState({ - currentQuoteIndex: newIndex; - }) - } - - getRandomInt(max) { - return Math.floor(Math.random() * Math.floor(max)); - } - - render() { - return ( - <div> - <h2>Random Quote</h2> - <p>{this.state.quotes[this.state.currentQuoteIndex]}</p> - <button type="button" onClick={this.changeQuote}> - Change Quote - </button> - </div> - ) - } - } - - export default RandomQuote; - -**Don't modify state directly** - -- <span id="11e2">It is important to `never` modify your state directly!</span> -- <span id="d085">ALWAYS use `this.setState` method to update state.</span> -- <span id="38f9">This is because when you only use this.state to re-assign, no re-rendering will occur => leaving our component out of sync.</span> - -**Properly updating state from the previous state** - -- <span id="839d">In our current example, the way we have `changeQuote` set up leaves us with occasionally producing the same index twice in a row.</span> -- <span id="6f45">One solution is to design a loop but keep in mind that state updates are handled asynchronously in React (your current value is not guaranteed to be the latest)</span> -- <span id="f71d">A safe method is to pass an anonymous method to `this.setState` (instead of an object literal)</span> - -**Previous** - - changeQuote = () => { - const newIndex = this.getRandomInt(this.state.quotes.length); - - this.setState({ - currentQuoteIndex: newIndex; - }) - } - -**Passing w/ Anon Method** - - changeQuote = () => { - this.setState((state, props) => { - const { quotes, currentQuoteIndex } = state; - - let newIndex = -1; - - do { - newIndex = this.getRandomInt(quote.length); - } while (newIndex === currentQuoteIndex); - - return { - currentQuoteIndex: newIndex, - }; - }); - }; - -**Providing default values for props** - -- <span id="05dd">In our current example, we pass in a static array of predefined quotes in our constructor.</span> -- <span id="29a1">The way it is set up right now leaves our list of quotes unchanged after initialization.</span> -- <span id="733b">We can make quotes more dynamic by replacing our static array with a `props` argument passed into `super`.</span> -- <span id="8d26">constructor(props) { super(props); }</span> -- <span id="e22e">We can now move our quotes array to our application entry point and pass it in as a prop.</span> - -#### Application Entry Point - - // ./src/index.js - import React from 'react' - import ReactDOM from 'react-dom'; - import RandomQuote from './RandomQuote'; - - // Re-assign our array here and pass it in as a prop in Render. - const quotes = [ - "May the Force be with you.", - "There's no place like home.", - "I'm the king of the world!", - "My mama always said life was like a box of chocolates.", - "I'll be back.", - "This way I can define more quotes", - ]; - - ReactDOM.render( - <React.StrictMode> - <RandomQuote quotes={quotes}/> - </React.StrictMode> - document.getElementById('root'); - ) - -- <span id="c3f2">One thing to note about this workaround is that the caller of the component _must_ set the quotes prop or the component will throw an error => so use `defaultProps`!</span> - -<!-- --> - - // At the bottom of RandomQuote.js... - RandomQuote.defaultProps = { - quotes: [ - "May the Force be with you.", - "There's no place like home.", - "I'm the king of the world!", - "My mama always said life was like a box of chocolates.", - "I'll be back.", - "This way I can define more quotes", - ], - }; - -- <span id="8909">A good safety net in case the consumer/caller doesn't provide a value for the quotes array.</span> -- <span id="a254">We can even remove it from our index.js now and an error will not be thrown.</span> - -### Handling Events - -- <span id="46a0">To add an event listener to an element, just define a method to handle the event and associate that method with the element event you are listening for. - **Example**</span> - -<!-- --> - - import React from "react"; - - class AlertButton extends React.Component { - showAlert = () => { - window.alert("Button Clicked!"); - }; - - render() { - return ( - <button type="button" onClick={this.showAlert}> - Submit - </button> - ); - } - } - -- <span id="c8ad">Note that when referring the handler method in onClick we're not invoking showAlert simply just passing a reference.</span> - -**Preventing default behavior** - -- <span id="0497">HTML Elements in the browser often have a lot of default behavior.</span> -- <span id="c546">I.E. Clicking on an `<a>` element navigates so a resource denoted by `<href>` property.</span> -- <span id="7f13">Here is an example of where using `e.preventDefault()` could come in handy.</span> - -<!-- --> - - import React from "react"; - - class NoDefaultSubmitForm extends React.Component { - submitForm = (e) => { - e.preventDefault(); - window.alert("Handling form submission..."); - }; - - render() { - return ( - <form onSubmit={this.submitForm}> - <button>Submit</button> - </form>; - )} - } - -- <span id="6df2">The button contained within the form will end up refreshing the page before `this.submitForm` method can be completed.</span> -- <span id="e214">We can stick an `e.preventDefault()` into the actual method to get around this problem.</span> -- <span id="bafc">`e` : Parameter that references a `Synthetic Event` object type.</span> - -**Using** `this` **in event handlers** - - // ./src/AlertButton.js - - import React from "react"; - - class AlertButton extends React.Component { - showAlert = () => { - window.alert("Button clicked!"); - console.log(this); - }; - - render() { - return ( - <button type="button" onClick={this.showAlert}> - Click Me - </button> - ); - } - } - - export default AlertButton; - -- <span id="159a">When we console log `this` we see the AlertButton object.</span> -- <span id="9158">If we were to write the showAlert method with a regular class method like:</span> - -<!-- --> - - showAlert() { - console.log(this); - } - -- <span id="13af">We would get `undefined` => remember that fat arrow binds to the current context!</span> - -**Reviewing class methods and the** `this` **keyword** - -> Binding: - - class Girlfriend { - constructor() { - this.name = "JavaScript"; - } - - displayName() { - console.log(this.name); - } - } - - const Ming = new Girlfriend(); - Ming.displayName(); // => Javascript - - const displayAgain = Ming.displayName; - displayAgain(); // => Result in a Type Error: Cannot read property 'name' of undefined. - -- <span id="f44c">The first time we use our `displayMethod` call, it is called directly on the instance of the boyfriend class, which is why `Javascript` was printed out.</span> -- <span id="5ab3">The second time it was called, the ref of the method is stored as a variable and method is called on that variable instead of the instance; resulting in a type error (it has lost it's context)</span> -- <span id="f151">Remember we can use the `bind` method to rebind context!</span> -- <span id="a90b">We can refactor to get the second call working like this:</span> - -<!-- --> - - const displayAgain = Ming.displayName.bind(Ming); displayAgain(); => //Now Javascript will be printed out. - -- <span id="9b5c">To continue using function declarations vs fat arrow we can assign context in a constructor within a class component.</span> - -<!-- --> - - import React from "react"; - - class AlertButton extends React.Component { - constructor() { - super(); - this.showAlert = this.showAlert.bind(this); // binding context - } - - showAlert() { - console.log(this); - } - - render() { - return ( - <button type="button" onClick={this.showAlert}> - Submit - </button> - ); - } - } - - export default AlertButton; - -- <span id="e397">`Experimental Syntax` : Syntax that has been proposed to add to ECMAScript but hasn't officially been added to the language specification yet.</span> -- <span id="eb35">It's good to pick one approach and use it consistently, either:</span> - -1. <span id="e7c9">Class Properties & Arrow Functions</span> -2. <span id="f447">Bind Method & This Keyword</span> - -**The** `SyntheticEvent` **object** - -- <span id="d26e">**Synthetic Event Objects**: Cross Browser wrappers around the browser's native event.</span> -- <span id="7319">Includes the use of stopPropagation() and preventDefault();</span> -- <span id="1d15">Attributes of the Synthetic Event Object:</span> - -<figure><img src="https://cdn-images-1.medium.com/max/800/1*OVA083oP8HKuRPyA-Ebpig.png" alt="Attributesboolean bubblesboolean cancelableDOMEventTarget currentTargetboolean defaultPreventednumber eventPhaseboolean isTrustedDOMEvent nativeEventvoid preventDefault()boolean isDefaultPrevented()void stopPropagation()boolean isPropagationStopped()void persist()DOMEventTarget targetnumber timeStampstring type" class="graf-image" /><figcaption>Attributesboolean bubblesboolean cancelableDOMEventTarget currentTargetboolean defaultPreventednumber eventPhaseboolean isTrustedDOMEvent nativeEventvoid preventDefault()boolean isDefaultPrevented()void stopPropagation()boolean isPropagationStopped()void persist()DOMEventTarget targetnumber timeStampstring type</figcaption></figure>- <span id="42b5">`nativeEvent` : property defined in a synthetic event object that gives you access to the underlying native browser event (rarely used!)</span> - -### Forms in React - -_Exercise being done in a separate file_ - -**Random Notes** - -- <span id="f551">`onChange` : detects when a value of an input element changes.</span> -- <span id="a180">Assigning `onChange` to our input fields makes our component's state update in real time during user input.</span> -- <span id="6814">Don't forget to add `preventDefault` onto form submissions to deal with the default behavior of the browser refreshing the page!</span> -- <span id="830f">`submittedOn: new Date(),` Can be added to a form, most likely will persist into a DB.</span> - -#### **Controlled Components** - -- <span id="2228">We use the `onChange` event handlers on form fields to keep our component's state as the `"one source of truth"`</span> -- <span id="44e7">Adding an `onChange` event handler to every single input can massively bloat your code.</span> -- <span id="056c">Try assigning it to it's own method to apply everywhere.</span> -- <span id="9137">`textarea` is handled differently in react: it takes in a value property to handle what the inner text will be.</span> - -<!-- --> - -- <span id="39ee">We can use validation libraries like `validate` to make our validation functions more complex.</span> - -<!-- --> - - import isEmail from "validator/es/lib/isEmail"; - - validate(name, email) { - const validationErrors = []; - - if (!name) { - validationErrors.push("Please provide a Name"); - } - - if (!email) { - validationErrors.push("Please provide an Email"); - } else if (!isEmail(email)) { - validationErrors.push("Please provide a valid Email"); - } - - return validationErrors; - } - -**Note About Client-side vs server-side validation** - -- <span id="588f">Server-side validation is not optional.</span> -- <span id="e35c">Tech-savvy users can manipulate client-side validations.</span> -- <span id="03da">Sometimes the 'best approach' is to skip implementing validations on the client-side and rely completely on the server-side validation.</span> - -### Component Lifecycle - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*6kzLSSpEJ8ypPSCM.png" class="graf-image" /></figure>- <span id="6e9c">Component Lifecycle is simply a way of describing the key moments in the lifetime of a component.</span> - -1. <span id="5e9c">Loading (Mounting)</span> -2. <span id="6930">Updating</span> -3. <span id="1ec1">Unloading (Unmounting)</span> - -**The lifecycle of a React component** - -- <span id="b8ed">Each `Class Component` has several `lifecycle methods` that you can add to run code at specific times.</span> -- <span id="f58a">`componentDidMount` : Method called after your component has been added to the component tree.</span> -- <span id="adb3">`componentDidUpdate` : Method called after your component has been updated.</span> -- <span id="d198">`componentWillUnmount` : Method called just before your component is removed from the component tree.</span> - -#### `Mounting` - -1. <span id="4ebf">`constructor` method is called</span> -2. <span id="59d0">`render` method is called</span> -3. <span id="7557">React updates the `DOM`</span> -4. <span id="6049">`componentDidMount` is called</span> - -#### `Updating` - -- <span id="5493">When component receives new `props`</span> - -1. <span id="3eb5">`render` method is called</span> -2. <span id="3c59">React updates the `DOM`</span> -3. <span id="e4de">`componentDidUpdate` is called</span> - -<span class="graf-dropCap">W</span>hen `setState` is called: - -1. <span id="6782">`render` method is called</span> -2. <span id="7d8c">React updates the `DOM`</span> -3. <span id="74b7">`componentDidUpdate` is called</span> - -#### `Unmounting` - -- <span id="3885">The moment before a class component is removed from the component tree:</span> -- <span id="b1e8">`componentDidMount` will be called.</span> - -**Avoiding the legacy lifecycle methods** - -- <span id="732f">Occasionally you will encounter some deprecated lifecycle methods:</span> -- <span id="fb04">UNSAFE_componentWillMount</span> -- <span id="5f6e">UNSAFE_componentWillReceiveProps</span> -- <span id="b7aa">UNSAFE_componentWillUpdate</span> -- <span id="6277">Just know they will be removed soon from React's API…☮️</span> - ---- - -### React Docs: - -<a href="https://gist.github.com/bgoonz/690d80b4f8ac5d359274d98cae87366a" class="markup--anchor markup--p-anchor">https://gist.github.com/bgoonz/216025f38eed1dd451df356e4085fa5a</a> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [August 22, 2021](https://medium.com/p/d8e0fc340714). - -<a href="https://medium.com/@bryanguner/react-state-d8e0fc340714" class="p-canonical">Canonical link</a> - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Regular-Expressions.md b/notes/articles/medium/markdown/Regular-Expressions.md deleted file mode 100644 index b85355bc6e..0000000000 --- a/notes/articles/medium/markdown/Regular-Expressions.md +++ /dev/null @@ -1,349 +0,0 @@ -# Regular Expressions - -description: - ---- - -#### <a href="http://medium.com/codex" class="markup--anchor markup--h4-anchor">CODEX</a> - -### Regular Expressions - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*VdDVM2Nzv6oGC5I0.png" class="graf-image" /></figure><figure><img src="https://cdn-images-1.medium.com/max/800/1*D83R_a0SSgMR0hI4jP6Asw.png" class="graf-image" /></figure><figure><img src="https://cdn-images-1.medium.com/max/800/1*vk5n412Bs-dx6UdgyUywdg.png" class="graf-image" /></figure>### description: - -_Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the_ `exec()` _and_ `test()` _methods of_ `RegExp`_, and with the_ `match()`_,_ `matchAll()`_,_ `replace()`_,_ `replaceAll()`_,_ `search()`_, and_ `split()` _methods of_ `String`_. This chapter describes JavaScript regular expressions._ - -### Creating a regular expression - -You construct a regular expression in one of two ways: - -1. <span id="8a7f">**Using a regular expression literal, which consists of a pattern enclosed between slashes, as follows:**</span> - -`let re = /ab+c/;` - -- <span id="f4e2">Regular expression literals provide compilation of the regular expression when the script is loaded. If the regular expression remains constant, using this can improve performance.</span> - -**2. Or calling the constructor function of the** `RegExp` **object, as follows:** - -- <span id="2016">`let re = new RegExp('ab+c');`</span> - -> _Using the constructor function provides runtime compilation of the regular expression_. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input. - -### Writing a regular expression pattern - -A regular expression pattern is composed of simple characters, such as `/abc/`, or a combination of simple and special characters, such as `/ab*c/` or `/Chapter (\d+)\.\d*/`. - -The last example includes **parentheses, which are used as a memory device**. _The match made with this part of the pattern is remembered for later use._ - -### Using simple patterns - -Simple patterns are constructed of characters for which you want to find a direct match. - -For example, the pattern `/abc/` matches character combinations in strings only when the exact sequence `"abc"` occurs (all characters together and in that order). - -Such a match would succeed in the strings `"Hi, do you know your abc's?"` and `"The latest airplane designs evolved from slabcraft."` - -In both cases the match is with the substring `"abc"`. - -There is no match in the string `"Grab crab"` because while it contains the substring `"ab c"`, it does not contain the exact substring `"abc"`. - -### Using special characters - -When the search for a match requires something more than a direct match, such as finding one or more b's, or finding white space, you can include special characters in the pattern. - -For example, to match _a single_ `"a"` _followed by zero or more_ `"b"`_s followed by_ `"c"`, you'd use the pattern `/ab*c/`: - -> the `*` after `"b"` means "0 or more occurrences of the preceding item." In the string `"cbbabbbbcdebc"`, this pattern will match the substring `"abbbbc"`. - -<a href="https://github.com/bgoonz/Cheat-Sheets/blob/master/Regular_Expressions/Assertions.html" class="markup--anchor markup--p-anchor"><strong>Assertions</strong></a>** : Assertions include boundaries, which indicate the beginnings and endings of lines and words, and other patterns indicating in some way that a match is possible (including look-ahead, look-behind, and conditional expressions).** - -<a href="https://github.com/bgoonz/Cheat-Sheets/blob/master/Regular_Expressions/Character_Classes.html" class="markup--anchor markup--p-anchor"><strong>Character classes</strong></a>** : Distinguish different types of characters. For example, distinguishing between letters and digits.** - -<a href="https://github.com/bgoonz/Cheat-Sheets/blob/master/Regular_Expressions/Groups_and_Ranges.html" class="markup--anchor markup--p-anchor"><strong>Groups and ranges</strong></a>** : Indicate groups and ranges of expression characters.** - -<a href="https://github.com/bgoonz/Cheat-Sheets/blob/master/Regular_Expressions/Quantifiers.html" class="markup--anchor markup--p-anchor"><strong>Quantifiers</strong></a>** : Indicate numbers of characters or expressions to match.** - -<a href="https://github.com/bgoonz/Cheat-Sheets/blob/master/Regular_Expressions/Unicode_Property_Escapes.html" class="markup--anchor markup--p-anchor"><strong>Unicode property escapes</strong></a>** : Distinguish based on unicode character properties, for example, upper- and lower-case letters, math symbols, and punctuation.** - -If you want to look at all the special characters that can be used in regular expressions in a single table, see the following: - -<figure><img src="https://cdn-images-1.medium.com/max/800/1*Wk5zFr1IHJxacq2a2zi5RQ.png" class="graf-image" /></figure>### Special characters in regular expressions. - -### Escaping - -If you need to use any of the special characters literally (actually searching for a `"*"`, for instance), you must escape it by putting a **backslash** in front of it. - -For instance, to search for `"a"` followed by `"*"` followed by `"b"`, - -> you'd use `/a\*b/` --- the backslash "escapes" the `"*"`, making it literal instead of special. - -Similarly, if you're writing a regular expression literal and need to match a slash ("/"), you need to escape that (otherwise, it terminates the pattern) - -For instance, to search for the string "/example/" followed by one or more alphabetic characters, you'd use `/\/example\/[a-z]+/i` - -**--the backslashes before each slash make them literal.** - -To match a literal backslash, you need to escape the backslash. - -For instance, to match the string "C:\\" where "C" can be any letter, - -you'd use `/[A-Z]:\\/` - ---- the first backslash escapes the one after it, so the expression searches for a single literal backslash. - -If using the `RegExp` constructor with a string literal, **remember that the backslash is an escape in string literals, so to use it in the regular expression, you need to escape it at the string literal level**. - -`/a\*b/` and `new RegExp("a\\*b")` create the same expression, - -which searches for "a" followed by a literal "\*" followed by "b". - -If escape strings are not already part of your pattern you can add them using `String.replace`: - - function escapeRegExp(string) { - return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string - } - -**The "g" after the regular expression is an option or flag that performs a global search, looking in the whole string and returning all matches.** - -### Using parentheses - -Parentheses around any part of the regular expression pattern causes that part of the matched substring to be remembered. - -Once remembered, the substring can be recalled for other use. - -### Using regular expressions in JavaScript - -Regular expressions are used with the `RegExp` **methods** - -`test()` **and** `exec()` - -and with the `String` **methods** `match()`**,** `replace()`**,** `search()`**, and** `split()`**.** - ---- - -### Method Descriptions - -#### `exec()` - -Executes a search for a match in a string. - -It returns an array of information or `null` on a mismatch. - -#### `test()` - -Tests for a match in a string. - -It returns `true` or `false`. - -#### `match()` - -Returns an array containing all of the matches, including capturing groups, or `null` if no match is found. - -#### `matchAll()` - -Returns an iterator containing all of the matches, including capturing groups. - -#### `search()` - -Tests for a match in a string. - -It returns the index of the match, or `-1` if the search fails. - -#### `replace()` - -Executes a search for a match in a string, and replaces the matched substring with a replacement substring. - -#### `replaceAll()` - -Executes a search for all matches in a string, and replaces the matched substrings with a replacement substring. - -#### `split()` - -Uses a regular expression or a fixed string to break a string into an array of substrings. - -### Methods that use regular expressions - -When you want to know whether a pattern is found in a string, use the `test()` or `search()` methods; - -for more information (but slower execution) use the `exec()` or `match()` methods. - -If you use `exec()` or `match()` and if the match succeeds, these methods return an array and update properties of the associated regular expression object and also of the predefined regular expression object, `RegExp`. - -If the **match fails, the** `exec()` **method returns** `null` (which coerces to `false`). - -In the following example, the script uses the `exec()` method to find a match in a string. - - let myRe = /d(b+)d/g; - let myArray = myRe.exec('cdbbdbsbz'); - -If you do not need to access the properties of the regular expression, an alternative way of creating `myArray` is with this script: - - let myArray = /d(b+)d/g.exec('cdbbdbsbz'); - // similar to "cdbbdbsbz".match(/d(b+)d/g); however, - // "cdbbdbsbz".match(/d(b+)d/g) outputs Array [ "dbbd" ], while - // /d(b+)d/g.exec('cdbbdbsbz') outputs Array [ 'dbbd', 'bb', index: 1, input: 'cdbbdbsbz' ]. - -(See <a href="https://github.com/bgoonz/Cheat-Sheets/blob/master/Regular_Expressions.md#g-different-behaviors" class="markup--anchor markup--p-anchor">different behaviors</a> for further info about the different behaviors.) - -If you want to construct the regular expression from a string, yet another alternative is this script: - - let myRe = new RegExp('d(b+)d', 'g'); - let myArray = myRe.exec('cdbbdbsbz'); - -With these scripts, the match succeeds and returns the array and updates the properties shown in the following table. - -Results of regular expression execution. - -You can use a regular expression created with an object initializer without assigning it to a letiable. - -If you do, however, every occurrence is a new regular expression. - -For this reason, if you use this form without assigning it to a letiable, you cannot subsequently access the properties of that regular expression. - -For example, assume you have this script: - - let myRe = /d(b+)d/g; - let myArray = myRe.exec('cdbbdbsbz'); - console.log('The value of lastIndex is ' + myRe.lastIndex); - - // "The value of lastIndex is 5" - -However, if you have this script: - - let myArray = /d(b+)d/g.exec('cdbbdbsbz'); - console.log('The value of lastIndex is ' + /d(b+)d/g.lastIndex); - - // "The value of lastIndex is 0" - -The occurrences of `/d(b+)d/g` in the two statements are different regular expression objects and hence have different values for their `lastIndex` property. - -If you need to access the properties of a regular expression created with an object initializer, you should first assign it to a variable. - -### \[Advanced searching with flags\] - -Regular expressions have **six optional flags** that allow for functionality like global and case insensitive searching. - -These flags can be used separately or together in any order, and are included as part of the regular expression. - -Flag Description Corresponding property - ---- - -`g` Global search. `RegExp.prototype.global` - -`i` Case-insensitive search. `RegExp.prototype.ignoreCase` - -`m` Multi-line search. `RegExp.prototype.multiline` - -`s` Allows `.` to match newline characters. `RegExp.prototype.dotAll` - -`u` "unicode"; treat a pattern as a sequence of unicode code points. `RegExp.prototype.unicode` - -`y` Perform a "sticky" search that matches starting at the current position in the target string. `RegExp.prototype.sticky` - -#### Regular expression flags - -_To include a flag with the regular expression, use this syntax:_ - - let re = /pattern/flags; - -or - - let re = new RegExp('pattern', 'flags'); - -Note that the flags are an integral part of a regular expression. They cannot be added or removed later. - -For example, `re = /\w+\s/g` creates a regular expression that looks for one or more characters followed by a space, and it looks for this combination throughout the string. - - let re = /\w+\s/g; - let str = 'fee fi fo fum'; - let myArray = str.match(re); - console.log(myArray); - - // ["fee ", "fi ", "fo "] - -You could replace the line: - - let re = /\w+\s/g; - -with: - - let re = new RegExp('\\w+\\s', 'g'); - -and get the same result. - -The behavior associated with the `g` flag is different when the `.exec()` method is used. - -The roles of "class" and "argument" get reversed: - -In the case of `.match()`, the string class (or data type) owns the method and the regular expression is just an argument, - -while in the case of `.exec()`, it is the regular expression that owns the method, with the string being the argument. - -Contrast this `str.match(re)` versus `re.exec(str)`. - -The `g` flag is used with the `.exec()` method to get iterative progression. - - let xArray; while(xArray = re.exec(str)) console.log(xArray); - // produces: - // ["fee ", index: 0, input: "fee fi fo fum"] - // ["fi ", index: 4, input: "fee fi fo fum"] - // ["fo ", index: 7, input: "fee fi fo fum"] - -The `m` flag is used to specify that a multiline input string should be treated as multiple lines. - -If the `m` flag is used, `^` and `$` match at the start or end of any line within the input string instead of the start or end of the entire string. - -### Using special characters to verify input - -In the following example, the user is expected to enter a phone number. When the user presses the "Check" button, the script checks the validity of the number. If the number is valid (matches the character sequence specified by the regular expression), the script shows a message thanking the user and confirming the number. If the number is invalid, the script informs the user that the phone number is not valid. - -Within non-capturing parentheses `(?:` , the regular expression looks for three numeric characters `\d{3}` OR `|` a left parenthesis `\(` followed by three digits` \d{3}`, followed by a close parenthesis `\)`, (end non-capturing parenthesis `)`), followed by one dash, forward slash, or decimal point and when found, remember the character `([-\/\.])`, followed by three digits `\d{3}`, followed by the remembered match of a dash, forward slash, or decimal point `\1`, followed by four digits `\d{4}`. - -The `Change` event activated when the user presses Enter sets the value of `RegExp.input`. - -#### HTML - - <p> - Enter your phone number (with area code) and then click "Check". - <br> - The expected format is like ###-###-####. - </p> - <form action="#"> - <input id="phone"> - <button onclick="testInfo(document.getElementById('phone'));">Check</button> - </form> - -#### JavaScript - - let re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/; - function testInfo(phoneInput) { - let OK = re.exec(phoneInput.value); - if (!OK) { - console.error(phoneInput.value + ' isn\'t a phone number with area code!'); - } else { - console.log('Thanks, your phone number is ' + OK[0]);} - } - -### Cheat Sheet - -<figure><img src="https://cdn-images-1.medium.com/max/800/1*VmpGy_BYCekOncdyrgSrxw.png" class="graf-image" /></figure>#### If you found this guide helpful feel free to checkout my GitHub/gist's where I host similar content: - -> <a href="https://gist.github.com/bgoonz" class="markup--anchor markup--blockquote-anchor"><strong>bgoonz's</strong> gists · GitHub</a> - -<a href="https://github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://github.com/bgoonz"><strong>bgoonz — Overview</strong> -<br/> - -<em>Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…</em>github.com</a><a href="https://github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -Or Checkout my personal Resource Site: - -<a href="https://goofy-euclid-1cd736.netlify.app/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://goofy-euclid-1cd736.netlify.app/"><strong>a/A-Student-Resources</strong> -<br/> - -<em>Edit description</em>goofy-euclid-1cd736.netlify.app</a><a href="https://goofy-euclid-1cd736.netlify.app/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [March 6, 2021](https://medium.com/p/4d8fb3eb146b). - -<a href="https://medium.com/@bryanguner/regular-expressions-4d8fb3eb146b" class="p-canonical">Canonical link</a> - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Regular.md b/notes/articles/medium/markdown/Regular.md deleted file mode 100644 index 6d3f028b99..0000000000 --- a/notes/articles/medium/markdown/Regular.md +++ /dev/null @@ -1,349 +0,0 @@ -# Regular Expressions - -description: - ---- - -#### <a href="http://medium.com/codex" class="markup--anchor markup--h4-anchor">CODEX</a> - -### Regular Expressions - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*VdDVM2Nzv6oGC5I0.png" class="graf-image" /></figure><figure><img src="https://cdn-images-1.medium.com/max/800/1*D83R_a0SSgMR0hI4jP6Asw.png" class="graf-image" /></figure><figure><img src="https://cdn-images-1.medium.com/max/800/1*vk5n412Bs-dx6UdgyUywdg.png" class="graf-image" /></figure>### description: - -_Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the_ `exec()` _and_ `test()` _methods of_ `RegExp`_, and with the_ `match()`_,_ `matchAll()`_,_ `replace()`_,_ `replaceAll()`_,_ `search()`_, and_ `split()` _methods of_ `String`_. This chapter describes JavaScript regular expressions._ - -### Creating a regular expression - -You construct a regular expression in one of two ways: - -1. <span id="8a7f">**Using a regular expression literal, which consists of a pattern enclosed between slashes, as follows:**</span> - -`let re = /ab+c/;` - -- <span id="f4e2">Regular expression literals provide compilation of the regular expression when the script is loaded. If the regular expression remains constant, using this can improve performance.</span> - -**2. Or calling the constructor function of the** `RegExp` **object, as follows:** - -- <span id="2016">`let re = new RegExp('ab+c');`</span> - -> _Using the constructor function provides runtime compilation of the regular expression_. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input. - -### Writing a regular expression pattern - -A regular expression pattern is composed of simple characters, such as `/abc/`, or a combination of simple and special characters, such as `/ab*c/` or `/Chapter (\d+)\.\d*/`. - -The last example includes **parentheses, which are used as a memory device**. _The match made with this part of the pattern is remembered for later use._ - -### Using simple patterns - -Simple patterns are constructed of characters for which you want to find a direct match. - -For example, the pattern `/abc/` matches character combinations in strings only when the exact sequence `"abc"` occurs (all characters together and in that order). - -Such a match would succeed in the strings `"Hi, do you know your abc's?"` and `"The latest airplane designs evolved from slabcraft."` - -In both cases the match is with the substring `"abc"`. - -There is no match in the string `"Grab crab"` because while it contains the substring `"ab c"`, it does not contain the exact substring `"abc"`. - -### Using special characters - -When the search for a match requires something more than a direct match, such as finding one or more b's, or finding white space, you can include special characters in the pattern. - -For example, to match _a single_ `"a"` _followed by zero or more_ `"b"`_s followed by_ `"c"`, you'd use the pattern `/ab*c/`: - -> the `*` after `"b"` means "0 or more occurrences of the preceding item." In the string `"cbbabbbbcdebc"`, this pattern will match the substring `"abbbbc"`. - -<a href="https://github.com/bgoonz/Cheat-Sheets/blob/master/Regular_Expressions/Assertions.html" class="markup--anchor markup--p-anchor"><strong>Assertions</strong></a>** : Assertions include boundaries, which indicate the beginnings and endings of lines and words, and other patterns indicating in some way that a match is possible (including look-ahead, look-behind, and conditional expressions).** - -<a href="https://github.com/bgoonz/Cheat-Sheets/blob/master/Regular_Expressions/Character_Classes.html" class="markup--anchor markup--p-anchor"><strong>Character classes</strong></a>** : Distinguish different types of characters. For example, distinguishing between letters and digits.** - -<a href="https://github.com/bgoonz/Cheat-Sheets/blob/master/Regular_Expressions/Groups_and_Ranges.html" class="markup--anchor markup--p-anchor"><strong>Groups and ranges</strong></a>** : Indicate groups and ranges of expression characters.** - -<a href="https://github.com/bgoonz/Cheat-Sheets/blob/master/Regular_Expressions/Quantifiers.html" class="markup--anchor markup--p-anchor"><strong>Quantifiers</strong></a>** : Indicate numbers of characters or expressions to match.** - -<a href="https://github.com/bgoonz/Cheat-Sheets/blob/master/Regular_Expressions/Unicode_Property_Escapes.html" class="markup--anchor markup--p-anchor"><strong>Unicode property escapes</strong></a>** : Distinguish based on unicode character properties, for example, upper- and lower-case letters, math symbols, and punctuation.** - -If you want to look at all the special characters that can be used in regular expressions in a single table, see the following: - -<figure><img src="https://cdn-images-1.medium.com/max/800/1*Wk5zFr1IHJxacq2a2zi5RQ.png" class="graf-image" /></figure>### Special characters in regular expressions. - -### Escaping - -If you need to use any of the special characters literally (actually searching for a `"*"`, for instance), you must escape it by putting a **backslash** in front of it. - -For instance, to search for `"a"` followed by `"*"` followed by `"b"`, - -> you'd use `/a\*b/` --- the backslash "escapes" the `"*"`, making it literal instead of special. - -Similarly, if you're writing a regular expression literal and need to match a slash ("/"), you need to escape that (otherwise, it terminates the pattern) - -For instance, to search for the string "/example/" followed by one or more alphabetic characters, you'd use `/\/example\/[a-z]+/i` - -**--the backslashes before each slash make them literal.** - -To match a literal backslash, you need to escape the backslash. - -For instance, to match the string "C:\\" where "C" can be any letter, - -you'd use `/[A-Z]:\\/` - ---- the first backslash escapes the one after it, so the expression searches for a single literal backslash. - -If using the `RegExp` constructor with a string literal, **remember that the backslash is an escape in string literals, so to use it in the regular expression, you need to escape it at the string literal level**. - -`/a\*b/` and `new RegExp("a\\*b")` create the same expression, - -which searches for "a" followed by a literal "\*" followed by "b". - -If escape strings are not already part of your pattern you can add them using `String.replace`: - - function escapeRegExp(string) { - return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string - } - -**The "g" after the regular expression is an option or flag that performs a global search, looking in the whole string and returning all matches.** - -### Using parentheses - -Parentheses around any part of the regular expression pattern causes that part of the matched substring to be remembered. - -Once remembered, the substring can be recalled for other use. - -### Using regular expressions in JavaScript - -Regular expressions are used with the `RegExp` **methods** - -`test()` **and** `exec()` - -and with the `String` **methods** `match()`**,** `replace()`**,** `search()`**, and** `split()`**.** - ---- - -### Method Descriptions - -#### `exec()` - -Executes a search for a match in a string. - -It returns an array of information or `null` on a mismatch. - -#### `test()` - -Tests for a match in a string. - -It returns `true` or `false`. - -#### `match()` - -Returns an array containing all of the matches, including capturing groups, or `null` if no match is found. - -#### `matchAll()` - -Returns an iterator containing all of the matches, including capturing groups. - -#### `search()` - -Tests for a match in a string. - -It returns the index of the match, or `-1` if the search fails. - -#### `replace()` - -Executes a search for a match in a string, and replaces the matched substring with a replacement substring. - -#### `replaceAll()` - -Executes a search for all matches in a string, and replaces the matched substrings with a replacement substring. - -#### `split()` - -Uses a regular expression or a fixed string to break a string into an array of substrings. - -### Methods that use regular expressions - -When you want to know whether a pattern is found in a string, use the `test()` or `search()` methods; - -for more information (but slower execution) use the `exec()` or `match()` methods. - -If you use `exec()` or `match()` and if the match succeeds, these methods return an array and update properties of the associated regular expression object and also of the predefined regular expression object, `RegExp`. - -If the **match fails, the** `exec()` **method returns** `null` (which coerces to `false`). - -In the following example, the script uses the `exec()` method to find a match in a string. - - let myRe = /d(b+)d/g; - let myArray = myRe.exec('cdbbdbsbz'); - -If you do not need to access the properties of the regular expression, an alternative way of creating `myArray` is with this script: - - let myArray = /d(b+)d/g.exec('cdbbdbsbz'); - // similar to "cdbbdbsbz".match(/d(b+)d/g); however, - // "cdbbdbsbz".match(/d(b+)d/g) outputs Array [ "dbbd" ], while - // /d(b+)d/g.exec('cdbbdbsbz') outputs Array [ 'dbbd', 'bb', index: 1, input: 'cdbbdbsbz' ]. - -(See <a href="https://github.com/bgoonz/Cheat-Sheets/blob/master/Regular_Expressions.md#g-different-behaviors" class="markup--anchor markup--p-anchor">different behaviors</a> for further info about the different behaviors.) - -If you want to construct the regular expression from a string, yet another alternative is this script: - - let myRe = new RegExp('d(b+)d', 'g'); - let myArray = myRe.exec('cdbbdbsbz'); - -With these scripts, the match succeeds and returns the array and updates the properties shown in the following table. - -Results of regular expression execution. - -You can use a regular expression created with an object initializer without assigning it to a letiable. - -If you do, however, every occurrence is a new regular expression. - -For this reason, if you use this form without assigning it to a letiable, you cannot subsequently access the properties of that regular expression. - -For example, assume you have this script: - - let myRe = /d(b+)d/g; - let myArray = myRe.exec('cdbbdbsbz'); - console.log('The value of lastIndex is ' + myRe.lastIndex); - - // "The value of lastIndex is 5" - -However, if you have this script: - - let myArray = /d(b+)d/g.exec('cdbbdbsbz'); - console.log('The value of lastIndex is ' + /d(b+)d/g.lastIndex); - - // "The value of lastIndex is 0" - -The occurrences of `/d(b+)d/g` in the two statements are different regular expression objects and hence have different values for their `lastIndex` property. - -If you need to access the properties of a regular expression created with an object initializer, you should first assign it to a variable. - -### \[Advanced searching with flags\] - -Regular expressions have **six optional flags** that allow for functionality like global and case insensitive searching. - -These flags can be used separately or together in any order, and are included as part of the regular expression. - -Flag Description Corresponding property - ---- - -`g` Global search. `RegExp.prototype.global` - -`i` Case-insensitive search. `RegExp.prototype.ignoreCase` - -`m` Multi-line search. `RegExp.prototype.multiline` - -`s` Allows `.` to match newline characters. `RegExp.prototype.dotAll` - -`u` "unicode"; treat a pattern as a sequence of unicode code points. `RegExp.prototype.unicode` - -`y` Perform a "sticky" search that matches starting at the current position in the target string. `RegExp.prototype.sticky` - -#### Regular expression flags - -_To include a flag with the regular expression, use this syntax:_ - - let re = /pattern/flags; - -or - - let re = new RegExp('pattern', 'flags'); - -Note that the flags are an integral part of a regular expression. They cannot be added or removed later. - -For example, `re = /\w+\s/g` creates a regular expression that looks for one or more characters followed by a space, and it looks for this combination throughout the string. - - let re = /\w+\s/g; - let str = 'fee fi fo fum'; - let myArray = str.match(re); - console.log(myArray); - - // ["fee ", "fi ", "fo "] - -You could replace the line: - - let re = /\w+\s/g; - -with: - - let re = new RegExp('\\w+\\s', 'g'); - -and get the same result. - -The behavior associated with the `g` flag is different when the `.exec()` method is used. - -The roles of "class" and "argument" get reversed: - -In the case of `.match()`, the string class (or data type) owns the method and the regular expression is just an argument, - -while in the case of `.exec()`, it is the regular expression that owns the method, with the string being the argument. - -Contrast this `str.match(re)` versus `re.exec(str)`. - -The `g` flag is used with the `.exec()` method to get iterative progression. - - let xArray; while(xArray = re.exec(str)) console.log(xArray); - // produces: - // ["fee ", index: 0, input: "fee fi fo fum"] - // ["fi ", index: 4, input: "fee fi fo fum"] - // ["fo ", index: 7, input: "fee fi fo fum"] - -The `m` flag is used to specify that a multiline input string should be treated as multiple lines. - -If the `m` flag is used, `^` and `$` match at the start or end of any line within the input string instead of the start or end of the entire string. - -### Using special characters to verify input - -In the following example, the user is expected to enter a phone number. When the user presses the "Check" button, the script checks the validity of the number. If the number is valid (matches the character sequence specified by the regular expression), the script shows a message thanking the user and confirming the number. If the number is invalid, the script informs the user that the phone number is not valid. - -Within non-capturing parentheses `(?:` , the regular expression looks for three numeric characters `\d{3}` OR `|` a left parenthesis `\(` followed by three digits` \d{3}`, followed by a close parenthesis `\)`, (end non-capturing parenthesis `)`), followed by one dash, forward slash, or decimal point and when found, remember the character `([-\/\.])`, followed by three digits `\d{3}`, followed by the remembered match of a dash, forward slash, or decimal point `\1`, followed by four digits `\d{4}`. - -The `Change` event activated when the user presses Enter sets the value of `RegExp.input`. - -#### HTML - - <p> - Enter your phone number (with area code) and then click "Check". - <br> - The expected format is like ###-###-####. - </p> - <form action="#"> - <input id="phone"> - <button onclick="testInfo(document.getElementById('phone'));">Check</button> - </form> - -#### JavaScript - - let re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/; - function testInfo(phoneInput) { - let OK = re.exec(phoneInput.value); - if (!OK) { - console.error(phoneInput.value + ' isn\'t a phone number with area code!'); - } else { - console.log('Thanks, your phone number is ' + OK[0]);} - } - -### Cheat Sheet - -<figure><img src="https://cdn-images-1.medium.com/max/800/1*VmpGy_BYCekOncdyrgSrxw.png" class="graf-image" /></figure>#### If you found this guide helpful feel free to checkout my GitHub/gist's where I host similar content: - -> <a href="https://gist.github.com/bgoonz" class="markup--anchor markup--blockquote-anchor"><strong>bgoonz's</strong> gists · GitHub</a> - -<a href="https://github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://github.com/bgoonz"><strong>bgoonz — Overview</strong> -<br/> - -<em>Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…</em>github.com</a><a href="https://github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -Or Checkout my personal Resource Site: - -<a href="https://goofy-euclid-1cd736.netlify.app/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://goofy-euclid-1cd736.netlify.app/"><strong>a/A-Student-Resources</strong> -<br/> - -<em>Edit description</em>goofy-euclid-1cd736.netlify.app</a><a href="https://goofy-euclid-1cd736.netlify.app/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [March 6, 2021](https://medium.com/p/4d8fb3eb146b). - -<a href="https://medium.com/@bryanguner/regular-expressions-4d8fb3eb146b" class="p-canonical">Canonical link</a> - -August 6, 2021. diff --git a/notes/articles/medium/markdown/Resources-By-Programming-Language.md b/notes/articles/medium/markdown/Resources-By-Programming-Language.md deleted file mode 100644 index f6226d45a3..0000000000 --- a/notes/articles/medium/markdown/Resources-By-Programming-Language.md +++ /dev/null @@ -1,102 +0,0 @@ -# Resources By Programming Language - -Here's a list of programming resources sorted by programming language. - ---- - -### Resources By Programming Language - -#### Here's a list of programming resources sorted by programming language. - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*-ViOhk6rVk72MIhu.png" class="graf-image" /></figure>### C - -- <span id="cd68"><a href="https://github.com/jwasham/coding-interview-university/blob/master/extras/cheat%20sheets/C%20Reference%20Card%20%28ANSI%29%202.2.pdf" class="markup--anchor markup--li-anchor">ANSI C Cheat Sheet</a></span> -- <span id="86cd">K&R C book (ANSI C)</span> -- <span id="322f"><a href="https://www.youtube.com/watch?v=U3zCxnj2w8M" class="markup--anchor markup--li-anchor">Make, Clang (video)</a></span> -- <span id="a17b">GDB:</span> -- <span id="8915"><a href="https://www.youtube.com/watch?v=USPvePv1uzE" class="markup--anchor markup--li-anchor">Harvard CS50 — GDB (video)</a></span> -- <span id="1a2c"><a href="https://www.youtube.com/watch?v=y5JmQItfFck" class="markup--anchor markup--li-anchor">Harvard CS50 — GDB (video)</a></span> -- <span id="f35c"><a href="https://www.youtube.com/watch?v=fvTsFjDuag8" class="markup--anchor markup--li-anchor">Valgrind (video)</a></span> -- <span id="a02f"><a href="https://books.google.co.in/books/about/Let_Us_C.html?id=7HrjAAAACAAJ" class="markup--anchor markup--li-anchor">Let us C</a></span> - -### C++ - -- <span id="dbe7"><a href="https://github.com/jwasham/coding-interview-university/blob/master/extras/cheat%20sheets/Cpp_reference.pdf" class="markup--anchor markup--li-anchor">C++ Cheat Sheet</a></span> -- <span id="7799"><a href="https://github.com/jwasham/coding-interview-university/blob/master/extras/cheat%20sheets/STL%20Quick%20Reference%201.29.pdf" class="markup--anchor markup--li-anchor">STL Cheat Sheet</a></span> -- <span id="c191"><a href="https://www.tutorialspoint.com/cplusplus/cpp_basic_syntax.htm" class="markup--anchor markup--li-anchor">basics</a></span> -- <span id="2aa2"><a href="https://www.cprogramming.com/tutorial/lesson6.html" class="markup--anchor markup--li-anchor">pointers</a></span> -- <span id="ac28"><a href="https://www.cprogramming.com/tutorial/lesson12.html" class="markup--anchor markup--li-anchor">class and object</a></span> -- <span id="ced6"><a href="https://www.cprogramming.com/tutorial/lesson4.html" class="markup--anchor markup--li-anchor">functions</a></span> -- <span id="83e6"><a href="https://www.geeksforgeeks.org/references-in-c/" class="markup--anchor markup--li-anchor">references</a></span> -- <span id="c787"><a href="https://www.cprogramming.com/tutorial/templates.html" class="markup--anchor markup--li-anchor">templates</a></span> -- <span id="4eba"><a href="https://www.youtube.com/watch?v=ZTu0kf-7h08" class="markup--anchor markup--li-anchor">compilation</a></span> -- <span id="012f"><a href="https://www.learncpp.com/cpp-tutorial/scope-duration-and-linkage-summary/" class="markup--anchor markup--li-anchor">scope & linkage</a></span> -- <span id="c684"><a href="https://www.tutorialspoint.com/cplusplus/cpp_namespaces.htm" class="markup--anchor markup--li-anchor">namespaces</a></span> -- <span id="3f4b"><a href="https://www.geeksforgeeks.org/object-oriented-programming-in-cpp/" class="markup--anchor markup--li-anchor">OOP</a></span> -- <span id="b123"><a href="https://www.hackerearth.com/practice/notes/standard-template-library/" class="markup--anchor markup--li-anchor">STL</a></span> -- <span id="fe31"><a href="http://www.cprogramming.com/tutorial/functors-function-objects-in-c++.html" class="markup--anchor markup--li-anchor">functors</a></span> -- <span id="6008"><a href="https://www.youtube.com/watch?v=NOCElcMcFik" class="markup--anchor markup--li-anchor">C++ at Google (video)</a></span> -- <span id="3eaf"><a href="https://google.github.io/styleguide/cppguide.html" class="markup--anchor markup--li-anchor">Google C++ Style Guide</a></span> -- <span id="f1fa"><a href="https://youtu.be/fHNmRkzxHWs" class="markup--anchor markup--li-anchor">Efficiency with Algorithms, Performance with Data Structures (video)</a></span> -- <span id="af38"><a href="https://www.youtube.com/watch?v=Rub-JsjMhWY" class="markup--anchor markup--li-anchor">Review of C++ concepts (video)</a></span> -- <span id="0e6e"><a href="https://books.google.co.in/books/about/Let_Us_C++.html?id=6HrjAAAACAAJ" class="markup--anchor markup--li-anchor">Let us C++</a></span> -- <span id="bb07"><a href="https://books.google.co.in/books/about/C++_Primer.html?id=J1HMLyxqJfgC&redir_esc=y" class="markup--anchor markup--li-anchor">C++ Primer</a></span> - -### Python - -- <span id="8ed2"><a href="https://github.com/jwasham/coding-interview-university/blob/master/extras/cheat%20sheets/python-cheat-sheet-v1.pdf" class="markup--anchor markup--li-anchor">Python Cheat Sheet</a></span> -- <span id="8eb6"><a href="https://www.youtube.com/watch?v=N4mEzFDjqtA" class="markup--anchor markup--li-anchor">Python in One Video</a></span> -- <span id="fa22"><a href="https://www.youtube.com/playlist?list=PL6gx4Cwl9DGAcbMi1sH6oAMk4JHw91mC_" class="markup--anchor markup--li-anchor">Series on 3.4 (video)</a></span> -- <span id="d244"><a href="https://www.youtube.com/watch?v=Iq9DzN6mvYA" class="markup--anchor markup--li-anchor">Statistics for Hackers (video)</a></span> -- <span id="a349"><a href="https://www.youtube.com/watch?v=JDSGVvMwNM8" class="markup--anchor markup--li-anchor">Faster Python (video)</a></span> -- <span id="e024"><a href="https://www.youtube.com/watch?v=LhadeL7_EIU&list=PLzV58Zm8FuBL6OAv1Yu6AwXZrnsFbbR0S&index=6" class="markup--anchor markup--li-anchor">CPython Walk (video)</a></span> -- <span id="da79"><a href="https://www.youtube.com/watch?v=_O23jIXsshs" class="markup--anchor markup--li-anchor">10 Tips for Pythonic Code (video)</a></span> -- <span id="2d17"><a href="https://www.youtube.com/watch?v=wf-BqAjZb8M" class="markup--anchor markup--li-anchor">Beyond PEP 8 — Best practices for beautiful intelligible code (video)</a></span> -- <span id="de47"><a href="https://automatetheboringstuff.com/" class="markup--anchor markup--li-anchor">Automate the Boring Stuff with Python</a></span> -- <span id="dbe9"><a href="https://github.com/ajinkyal121/coding-interview-university/blob/master/extras/cheat%20sheets/Coding%20Interview%20Python%20Language%20Essentials.pdf" class="markup--anchor markup--li-anchor">Coding Interview Essentials</a></span> -- <span id="aa97"><a href="https://www.youtube.com/watch?v=kQDxmjfkIKY" class="markup--anchor markup--li-anchor">Data Structures And Algorithms in Python</a></span> - -### Java - -- <span id="e7b2"><a href="https://see.stanford.edu/Course/CS106A" class="markup--anchor markup--li-anchor">Stanford CS106A — Programming Methodology (video)</a></span> -- <span id="3c65"><a href="https://www.edx.org/course/software-construction-java-mitx-6-005-1x" class="markup--anchor markup--li-anchor">Software Construction In Java (video)</a></span> -- <span id="1ebe"><a href="http://introcs.cs.princeton.edu/java/home/" class="markup--anchor markup--li-anchor">Introduction To Programming In Java</a></span> -- <span id="ad86"><a href="http://algs4.cs.princeton.edu/home/" class="markup--anchor markup--li-anchor">Algorithms 4th Ed — Algorithm Book In Java</a></span> -- <span id="835a"><a href="https://www.amazon.com/Effective-Java-Joshua-Bloch-ebook/dp/B078H61SCH" class="markup--anchor markup--li-anchor">Effective Java 3rd Edition</a></span> -- <span id="cba0"><a href="https://www.youtube.com/watch?v=RBSGKlAvoiM&t=1744s" class="markup--anchor markup--li-anchor">Data Structures Easy to Advanced Course — Full Tutorial from a Google Engineer</a></span> - -### Go - -- <span id="7cf8"><a href="https://golang.org/" class="markup--anchor markup--li-anchor">The Go programming Language</a></span> -- <span id="0039"><a href="http://www.gopl.io/" class="markup--anchor markup--li-anchor">The Go programming Language (book)</a></span> -- <span id="4ce3"><a href="https://tour.golang.org/" class="markup--anchor markup--li-anchor">A Tour of Go</a></span> -- <span id="8b4b"><a href="https://golang.org/doc/effective_go.html" class="markup--anchor markup--li-anchor">Effective Go</a></span> -- <span id="7281"><a href="https://golang.org/wiki" class="markup--anchor markup--li-anchor">Go Wiki</a></span> -- <span id="775f"><a href="https://talks.golang.org/2012/splash.article" class="markup--anchor markup--li-anchor">Go at Google: Language Design in the Service of Software Engineering</a></span> -- <span id="72e6"><a href="http://go-proverbs.github.io/" class="markup--anchor markup--li-anchor">Go Proverbs</a></span> -- <span id="0359"><a href="https://www.youtube.com/watch?v=PAAkCSZUG1c" class="markup--anchor markup--li-anchor">Go Proverbs — Rob Pike (video)</a></span> - -### HTML - -- <span id="a39d"><a href="https://www.youtube.com/playlist?list=PLr6-GrHUlVf_ZNmuQSXdS197Oyr1L9sPB" class="markup--anchor markup--li-anchor">Quick HTML Tutorial for Beginners</a></span> -- <span id="386f"><a href="https://www.youtube.com/watch?v=UB1O30fR-EE" class="markup--anchor markup--li-anchor">HTML Crash Course for Beginners (1 hr)</a></span> -- <span id="541a"><a href="https://www.freecodecamp.org/learn/responsive-web-design/basic-html-and-html5/" class="markup--anchor markup--li-anchor">Basic HTML and HTML5</a></span> - -### CSS - -- <span id="a683"><a href="https://www.youtube.com/playlist?list=PLr6-GrHUlVf8JIgLcu3sHigvQjTw_aC9C" class="markup--anchor markup--li-anchor">Quick CSS Tutorial for Beginners</a></span> -- <span id="4fb3"><a href="https://www.youtube.com/watch?v=yfoY53QXEnI" class="markup--anchor markup--li-anchor">CSS Crash Course for absolute Beginners</a></span> -- <span id="b459"><a href="https://www.freecodecamp.org/learn/responsive-web-design/basic-css/" class="markup--anchor markup--li-anchor">Basic CSS</a></span> - -### Javascript - -- <span id="11ee"><a href="https://www.youtube.com/watch?v=Ukg_U3CnJWI" class="markup--anchor markup--li-anchor">Learn Javascript in 12 minutes</a></span> -- <span id="9cbc"><a href="https://www.youtube.com/playlist?list=PL41lfR-6DnOrwYi5d824q9-Y6z3JdSgQa" class="markup--anchor markup--li-anchor">Javascript Beginner Tutorials</a></span> -- <span id="1239"><a href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/" class="markup--anchor markup--li-anchor">Javascript Algorithms and Data Structures</a></span> -- <span id="9d72"><a href="https://github.com/trekhleb/javascript-algorithms" class="markup--anchor markup--li-anchor">Javascript Algorithms With Explanations</a></span> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [May 31, 2021](https://medium.com/p/399d9f9ef520). - -<a href="https://medium.com/@bryanguner/resources-by-programming-language-399d9f9ef520" class="p-canonical">Canonical link</a> - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Resources-By-Programming.md b/notes/articles/medium/markdown/Resources-By-Programming.md deleted file mode 100644 index 203e6d72a8..0000000000 --- a/notes/articles/medium/markdown/Resources-By-Programming.md +++ /dev/null @@ -1,102 +0,0 @@ -# Resources By Programming Language - -Here's a list of programming resources sorted by programming language. - ---- - -### Resources By Programming Language - -#### Here's a list of programming resources sorted by programming language. - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*-ViOhk6rVk72MIhu.png" class="graf-image" /></figure>### C - -- <span id="cd68"><a href="https://github.com/jwasham/coding-interview-university/blob/master/extras/cheat%20sheets/C%20Reference%20Card%20%28ANSI%29%202.2.pdf" class="markup--anchor markup--li-anchor">ANSI C Cheat Sheet</a></span> -- <span id="86cd">K&R C book (ANSI C)</span> -- <span id="322f"><a href="https://www.youtube.com/watch?v=U3zCxnj2w8M" class="markup--anchor markup--li-anchor">Make, Clang (video)</a></span> -- <span id="a17b">GDB:</span> -- <span id="8915"><a href="https://www.youtube.com/watch?v=USPvePv1uzE" class="markup--anchor markup--li-anchor">Harvard CS50 — GDB (video)</a></span> -- <span id="1a2c"><a href="https://www.youtube.com/watch?v=y5JmQItfFck" class="markup--anchor markup--li-anchor">Harvard CS50 — GDB (video)</a></span> -- <span id="f35c"><a href="https://www.youtube.com/watch?v=fvTsFjDuag8" class="markup--anchor markup--li-anchor">Valgrind (video)</a></span> -- <span id="a02f"><a href="https://books.google.co.in/books/about/Let_Us_C.html?id=7HrjAAAACAAJ" class="markup--anchor markup--li-anchor">Let us C</a></span> - -### C++ - -- <span id="dbe7"><a href="https://github.com/jwasham/coding-interview-university/blob/master/extras/cheat%20sheets/Cpp_reference.pdf" class="markup--anchor markup--li-anchor">C++ Cheat Sheet</a></span> -- <span id="7799"><a href="https://github.com/jwasham/coding-interview-university/blob/master/extras/cheat%20sheets/STL%20Quick%20Reference%201.29.pdf" class="markup--anchor markup--li-anchor">STL Cheat Sheet</a></span> -- <span id="c191"><a href="https://www.tutorialspoint.com/cplusplus/cpp_basic_syntax.htm" class="markup--anchor markup--li-anchor">basics</a></span> -- <span id="2aa2"><a href="https://www.cprogramming.com/tutorial/lesson6.html" class="markup--anchor markup--li-anchor">pointers</a></span> -- <span id="ac28"><a href="https://www.cprogramming.com/tutorial/lesson12.html" class="markup--anchor markup--li-anchor">class and object</a></span> -- <span id="ced6"><a href="https://www.cprogramming.com/tutorial/lesson4.html" class="markup--anchor markup--li-anchor">functions</a></span> -- <span id="83e6"><a href="https://www.geeksforgeeks.org/references-in-c/" class="markup--anchor markup--li-anchor">references</a></span> -- <span id="c787"><a href="https://www.cprogramming.com/tutorial/templates.html" class="markup--anchor markup--li-anchor">templates</a></span> -- <span id="4eba"><a href="https://www.youtube.com/watch?v=ZTu0kf-7h08" class="markup--anchor markup--li-anchor">compilation</a></span> -- <span id="012f"><a href="https://www.learncpp.com/cpp-tutorial/scope-duration-and-linkage-summary/" class="markup--anchor markup--li-anchor">scope & linkage</a></span> -- <span id="c684"><a href="https://www.tutorialspoint.com/cplusplus/cpp_namespaces.htm" class="markup--anchor markup--li-anchor">namespaces</a></span> -- <span id="3f4b"><a href="https://www.geeksforgeeks.org/object-oriented-programming-in-cpp/" class="markup--anchor markup--li-anchor">OOP</a></span> -- <span id="b123"><a href="https://www.hackerearth.com/practice/notes/standard-template-library/" class="markup--anchor markup--li-anchor">STL</a></span> -- <span id="fe31"><a href="http://www.cprogramming.com/tutorial/functors-function-objects-in-c++.html" class="markup--anchor markup--li-anchor">functors</a></span> -- <span id="6008"><a href="https://www.youtube.com/watch?v=NOCElcMcFik" class="markup--anchor markup--li-anchor">C++ at Google (video)</a></span> -- <span id="3eaf"><a href="https://google.github.io/styleguide/cppguide.html" class="markup--anchor markup--li-anchor">Google C++ Style Guide</a></span> -- <span id="f1fa"><a href="https://youtu.be/fHNmRkzxHWs" class="markup--anchor markup--li-anchor">Efficiency with Algorithms, Performance with Data Structures (video)</a></span> -- <span id="af38"><a href="https://www.youtube.com/watch?v=Rub-JsjMhWY" class="markup--anchor markup--li-anchor">Review of C++ concepts (video)</a></span> -- <span id="0e6e"><a href="https://books.google.co.in/books/about/Let_Us_C++.html?id=6HrjAAAACAAJ" class="markup--anchor markup--li-anchor">Let us C++</a></span> -- <span id="bb07"><a href="https://books.google.co.in/books/about/C++_Primer.html?id=J1HMLyxqJfgC&redir_esc=y" class="markup--anchor markup--li-anchor">C++ Primer</a></span> - -### Python - -- <span id="8ed2"><a href="https://github.com/jwasham/coding-interview-university/blob/master/extras/cheat%20sheets/python-cheat-sheet-v1.pdf" class="markup--anchor markup--li-anchor">Python Cheat Sheet</a></span> -- <span id="8eb6"><a href="https://www.youtube.com/watch?v=N4mEzFDjqtA" class="markup--anchor markup--li-anchor">Python in One Video</a></span> -- <span id="fa22"><a href="https://www.youtube.com/playlist?list=PL6gx4Cwl9DGAcbMi1sH6oAMk4JHw91mC_" class="markup--anchor markup--li-anchor">Series on 3.4 (video)</a></span> -- <span id="d244"><a href="https://www.youtube.com/watch?v=Iq9DzN6mvYA" class="markup--anchor markup--li-anchor">Statistics for Hackers (video)</a></span> -- <span id="a349"><a href="https://www.youtube.com/watch?v=JDSGVvMwNM8" class="markup--anchor markup--li-anchor">Faster Python (video)</a></span> -- <span id="e024"><a href="https://www.youtube.com/watch?v=LhadeL7_EIU&list=PLzV58Zm8FuBL6OAv1Yu6AwXZrnsFbbR0S&index=6" class="markup--anchor markup--li-anchor">CPython Walk (video)</a></span> -- <span id="da79"><a href="https://www.youtube.com/watch?v=_O23jIXsshs" class="markup--anchor markup--li-anchor">10 Tips for Pythonic Code (video)</a></span> -- <span id="2d17"><a href="https://www.youtube.com/watch?v=wf-BqAjZb8M" class="markup--anchor markup--li-anchor">Beyond PEP 8 — Best practices for beautiful intelligible code (video)</a></span> -- <span id="de47"><a href="https://automatetheboringstuff.com/" class="markup--anchor markup--li-anchor">Automate the Boring Stuff with Python</a></span> -- <span id="dbe9"><a href="https://github.com/ajinkyal121/coding-interview-university/blob/master/extras/cheat%20sheets/Coding%20Interview%20Python%20Language%20Essentials.pdf" class="markup--anchor markup--li-anchor">Coding Interview Essentials</a></span> -- <span id="aa97"><a href="https://www.youtube.com/watch?v=kQDxmjfkIKY" class="markup--anchor markup--li-anchor">Data Structures And Algorithms in Python</a></span> - -### Java - -- <span id="e7b2"><a href="https://see.stanford.edu/Course/CS106A" class="markup--anchor markup--li-anchor">Stanford CS106A — Programming Methodology (video)</a></span> -- <span id="3c65"><a href="https://www.edx.org/course/software-construction-java-mitx-6-005-1x" class="markup--anchor markup--li-anchor">Software Construction In Java (video)</a></span> -- <span id="1ebe"><a href="http://introcs.cs.princeton.edu/java/home/" class="markup--anchor markup--li-anchor">Introduction To Programming In Java</a></span> -- <span id="ad86"><a href="http://algs4.cs.princeton.edu/home/" class="markup--anchor markup--li-anchor">Algorithms 4th Ed — Algorithm Book In Java</a></span> -- <span id="835a"><a href="https://www.amazon.com/Effective-Java-Joshua-Bloch-ebook/dp/B078H61SCH" class="markup--anchor markup--li-anchor">Effective Java 3rd Edition</a></span> -- <span id="cba0"><a href="https://www.youtube.com/watch?v=RBSGKlAvoiM&t=1744s" class="markup--anchor markup--li-anchor">Data Structures Easy to Advanced Course — Full Tutorial from a Google Engineer</a></span> - -### Go - -- <span id="7cf8"><a href="https://golang.org/" class="markup--anchor markup--li-anchor">The Go programming Language</a></span> -- <span id="0039"><a href="http://www.gopl.io/" class="markup--anchor markup--li-anchor">The Go programming Language (book)</a></span> -- <span id="4ce3"><a href="https://tour.golang.org/" class="markup--anchor markup--li-anchor">A Tour of Go</a></span> -- <span id="8b4b"><a href="https://golang.org/doc/effective_go.html" class="markup--anchor markup--li-anchor">Effective Go</a></span> -- <span id="7281"><a href="https://golang.org/wiki" class="markup--anchor markup--li-anchor">Go Wiki</a></span> -- <span id="775f"><a href="https://talks.golang.org/2012/splash.article" class="markup--anchor markup--li-anchor">Go at Google: Language Design in the Service of Software Engineering</a></span> -- <span id="72e6"><a href="http://go-proverbs.github.io/" class="markup--anchor markup--li-anchor">Go Proverbs</a></span> -- <span id="0359"><a href="https://www.youtube.com/watch?v=PAAkCSZUG1c" class="markup--anchor markup--li-anchor">Go Proverbs — Rob Pike (video)</a></span> - -### HTML - -- <span id="a39d"><a href="https://www.youtube.com/playlist?list=PLr6-GrHUlVf_ZNmuQSXdS197Oyr1L9sPB" class="markup--anchor markup--li-anchor">Quick HTML Tutorial for Beginners</a></span> -- <span id="386f"><a href="https://www.youtube.com/watch?v=UB1O30fR-EE" class="markup--anchor markup--li-anchor">HTML Crash Course for Beginners (1 hr)</a></span> -- <span id="541a"><a href="https://www.freecodecamp.org/learn/responsive-web-design/basic-html-and-html5/" class="markup--anchor markup--li-anchor">Basic HTML and HTML5</a></span> - -### CSS - -- <span id="a683"><a href="https://www.youtube.com/playlist?list=PLr6-GrHUlVf8JIgLcu3sHigvQjTw_aC9C" class="markup--anchor markup--li-anchor">Quick CSS Tutorial for Beginners</a></span> -- <span id="4fb3"><a href="https://www.youtube.com/watch?v=yfoY53QXEnI" class="markup--anchor markup--li-anchor">CSS Crash Course for absolute Beginners</a></span> -- <span id="b459"><a href="https://www.freecodecamp.org/learn/responsive-web-design/basic-css/" class="markup--anchor markup--li-anchor">Basic CSS</a></span> - -### Javascript - -- <span id="11ee"><a href="https://www.youtube.com/watch?v=Ukg_U3CnJWI" class="markup--anchor markup--li-anchor">Learn Javascript in 12 minutes</a></span> -- <span id="9cbc"><a href="https://www.youtube.com/playlist?list=PL41lfR-6DnOrwYi5d824q9-Y6z3JdSgQa" class="markup--anchor markup--li-anchor">Javascript Beginner Tutorials</a></span> -- <span id="1239"><a href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/" class="markup--anchor markup--li-anchor">Javascript Algorithms and Data Structures</a></span> -- <span id="9d72"><a href="https://github.com/trekhleb/javascript-algorithms" class="markup--anchor markup--li-anchor">Javascript Algorithms With Explanations</a></span> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [May 31, 2021](https://medium.com/p/399d9f9ef520). - -<a href="https://medium.com/@bryanguner/resources-by-programming-language-399d9f9ef520" class="p-canonical">Canonical link</a> - -August 6, 2021. diff --git a/notes/articles/medium/markdown/Scheduling--setTimeout-and-setInterval.md b/notes/articles/medium/markdown/Scheduling--setTimeout-and-setInterval.md deleted file mode 100644 index 7ae1685f80..0000000000 --- a/notes/articles/medium/markdown/Scheduling--setTimeout-and-setInterval.md +++ /dev/null @@ -1,278 +0,0 @@ -# Scheduling: setTimeout and setInterval - -We may decide to execute a function not right now, but at a later time. That's called "scheduling a call". - ---- - -### Scheduling: setTimeout and setInterval - -We may decide to execute a function not right now, but at a later time. That's called "scheduling a call". - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*EnCk0hh8R6B290EH.gif" class="graf-image" /></figure>There are two methods for it: - -- <span id="4106">`setTimeout` allows us to run a function once after the interval of time.</span> -- <span id="333d">`setInterval` allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.</span> - -These methods are not a part of JavaScript specification. But most environments have an internal scheduler and provide these methods. In particular, they are supported in all browsers and Node.js. - -### setTimeout - -The syntax: - - let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...) - -Parameters: - -`func|code`: Function or a string of code to execute. -Usually, that's a function. For historical reasons, a string of code can be passed, but that's not recommended. - -`delay`: The delay before running, in milliseconds (1000 ms = 1 second), by default 0. - -`arg1`, `arg2`: Arguments for the function (not supported in IE9-) - -For instance, this code calls `sayHi()` after one second: - - function sayHi() { - alert('Hello'); - } - - *!* - setTimeout(sayHi, 1000); - */!* - -With arguments: - - function sayHi(phrase, who) { - alert( phrase + ', ' + who ); - } - - *!* - setTimeout(sayHi, 1000, "Hello", "John"); // Hello, John - */!* - -If the first argument is a string, then JavaScript creates a function from it. - -So, this will also work: - - setTimeout("alert('Hello')", 1000); - -But using strings is not recommended, use arrow functions instead of them, like this: - - setTimeout(() => alert('Hello'), 1000); - - Novice developers sometimes make a mistake by adding brackets `()` after the function: - - ```js - // wrong! - setTimeout(sayHi(), 1000); - ``` - That doesn't work, because `setTimeout` expects a reference to a function. And here `sayHi()` runs the function, and the *result of its execution* is passed to `setTimeout`. In our case the result of `sayHi()` is `undefined` (the function returns nothing), so nothing is scheduled. - -### Canceling with clearTimeout - -A call to `setTimeout` returns a "timer identifier" `timerId` that we can use to cancel the execution. - -The syntax to cancel: - - let timerId = setTimeout(...); - clearTimeout(timerId); - -In the code below, we schedule the function and then cancel it (changed our mind). As a result, nothing happens: - - let timerId = setTimeout(() => alert("never happens"), 1000); - alert(timerId); // timer identifier - - clearTimeout(timerId); - alert(timerId); // same identifier (doesn't become null after canceling) - -As we can see from `alert` output, in a browser the timer identifier is a number. In other environments, this can be something else. For instance, Node.js returns a timer object with additional methods. - -Again, there is no universal specification for these methods, so that's fine. - -For browsers, timers are described in the <a href="https://www.w3.org/TR/html5/webappapis.html#timers" class="markup--anchor markup--p-anchor">timers section</a> of HTML5 standard. - -### setInterval - -The `setInterval` method has the same syntax as `setTimeout`: - - let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...) - -All arguments have the same meaning. But unlike `setTimeout` it runs the function not only once, but regularly after the given interval of time. - -To stop further calls, we should call `clearInterval(timerId)`. - -The following example will show the message every 2 seconds. After 5 seconds, the output is stopped: - - // repeat with the interval of 2 seconds - let timerId = setInterval(() => alert('tick'), 2000); - - // after 5 seconds stop - setTimeout(() => { clearInterval(timerId); alert('stop'); }, 5000); - -\`\`\`smart header = "Time goes on while `alert` is shown" - -In most browsers, including Chrome and Firefox, the internal timer continues "ticking" while showing `alert/confirm/prompt`. - -So if you run the code above and don't dismiss the `alert` window for some time, then the next `alert` will be shown immediately as you do it. The actual interval between alerts will be shorter than 2 seconds. - - ## Nested setTimeout - <p class="mume-header " id="nested-settimeout"></p> - - There are two ways of running something regularly. - - One is `setInterval`. The other one is a nested `setTimeout`, like this: - - ```js - /** instead of: - let timerId = setInterval(() => alert('tick'), 2000); - */ - - let timerId = setTimeout(function tick() { - alert('tick'); - *!* - timerId = setTimeout(tick, 2000); // (*) - */!* - }, 2000); - -The `setTimeout` above schedules the next call right at the end of the current one `(*)`. - -The nested `setTimeout` is a more flexible method than `setInterval`. This way the next call may be scheduled differently, depending on the results of the current one. - -For instance, we need to write a service that sends a request to the server every 5 seconds asking for data, but in case the server is overloaded, it should increase the interval to 10, 20, 40 seconds… - -Here's the pseudocode: - - let delay = 5000; - - let timerId = setTimeout(function request() { - ...send request... - - if (request failed due to server overload) { - // increase the interval to the next run - delay *= 2; - } - - timerId = setTimeout(request, delay); - - }, delay); - -And if the functions that we're scheduling are CPU-hungry, then we can measure the time taken by the execution and plan the next call sooner or later. - -**Nested** `setTimeout` **allows to set the delay between the executions more precisely than** `setInterval`**.** - -Let's compare two code fragments. The first one uses `setInterval`: - - let i = 1; - setInterval(function() { - func(i++); - }, 100); - -The second one uses nested `setTimeout`: - - let i = 1; - setTimeout(function run() { - func(i++); - setTimeout(run, 100); - }, 100); - -For `setInterval` the internal scheduler will run `func(i++)` every 100ms: - -Did you notice? - -**The real delay between** `func` **calls for** `setInterval` **is less than in the code!** - -That's normal, because the time taken by `func`'s execution "consumes" a part of the interval. - -It is possible that `func`'s execution turns out to be longer than we expected and takes more than 100ms. - -In this case the engine waits for `func` to complete, then checks the scheduler and if the time is up, runs it again _immediately_. - -In the edge case, if the function always executes longer than `delay` ms, then the calls will happen without a pause at all. - -And here is the picture for the nested `setTimeout`: - -**The nested** `setTimeout` **guarantees the fixed delay (here 100ms).** - -That's because a new call is planned at the end of the previous one. - - When a function is passed in `setInterval/setTimeout`, an internal reference is created to it and saved in the scheduler. It prevents the function from being garbage collected, even if there are no other references to it. - - ```js - // the function stays in memory until the scheduler calls it - setTimeout(function() {...}, 100); - ``` - - For `setInterval` the function stays in memory until `clearInterval` is called. - - There's a side-effect. A function references the outer lexical environment, so, while it lives, outer variables live too. They may take much more memory than the function itself. So when we don't need the scheduled function anymore, it's better to cancel it, even if it's very small. - -### Zero delay setTimeout - -There's a special use case: `setTimeout(func, 0)`, or just `setTimeout(func)`. - -This schedules the execution of `func` as soon as possible. But the scheduler will invoke it only after the currently executing script is complete. - -So the function is scheduled to run "right after" the current script. - -For instance, this outputs "Hello", then immediately "World": - - setTimeout(() => alert("World")); - - alert("Hello"); - -The first line "puts the call into calendar after 0ms". But the scheduler will only "check the calendar" after the current script is complete, so `"Hello"` is first, and `"World"` -- after it. - -There are also advanced browser-related use cases of a zero-delay timeout, that we'll discuss in the chapter info:event-loop. - - In the browser, there's a limitation of how often nested timers can run. The [HTML5 standard](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers) says: "after five nested timers, the interval is forced to be at least 4 milliseconds.". - - Let's demonstrate what it means with the example below. The `setTimeout` call in it re-schedules itself with zero delay. Each call remembers the real time from the previous one in the `times` array. What do the real delays look like? Let's see: - - ```js run - let start = Date.now(); - let times = []; - - setTimeout(function run() { - times.push(Date.now() - start); // remember delay from the previous call - - if (start + 100 < Date.now()) alert(times); // show the delays after 100ms - else setTimeout(run); // else re-schedule - }); - - // an example of the output: - // 1,1,1,1,9,15,20,24,30,35,40,45,50,55,59,64,70,75,80,85,90,95,100 - ``` - - First timers run immediately (just as written in the spec), and then we see `9, 15, 20, 24...`. The 4+ ms obligatory delay between invocations comes into play. - - The similar thing happens if we use `setInterval` instead of `setTimeout`: `setInterval(f)` runs `f` few times with zero-delay, and afterwards with 4+ ms delay. - - That limitation comes from ancient times and many scripts rely on it, so it exists for historical reasons. - - For server-side JavaScript, that limitation does not exist, and there exist other ways to schedule an immediate asynchronous job, like [setImmediate](https://nodejs.org/api/timers.html#timers_setimmediate_callback_args) for Node.js. So this note is browser-specific. - -### Summary - -- <span id="4074">Methods `setTimeout(func, delay, ...args)` and `setInterval(func, delay, ...args)` allow us to run the `func` once/regularly after `delay` milliseconds.</span> -- <span id="6249">To cancel the execution, we should call `clearTimeout/clearInterval` with the value returned by `setTimeout/setInterval`.</span> -- <span id="af18">Nested `setTimeout` calls are a more flexible alternative to `setInterval`, allowing us to set the time _between_ executions more precisely.</span> -- <span id="06e2">Zero delay scheduling with `setTimeout(func, 0)` (the same as `setTimeout(func)`) is used to schedule the call "as soon as possible, but after the current script is complete".</span> -- <span id="5393">The browser limits the minimal delay for five or more nested calls of `setTimeout` or for `setInterval` (after 5th call) to 4ms. That's for historical reasons.</span> - -Please note that all scheduling methods do not _guarantee_ the exact delay. - -For example, the in-browser timer may slow down for a lot of reasons: - -- <span id="e3b2">The CPU is overloaded.</span> -- <span id="2aed">The browser tab is in the background mode.</span> -- <span id="116d">The laptop is on battery.</span> - -All that may increase the minimal timer resolution (the minimal delay) to 300ms or even 1000ms depending on the browser and OS-level performance settings. - -_More content at_ <a href="http://plainenglish.io/" class="markup--anchor markup--p-anchor"><em>plainenglish.io</em></a> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [May 18, 2021](https://medium.com/p/fcb2f40d16f7). - -<a href="https://medium.com/@bryanguner/scheduling-settimeout-and-setinterval-fcb2f40d16f7" class="p-canonical">Canonical link</a> - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Scheduling--setTimeout-and.md b/notes/articles/medium/markdown/Scheduling--setTimeout-and.md deleted file mode 100644 index 82a247184b..0000000000 --- a/notes/articles/medium/markdown/Scheduling--setTimeout-and.md +++ /dev/null @@ -1,278 +0,0 @@ -# Scheduling: setTimeout and setInterval - -We may decide to execute a function not right now, but at a later time. That's called "scheduling a call". - ---- - -### Scheduling: setTimeout and setInterval - -We may decide to execute a function not right now, but at a later time. That's called "scheduling a call". - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*EnCk0hh8R6B290EH.gif" class="graf-image" /></figure>There are two methods for it: - -- <span id="4106">`setTimeout` allows us to run a function once after the interval of time.</span> -- <span id="333d">`setInterval` allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.</span> - -These methods are not a part of JavaScript specification. But most environments have an internal scheduler and provide these methods. In particular, they are supported in all browsers and Node.js. - -### setTimeout - -The syntax: - - let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...) - -Parameters: - -`func|code`: Function or a string of code to execute. -Usually, that's a function. For historical reasons, a string of code can be passed, but that's not recommended. - -`delay`: The delay before running, in milliseconds (1000 ms = 1 second), by default 0. - -`arg1`, `arg2`: Arguments for the function (not supported in IE9-) - -For instance, this code calls `sayHi()` after one second: - - function sayHi() { - alert('Hello'); - } - - *!* - setTimeout(sayHi, 1000); - */!* - -With arguments: - - function sayHi(phrase, who) { - alert( phrase + ', ' + who ); - } - - *!* - setTimeout(sayHi, 1000, "Hello", "John"); // Hello, John - */!* - -If the first argument is a string, then JavaScript creates a function from it. - -So, this will also work: - - setTimeout("alert('Hello')", 1000); - -But using strings is not recommended, use arrow functions instead of them, like this: - - setTimeout(() => alert('Hello'), 1000); - - Novice developers sometimes make a mistake by adding brackets `()` after the function: - - ```js - // wrong! - setTimeout(sayHi(), 1000); - ``` - That doesn't work, because `setTimeout` expects a reference to a function. And here `sayHi()` runs the function, and the *result of its execution* is passed to `setTimeout`. In our case the result of `sayHi()` is `undefined` (the function returns nothing), so nothing is scheduled. - -### Canceling with clearTimeout - -A call to `setTimeout` returns a "timer identifier" `timerId` that we can use to cancel the execution. - -The syntax to cancel: - - let timerId = setTimeout(...); - clearTimeout(timerId); - -In the code below, we schedule the function and then cancel it (changed our mind). As a result, nothing happens: - - let timerId = setTimeout(() => alert("never happens"), 1000); - alert(timerId); // timer identifier - - clearTimeout(timerId); - alert(timerId); // same identifier (doesn't become null after canceling) - -As we can see from `alert` output, in a browser the timer identifier is a number. In other environments, this can be something else. For instance, Node.js returns a timer object with additional methods. - -Again, there is no universal specification for these methods, so that's fine. - -For browsers, timers are described in the <a href="https://www.w3.org/TR/html5/webappapis.html#timers" class="markup--anchor markup--p-anchor">timers section</a> of HTML5 standard. - -### setInterval - -The `setInterval` method has the same syntax as `setTimeout`: - - let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...) - -All arguments have the same meaning. But unlike `setTimeout` it runs the function not only once, but regularly after the given interval of time. - -To stop further calls, we should call `clearInterval(timerId)`. - -The following example will show the message every 2 seconds. After 5 seconds, the output is stopped: - - // repeat with the interval of 2 seconds - let timerId = setInterval(() => alert('tick'), 2000); - - // after 5 seconds stop - setTimeout(() => { clearInterval(timerId); alert('stop'); }, 5000); - -\`\`\`smart header = "Time goes on while `alert` is shown" - -In most browsers, including Chrome and Firefox, the internal timer continues "ticking" while showing `alert/confirm/prompt`. - -So if you run the code above and don't dismiss the `alert` window for some time, then the next `alert` will be shown immediately as you do it. The actual interval between alerts will be shorter than 2 seconds. - - ## Nested setTimeout - <p class="mume-header " id="nested-settimeout"></p> - - There are two ways of running something regularly. - - One is `setInterval`. The other one is a nested `setTimeout`, like this: - - ```js - /** instead of: - let timerId = setInterval(() => alert('tick'), 2000); - */ - - let timerId = setTimeout(function tick() { - alert('tick'); - *!* - timerId = setTimeout(tick, 2000); // (*) - */!* - }, 2000); - -The `setTimeout` above schedules the next call right at the end of the current one `(*)`. - -The nested `setTimeout` is a more flexible method than `setInterval`. This way the next call may be scheduled differently, depending on the results of the current one. - -For instance, we need to write a service that sends a request to the server every 5 seconds asking for data, but in case the server is overloaded, it should increase the interval to 10, 20, 40 seconds… - -Here's the pseudocode: - - let delay = 5000; - - let timerId = setTimeout(function request() { - ...send request... - - if (request failed due to server overload) { - // increase the interval to the next run - delay *= 2; - } - - timerId = setTimeout(request, delay); - - }, delay); - -And if the functions that we're scheduling are CPU-hungry, then we can measure the time taken by the execution and plan the next call sooner or later. - -**Nested** `setTimeout` **allows to set the delay between the executions more precisely than** `setInterval`**.** - -Let's compare two code fragments. The first one uses `setInterval`: - - let i = 1; - setInterval(function() { - func(i++); - }, 100); - -The second one uses nested `setTimeout`: - - let i = 1; - setTimeout(function run() { - func(i++); - setTimeout(run, 100); - }, 100); - -For `setInterval` the internal scheduler will run `func(i++)` every 100ms: - -Did you notice? - -**The real delay between** `func` **calls for** `setInterval` **is less than in the code!** - -That's normal, because the time taken by `func`'s execution "consumes" a part of the interval. - -It is possible that `func`'s execution turns out to be longer than we expected and takes more than 100ms. - -In this case the engine waits for `func` to complete, then checks the scheduler and if the time is up, runs it again _immediately_. - -In the edge case, if the function always executes longer than `delay` ms, then the calls will happen without a pause at all. - -And here is the picture for the nested `setTimeout`: - -**The nested** `setTimeout` **guarantees the fixed delay (here 100ms).** - -That's because a new call is planned at the end of the previous one. - - When a function is passed in `setInterval/setTimeout`, an internal reference is created to it and saved in the scheduler. It prevents the function from being garbage collected, even if there are no other references to it. - - ```js - // the function stays in memory until the scheduler calls it - setTimeout(function() {...}, 100); - ``` - - For `setInterval` the function stays in memory until `clearInterval` is called. - - There's a side-effect. A function references the outer lexical environment, so, while it lives, outer variables live too. They may take much more memory than the function itself. So when we don't need the scheduled function anymore, it's better to cancel it, even if it's very small. - -### Zero delay setTimeout - -There's a special use case: `setTimeout(func, 0)`, or just `setTimeout(func)`. - -This schedules the execution of `func` as soon as possible. But the scheduler will invoke it only after the currently executing script is complete. - -So the function is scheduled to run "right after" the current script. - -For instance, this outputs "Hello", then immediately "World": - - setTimeout(() => alert("World")); - - alert("Hello"); - -The first line "puts the call into calendar after 0ms". But the scheduler will only "check the calendar" after the current script is complete, so `"Hello"` is first, and `"World"` -- after it. - -There are also advanced browser-related use cases of a zero-delay timeout, that we'll discuss in the chapter info:event-loop. - - In the browser, there's a limitation of how often nested timers can run. The [HTML5 standard](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers) says: "after five nested timers, the interval is forced to be at least 4 milliseconds.". - - Let's demonstrate what it means with the example below. The `setTimeout` call in it re-schedules itself with zero delay. Each call remembers the real time from the previous one in the `times` array. What do the real delays look like? Let's see: - - ```js run - let start = Date.now(); - let times = []; - - setTimeout(function run() { - times.push(Date.now() - start); // remember delay from the previous call - - if (start + 100 < Date.now()) alert(times); // show the delays after 100ms - else setTimeout(run); // else re-schedule - }); - - // an example of the output: - // 1,1,1,1,9,15,20,24,30,35,40,45,50,55,59,64,70,75,80,85,90,95,100 - ``` - - First timers run immediately (just as written in the spec), and then we see `9, 15, 20, 24...`. The 4+ ms obligatory delay between invocations comes into play. - - The similar thing happens if we use `setInterval` instead of `setTimeout`: `setInterval(f)` runs `f` few times with zero-delay, and afterwards with 4+ ms delay. - - That limitation comes from ancient times and many scripts rely on it, so it exists for historical reasons. - - For server-side JavaScript, that limitation does not exist, and there exist other ways to schedule an immediate asynchronous job, like [setImmediate](https://nodejs.org/api/timers.html#timers_setimmediate_callback_args) for Node.js. So this note is browser-specific. - -### Summary - -- <span id="4074">Methods `setTimeout(func, delay, ...args)` and `setInterval(func, delay, ...args)` allow us to run the `func` once/regularly after `delay` milliseconds.</span> -- <span id="6249">To cancel the execution, we should call `clearTimeout/clearInterval` with the value returned by `setTimeout/setInterval`.</span> -- <span id="af18">Nested `setTimeout` calls are a more flexible alternative to `setInterval`, allowing us to set the time _between_ executions more precisely.</span> -- <span id="06e2">Zero delay scheduling with `setTimeout(func, 0)` (the same as `setTimeout(func)`) is used to schedule the call "as soon as possible, but after the current script is complete".</span> -- <span id="5393">The browser limits the minimal delay for five or more nested calls of `setTimeout` or for `setInterval` (after 5th call) to 4ms. That's for historical reasons.</span> - -Please note that all scheduling methods do not _guarantee_ the exact delay. - -For example, the in-browser timer may slow down for a lot of reasons: - -- <span id="e3b2">The CPU is overloaded.</span> -- <span id="2aed">The browser tab is in the background mode.</span> -- <span id="116d">The laptop is on battery.</span> - -All that may increase the minimal timer resolution (the minimal delay) to 300ms or even 1000ms depending on the browser and OS-level performance settings. - -_More content at_ <a href="http://plainenglish.io/" class="markup--anchor markup--p-anchor"><em>plainenglish.io</em></a> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [May 18, 2021](https://medium.com/p/fcb2f40d16f7). - -<a href="https://medium.com/@bryanguner/scheduling-settimeout-and-setinterval-fcb2f40d16f7" class="p-canonical">Canonical link</a> - -August 6, 2021. diff --git a/notes/articles/medium/markdown/So-like-how-much-does-microsoft-pay-you-a-year-.md b/notes/articles/medium/markdown/So-like-how-much-does-microsoft-pay-you-a-year-.md deleted file mode 100644 index 3744ab6e2f..0000000000 --- a/notes/articles/medium/markdown/So-like-how-much-does-microsoft-pay-you-a-year-.md +++ /dev/null @@ -1,11 +0,0 @@ -# So like how much does microsoft pay you a year? - ---- - -So like how much does microsoft pay you a year? - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [August 6, 2021](https://medium.com/p/b02247df19a0). - -<a href="https://medium.com/@bryanguner/so-like-how-much-does-microsoft-pay-you-a-year-b02247df19a0" class="p-canonical">Canonical link</a> - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Super-Simple-Intro-To-HTML.md b/notes/articles/medium/markdown/Super-Simple-Intro-To-HTML.md deleted file mode 100644 index 7085f76c49..0000000000 --- a/notes/articles/medium/markdown/Super-Simple-Intro-To-HTML.md +++ /dev/null @@ -1,238 +0,0 @@ -# Super Simple Intro To HTML - -What is HTML, CSS & JS and why do we need all three? - ---- - -### Super Simple Intro To HTML - -#### What is HTML, CSS & JS and why do we need all three? - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*KxF-AuqgX7UklUa4.png" class="graf-image" /></figure>HTML stands for "Hypertext Markup Language". Basically, HTML is the structure for the website, words, bullet points, data tables, etc. CSS stands for "Cascading Style Sheets" which means it's the "Style" it's how to make your website look professional, and look visually appealing. JS is how to make your website actually \*\*work\*\*. - -For example, if you created something like YouTube and one of the options you can watch videos, you used HTML for the title, you used CSS for the color/s, and you have to make it actually work! So when you click on it it will run the video. This is an example of the three programming languages working in unison to form an experience you're already familiar with if you're reading this… - -**I mean most likely… unless you printed it because you hate trees.** - -— — — — — — — — — — - - -### What are Tags and Attributes? - -Tags and attributes are the basis of HTML. - -They work together but perform different functions — it is worth investing 2 minutes in **differentiating the two**. - -#### What Are HTML Tags? - -<a href="https://html.com/tags/" class="markup--anchor markup--p-anchor">Tags</a> are used to **mark up the start of an HTML element** and they are usually enclosed in angle brackets. An example of a tag is: `<h1>`. - -Most tags must be opened `<h1>` and closed `</h1>` in order to function. - -#### What are HTML Attributes? - -<a href="https://html.com/attributes/" class="markup--anchor markup--p-anchor">Attributes</a> contain **additional pieces of information**. Attributes take the form of an opening tag and additional info is **placed inside**. - -An example of an attribute is: - -`<img src="mydog.jpg" alt="A photo of my dog.">` - -In this instance, the image source (src) and the alt text (alt) are attributes of the `<img>` tag. - -#### Golden Rules To Remember - -1. <span id="e12a">The vast majority of tags must be **opened** (`<tag>`) and **closed** (`</tag>`) with the element information such as a title or text resting between the tags.</span> -2. <span id="c99f">When using multiple tags, the tags must be **closed in the order in which they were opened**. For example:</span> -3. <span id="9eb5">`<strong><em>This is really important!</em></strong>`</span> - -Let's have a look at how CodePen works, firstly, you need to go to their website. After that, you must create an account. After you do that, You will see something like this - -### How to get started - -If you're using Visual Studio Code, congrats! There is Emmet support built into VSCode, so you won't need to install any extensions. If you're working in Atom you'll need to install the Emmet plugin, which can be <a href="https://atom.io/packages/emmet" class="markup--anchor markup--p-anchor">found here</a>. - -### Basic Syntax - -**_HTML Boilerplate_** - -If you've been working in VSCode, you've probably seen Emmet syntax highlighting when working in HTML documents. In my opinion, the most convenient Emmet shortcut is **_html:5_**. This will create an HTML boilerplate, and fill out metadata tags in the head of your document. - - html:5 - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*oDrxfgtO2WE9_Z6d.png" class="graf-image" /></figure>Emmet Abbreviation for different HTML boilerplates. - -**When you see the auto complete as pictured above you can hit tab to auto fill the boilerplate html document.** - -That one small shortcut autogenerates all this metadata and head and body tags: - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*LgiaI-W7QB4mtifR.png" class="graf-image" /></figure>#### Here's some slightly more advanced boilerplate for you to use as a starting point in your projects. - -### HTML Language - -**Chapter 1: Formatting text** - -**Tags in HTML:** Tags are one of the most important parts in an HTML document. (We will get to what HTML document is after we know what tags are). HTML uses some predefined tags which tells the browser about content display property, that is how to display a particular given content. For Example, to create a paragraph, one must use the paragraph tags(<p> </p>) and to insert an image one must use the img tags(<img />). - -There are generally two types of tags in HTML: - -1. <span id="9de4">**Paired tags:** These tags come in pairs. That is they have both opening (< >) and closing(</ >) tags.</span> -2. <span id="4b61">**Singular tags:** These tags do not required to be closed</span> - -> i.e. - - <hr> - <p> The tag above me is a horizontal line that doesn't need a closing tag </p> - -HTML tags have two main types: **block-level** and **inline tags**. - -1. <span id="bd59">Block-level elements take up the full available space and always start a new line in the document. Headings and paragraphs are a great example of block tags.</span> -2. <span id="2479">Inline elements only take up as much space as they need and don't start a new line on the page. They usually serve to format the inner contents of block-level elements. Links and emphasized strings are good examples of inline tags.</span> - -### Block-Level Tags - -The three block level tags every HTML document needs to contain are **<html>**, **<head>**, and **<body>**. - -1. <span id="bd5d">The **<html></html>** tag is the highest level element that encloses every HTML page.</span> -2. <span id="c015">The **<head></head>** tag holds meta information such as the page's title and charset.</span> -3. <span id="5ca8">Finally, the **<body></body>** tag encloses all the content that appears on the page.</span> - -- <span id="7864">Paragraphs are enclosed by **_<p></p>_**, while blockquotes use the **_<blockquote></blockquote>_** tag.</span> -- <span id="82ad">Divisions are bigger content sections that typically contain several paragraphs, images, sometimes blockquotes, and other smaller elements. We can mark them up using the **_<div></div>_** tag. A div element can contain another div tag inside it as well.</span> -- <span id="39c6">You may also use **_<ol></ol>_** tags for ordered lists and **_<ul></ul>_** for unordered ones. Individual list items must be enclosed by the **_<li></li>_** tag. For example, this is how a basic unordered list looks like in HTML:</span> - -1. <span id="e470">**<ul>**</span> -2. <span id="b8c5">**<li>**List item 1**</li>**</span> -3. <span id="3c1d">**<li>**List item 2**</li>**</span> -4. <span id="97b4">**<li>**List item 3**</li>**</span> -5. <span id="b59a">**</ul>**</span> - -### **Structure of an HTML Document** - -An HTML Document is mainly divided into two parts: - -- <span id="0424">**HEAD**: This contains the information about the HTML document. For Example, Title of the page, version of HTML, Meta-Data etc.</span> - -HTML TAG Specifies an html document. The HTML element (or HTML root element) represents the root of an HTML document. All other elements must be descendants of this element. Since the element is the first in a document, it is called the root element. - -Although this tag can be implied, or not required, with HTML, it is required to be opened and closed in XHTML. - -- <span id="83fe">Divisions are bigger content sections that typically contain several paragraphs, images, sometimes blockquotes, and other smaller elements. We can mark them up using the **_<div></div>_** tag. A div element can contain another div tag inside it as well.</span> -- <span id="9d53">You may also use **_<ol></ol>_** tags for ordered lists and **_<ul></ul>_** for unordered ones. Individual list items must be enclosed by the **_<li></li>_** tag. For example, this is how a basic unordered list looks like in HTML:</span> - -1. <span id="4097">**<ul>**</span> -2. <span id="0103">**<li>**List item 1**</li>**</span> -3. <span id="1de2">**<li>**List item 2**</li>**</span> -4. <span id="dad0">**<li>**List item 3**</li>**</span> -5. <span id="592f">**</ul>**</span> - -### Inline Tags - -Many inline tags are used to format text. For example, a **<strong></strong>** tag would render an element in **bold**, whereas _<em></em>_ tags would show it in _italics_. - -Hyperlinks are also inline elements that require **_<a></a>_** tags and **href** attributes to indicate the link's destination: - -1. <span id="f67d">**<a** **href=**"https://example.com/"**>**Click me!**</a>**</span> - -Images are inline elements too. You can add one using **_<img>_** without any closing tag. But you will also need to use the **_src_** attribute to specify the image path, for example: - -1. <span id="3924">**<img** **src=**"/images/example.jpg" **alt=**"Example image"**>**</span> - -#### **BODY**: This contains everything you want to display on the Web Page. - - <body> - - <! — Everything the user sees on the webpage goes here! — ps… this is a comment → - - </body> - -Let us now have a look on the basic structure of HTML. That is the code which is must for every webpage to have: - -**_<!DOCTYPE html>_** - -#### Here is some boilerplate html you can use as a starting point:!!Every Webpage must contain this code.!! - ---- - -### **<!DOCTYPE html>** - ---- - -Below is the complete explanation of each of the tags used in the above piece of HTML code: - -**<!DOCTYPE html>:** This tag is used to tells the HTML version. This currently tells that the version is HTML 5. - -> **_<html>_:** This is called HTML root element and used to wrap all the code. - -> **<head>:** Head tag contains metadata, title, page CSS etc. All the HTML elements that can be used inside the <head> element are: - -> **<body>:** Body tag is used to enclosed all the data which a web page has from texts to links. All of the content that you see rendered in the browser is contained within this element. - -### Bold Text: - -<b> **this is bold** </b> - -<strong> ⇐ this is for strong, emergency emotions. - -\_\_\_\_\_\_\_\_\_\_\_ - -**HEADING/S:** - -_6 types from largest(h1) to smallest (h6)_ - -<h1> <h2> <h3> <h4> <h5> <h6> - -\_\_\_\_\_\_\_\_\_\_\_ - -**ITALICS:** There are two ways to use it, the first one is the <i> tag and the second one is the <em> tag. They both italicize the text<a href="https://emojipedia.org/person-shrugging/" class="markup--anchor markup--p-anchor">🤷</a> - -<i> _this is fancy text that's too good to for us_</i> - -\_\_\_\_\_\_\_\_\_\_\_ - -**PARAGRAPHS:** In order to make Paragraphs, just add <p>. - -<p> Hi there my name is Jason. </p> - -\_\_\_\_\_\_\_\_\_\_\_ - -**TITLES: not the same thing as a heading (which renders on the html page) but instead the title element represents the title of the page as shown in the tab of the browser.** - -<head> - -As such <title>This is the title</title> it is always found between <head> tags and not in the body of the page where all the content that gets rendered on the page is contained. - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*CSqPk3mD0fR-oOAb" class="graf-image" /></figure>### Here's a handy Cheat Sheet: - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*c9Vyer_N97InJsUB.png" class="graf-image" /></figure>Below I am going to Include a gist that contains html code that uses pretty much every tag I could think of off the top of my head… - -If it's not included here I promise you it's seldom used by most webpages. - -Below that I will embed an image of the webpage that it renders too…. - -that super small text at the bottom is actually one giant button: - -<figure><img src="https://cdn-images-1.medium.com/max/2560/1*gdM-6smOEc2ChCI_8_Ql_g.png" class="graf-image" /></figure> - -### If you found this guide helpful feel free to checkout my GitHub/gists where I host similar content: - -<a href="https://gist.github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://gist.github.com/bgoonz"><strong>bgoonz's gists</strong> -<br/> - -<em>Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…</em>gist.github.com</a><a href="https://gist.github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://github.com/bgoonz"><strong>bgoonz — Overview</strong> -<br/> - -<em>Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…</em>github.com</a><a href="https://github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -### Or Checkout my personal Resource Site: - -<a href="https://web-dev-resource-hub.netlify.app/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://web-dev-resource-hub.netlify.app/"><strong>Web-Dev-Hub</strong> -<br/> - -<em>Edit description</em>web-dev-resource-hub.netlify.app</a><a href="https://web-dev-resource-hub.netlify.app/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [March 13, 2021](https://medium.com/p/651d695f9bc). - -<a href="https://medium.com/@bryanguner/super-simple-intro-to-html-651d695f9bc" class="p-canonical">Canonical link</a> - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Super-Simple-Intro-To-React.md b/notes/articles/medium/markdown/Super-Simple-Intro-To-React.md deleted file mode 100644 index 2c8fc1b6f8..0000000000 --- a/notes/articles/medium/markdown/Super-Simple-Intro-To-React.md +++ /dev/null @@ -1,414 +0,0 @@ -# Super Simple Intro To React - -This is a basic introduction for those who feel overwhelmed by the vast microcosm that is the React ecosystem! - ---- - -### Super Simple Intro To React - -#### This is a basic introduction for those who feel overwhelmed by the vast microcosm that is the React ecosystem! - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*3wl1cp6IklxaFuBi.gif" class="graf-image" /></figure>### Here's a sandbox for you to practice with: - -<a href="https://codesandbox.io/s/intro-to-react-i72er" class="markup--anchor markup--p-anchor">https://codesandbox.io/s/intro-to-react-i72er</a> - -<a href="https://codesandbox.io/s/intro-to-react-i72er" class="markup--anchor markup--p-anchor">https://codesandbox.io/s/intro-to-react-i72er</a> - -### Introduction to React - -- <span id="714e">Simply a nice library that turns data into DOM.</span> -- <span id="dffd">`Tree Diffing` : Fast comparison and patching of data by comparing the current virtual DOM and new virtual DOM - updating only the pieces that change.</span> -- <span id="d53b">`It's just a tree with some fancy diffing`</span> - -### Create Element - -**From JavaScript To DOM** - -- <span id="9d7c">The `React.createElement` function has the following form:</span> - -<!-- --> - - React.createElement(type, [props], [...children]); - -- <span id="44e8">`Type` : Type of element to create, i.e. a string for an HTML element or a reference to a function or class that is a React component.</span> -- <span id="7359">`Props` : Object that contains data to render the element.</span> -- <span id="5990">`Children` : Children of the element, as many as you want.</span> - -**Creating elements** - -- <span id="03dd">Our rendering goal:</span> - -<!-- --> - - <ul> - <li class="selected"> - <a href="/pets">Pets</a> - </li> - <li> - <a href="/owners">Owners</a> - </li> - </ul> - -- <span id="57a5">There are five tags to create:</span> -- <span id="9d1c">One `ul`</span> -- <span id="30d1">Two `li`</span> -- <span id="dd2d">Two `a`</span> - -> There are certain attributes we want to appear in the DOM for these tags as well: - -- <span id="1bce">Each `li` has a `class` (or `className` in React)</span> -- <span id="19af">Both `a` ele's have `href` attributes</span> -- <span id="5dfe">Also keep in mind the parent child relationships happening between the tags.</span> -- <span id="cb9e">`ul` is the parent of both `li`</span> -- <span id="7a63">Each `li` has an `a` element as a child</span> -- <span id="c0be">Each `a` has a `text content` child</span> - -<!-- --> - - React.createElement( - "ul", - null, - React.createElement( - "li", - { className: "selected" }, - React.createElement("a", { href: "/pets" }, "Pets") - ), - React.createElement( - "li", - null, - React.createElement("a", { href: "/owners" }, "Owners") - ) - ); - -**Converting to virtual DOM** - -- <span id="9df1">After you set up your `React.createElement`, you use `React.render` to take the value returned from cE and a DOM node to insert into the conversion of the real DOM.</span> - -<!-- --> - - // Put the element tree in a variable - const navList = React.createElement( - "ul", - null, - React.createElement( - "li", - { className: "selected" }, - React.createElement("a", { href: "/pets" }, "Pets") - ), - React.createElement( - "li", - null, - React.createElement("a", { href: "/owners" }, "Owners") - ) - ); - - // Get a DOM node for React to render to - const mainElement = document.querySelector("main"); - - // Give React the element tree and the target - ReactDOM.render(navList, mainElement); - -> JS Code => Virtual DOM => Real Dom - -**Updates** - -- <span id="8e8f">If you call React.render a second or multiple times it just checks the existing Virtual DOM and it knows which smaller areas to change.</span> - -**Thinking in Components** - -- <span id="fb8f">Components are pieces of reusable front-end pieces.</span> -- <span id="1f67">Components should be Single Responsibility Principle compliant.</span> - -### Create Element - -`React.createElement Demo` - -- <span id="3f55">Can import non-local dependencies with `import 'package-link'`</span> - -<!-- --> - - const App = () => React.createElement("h1", null, "Hello, Programmers!"); - - const target = document.querySelector("main"); - const app = React.createElement(App, null); - // Give React the element tree and the target - ReactDOM.render(app, target); - -- <span id="74b4">Remember when importing modules from other files you have to denote the file type in the import statement.</span> - -**HTML Original** - - <section class="clue"> - <h1 class="clue__title">Clue$ 268530</h1> - <div class="clue__question"> - 2009: I dreamed a Dream - </div> - <div class="clue__category"> - <<unparsed>> - </div> - <div class="clue__amount"> - $800 - </div> - </section> - -**React Version** - - const Clue = () => - React.createElement( - "section", - { className: "clue" }, - React.createElement("h1", { className: "clue__title" }, "Title"), - React.createElement("div", { className: "clue__question" }, "?"), - React.createElement("div", { className: "clue__category" }, "Category"), - React.createElement("div", { className: "clue__amount" }, "$800") - ); - -- <span id="9fe5">Because `class` is a reserved keyword in JS, in React we can use `className` to assign a class to an element.</span> -- <span id="9cb2">Remember the data that goes into createElement: element type, data to pass into the element, and then children.</span> -- <span id="0021">`props` : Properties;</span> -- <span id="bf4e">To handle certain values that are initially undefined, we can use `defaultProps`.</span> - -<!-- --> - - Clue.defaultProps = { - category: {}, - }; - -- <span id="6dcb">You can change in the devTools Network tab the internet speed to check for values that may be undefined to hangle with defaultProps.</span> -- <span id="5608">If we fetch multiple pieces of data, we can render many things by using `map`.</span> -- <span id="3ad4">You need to assign a unique key to each of the clues.</span> -- <span id="8b0d">We need to keep track of them individually so that React can easily refer to a specific one if there is an issue. - `clue => { key:clue.id, ...clue }`</span> - -<!-- --> - - const App = (props) => - React.createElement( - "h1", - null, - props.clues.map((clue) => - React.createElement(Clue, { key: clue.id, ...clue }) - ) - ); - - export default App; - -- <span id="0eb5">Note: JSX is preferred over React.createElement;</span> - -### Notes from Hello Programmer Exercise - -- <span id="6f06">When you import modules from websites they must have CORs activated.</span> -- <span id="5934">These import statements, import `global variables`.</span> -- <span id="905d">When we want to move our code into production we need to change the imports into the production minified versions.</span> - -<!-- --> - - import "https://unpkg.com/react@16/umd/react.production.min.js"; - import "https://unpkg.com/react-dom@16.13.1/umd/react-dom.production.min.js"; - -- <span id="33ca">While we will never actually be creating full apps with just React.createElement => it is the enginer that is running under the hood!</span> - -<!-- --> - - import "https://unpkg.com/react@16/umd/react.development.js"; - import "https://unpkg.com/react-dom@16/umd/react-dom.development.js"; - - const Links = () => - React.createElement( - "ul", - { id: "nav-links" }, - React.createElement( - "li", - { className: "is-selected" }, - React.createElement("a", { href: "https://bgoonz-blog.netlify.app/" }, "BgoonzBlog2.0") - ), - React.createElement( - "li", - null, - React.createElement("a", { href: "https://github.com/bgoonz/" }, "Github") - ) - ); - - // Set up React Element: Type, Imported Data, Child (Child is Text in this Scenario) - // HelloWorld is a function based component - const HelloWorld = () => React.createElement("h1", null, "Hello, Programmers"); - - const AllTogether = () => - React.createElement( - "div", - null, - React.createElement(HelloWorld, null), - React.createElement(Links, null) - ); - - // Target the Element to append new Ele - const target = document.querySelector("main"); - - // Assign your 'App' to your created Elements - // We are creating an element from the HelloWorld function. - const app = React.createElement(AllTogether, null); - - // Render from the Virtual Dom to the Actual Dom - ReactDOM.render(app, target); - -### Introduction to JSX - -- <span id="f398">`JSX` : Javascript Extension, a new language created by React developers to have an easier way of interacting with the React API.</span> - -**How to use JSX** - -- <span id="1e31">We will use `babel` to convert version of modern JS into an older version of JS. - **React Create Element**</span> - -<!-- --> - - const ExampleComponent = (props) => - React.createElement( - React.Fragment, - null, - React.createElement("h1", null, "Hello!"), - React.createElement("img", { src: "https://via.placeholder.com/150" }), - React.createElement("a", { href: props.searchUrl }, props.searchText) - ); - -**JSX Version** - - const ExampleComponent = (props) => ( - <React.Fragment> - <h1>Hello!</h1> - <img src="https://via.placeholder.com/150" /> - <a href={props.searchUrl}>{props.searchText}</a> - </React.Fragment> - ); - -- <span id="e8e0">Keep in mind that self closing tags in React must have a `forward slash` to close it.</span> - -### **Properties and Data** - - <img src="https://via.placeholder.com/150" />; - // becomes.. - React.createElement("img", { src: "https://via.placeholder.com/150" }); - // if we want to pass in data vs just a string literal - <a href={props.searchUrl}>{props.searchText}</a>; - // so it becomes.. - React.createElement("a", { href: props.searchUrl }, props.searchText); - // if you want the text search uppercase.. - <a href={props.searchUrl}>{props.searchText.toUpperCase()}</a>; - -- <span id="8780">Comments in JSX have the following syntax:</span> - -<!-- --> - - <div> - <h2>This is JSX</h2> - {/* This is a comment in JSX */} - </div> - -#### `Property Names`: - -- <span id="fcde">`checked` : Attribute of input components such as checkbox or radio, use it to set whether the component is checked or not.</span> -- <span id="ae4c">`className` : Used to specify a CSS class.</span> -- <span id="2d7b">`dangerouslySetInnerHTML` : React's equivalent of innerHTML because it is risky to cross-site scripting attacks.</span> -- <span id="5f13">`htmlFor` : Because `for` is protected keyword, React elements use this instead.</span> -- <span id="5880">`onChange` : Event fired whenever a form field is changed.</span> -- <span id="fb2b">`style` : Accepts a JS object with camelCase properties rather than a CSS string.</span> -- <span id="8f1c">`value` : Supported by Input, Select, and TextArea components; use it to set the value of the component.</span> - -> **_Note: React uses camel-case!!!_** - -#### **The JSX semicolon gotcha** - -- <span id="3d60">We wrap what want to return in parenthesis so JS doesn't auto add semi-colons after every line and run the code incorrectly.</span> - -<!-- --> - - function App() { - return ( - <div> - <h1>Hello!</h1> - <div>Welcome to JSX.</div> - </div> - ); - } - -#### **create Element equivalent** - - is equivalent to - - function App() { - return ( - React.createElement( - 'div', - null, - React.createElement('h1', null, 'Hello!'), - React.createElement('div', null, 'Welcome to JSX.'), - ) - ); - } - -- <span id="6898">Just remember if you decided to use the return keyword in a function to 'return some JSX', then make sure you wrap the JSX in parenthesis.</span> - ---- - -`npx create-react-app my-app` - -- <span id="a3ca">Single line used to initiate a React application.</span> -- <span id="61c5">React has a great toolchain where you can see changes live as you're editing your application.</span> -- <span id="4889">React errors will be rendered directly onto the browser window.</span> -- <span id="f917">A downside is that it installs a lot of bloat files.</span> -- <span id="bdd9">Examples of React create Element and JSX equivalent</span> - -<!-- --> - - React.createElement( - "a", - { - className: "active", - href: "https://github.com/bgoonz/", - }, - "Github" - ); - // JSX Version - <a className="active" href="https://github.com/bgoonz/"> - Github - </a>; - - React.createElement( - OwnerDetails, - { - owner: props.data.owner, - number: props.index + 1, - }, - props.name - ); - // JSX Version - <OwnerDetails owner={props.data.owner} number={props.index + 1}> - {props.name} - </OwnerDetails>; - -**More Complex JSX Example** - - const BookPanel = (props) => { - <section className="book" id={`book-${props.id}`}> - <h1 className="book__title">{props.title}</h1> - <img src={props.coverUrl} /> - <div className="book__desc">{props.description}</div> - </section>; - }; - -### My Blog: - -<a href="https://master--bgoonz-blog.netlify.app/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://master--bgoonz-blog.netlify.app/"><strong>Web-Dev-Hub</strong> -<br/> - -<em>Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…</em>master--bgoonz-blog.netlify.app</a><a href="https://master--bgoonz-blog.netlify.app/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -### Here are the React Docs In One Markdown File: - -<a href="https://gist.github.com/bgoonz/690d80b4f8ac5d359274d98cae87366a" class="markup--anchor markup--p-anchor">https://gist.github.com/bgoonz/690d80b4f8ac5d359274d98cae87366a</a> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [August 22, 2021](https://medium.com/p/5c78e4207b7f). - -<a href="https://medium.com/@bryanguner/super-simple-intro-to-react-5c78e4207b7f" class="p-canonical">Canonical link</a> - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Super-Simple-Intro-To.md b/notes/articles/medium/markdown/Super-Simple-Intro-To.md deleted file mode 100644 index 0de2245e91..0000000000 --- a/notes/articles/medium/markdown/Super-Simple-Intro-To.md +++ /dev/null @@ -1,238 +0,0 @@ -# Super Simple Intro To HTML - -What is HTML, CSS & JS and why do we need all three? - ---- - -### Super Simple Intro To HTML - -#### What is HTML, CSS & JS and why do we need all three? - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*KxF-AuqgX7UklUa4.png" class="graf-image" /></figure>HTML stands for "Hypertext Markup Language". Basically, HTML is the structure for the website, words, bullet points, data tables, etc. CSS stands for "Cascading Style Sheets" which means it's the "Style" it's how to make your website look professional, and look visually appealing. JS is how to make your website actually \*\*work\*\*. - -For example, if you created something like YouTube and one of the options you can watch videos, you used HTML for the title, you used CSS for the color/s, and you have to make it actually work! So when you click on it it will run the video. This is an example of the three programming languages working in unison to form an experience you're already familiar with if you're reading this… - -**I mean most likely… unless you printed it because you hate trees.** - -— — — — — — — — — — - - -### What are Tags and Attributes? - -Tags and attributes are the basis of HTML. - -They work together but perform different functions — it is worth investing 2 minutes in **differentiating the two**. - -#### What Are HTML Tags? - -<a href="https://html.com/tags/" class="markup--anchor markup--p-anchor">Tags</a> are used to **mark up the start of an HTML element** and they are usually enclosed in angle brackets. An example of a tag is: `<h1>`. - -Most tags must be opened `<h1>` and closed `</h1>` in order to function. - -#### What are HTML Attributes? - -<a href="https://html.com/attributes/" class="markup--anchor markup--p-anchor">Attributes</a> contain **additional pieces of information**. Attributes take the form of an opening tag and additional info is **placed inside**. - -An example of an attribute is: - -`<img src="mydog.jpg" alt="A photo of my dog.">` - -In this instance, the image source (src) and the alt text (alt) are attributes of the `<img>` tag. - -#### Golden Rules To Remember - -1. <span id="e12a">The vast majority of tags must be **opened** (`<tag>`) and **closed** (`</tag>`) with the element information such as a title or text resting between the tags.</span> -2. <span id="c99f">When using multiple tags, the tags must be **closed in the order in which they were opened**. For example:</span> -3. <span id="9eb5">`<strong><em>This is really important!</em></strong>`</span> - -Let's have a look at how CodePen works, firstly, you need to go to their website. After that, you must create an account. After you do that, You will see something like this - -### How to get started - -If you're using Visual Studio Code, congrats! There is Emmet support built into VSCode, so you won't need to install any extensions. If you're working in Atom you'll need to install the Emmet plugin, which can be <a href="https://atom.io/packages/emmet" class="markup--anchor markup--p-anchor">found here</a>. - -### Basic Syntax - -**_HTML Boilerplate_** - -If you've been working in VSCode, you've probably seen Emmet syntax highlighting when working in HTML documents. In my opinion, the most convenient Emmet shortcut is **_html:5_**. This will create an HTML boilerplate, and fill out metadata tags in the head of your document. - - html:5 - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*oDrxfgtO2WE9_Z6d.png" class="graf-image" /></figure>Emmet Abbreviation for different HTML boilerplates. - -**When you see the auto complete as pictured above you can hit tab to auto fill the boilerplate html document.** - -That one small shortcut autogenerates all this metadata and head and body tags: - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*LgiaI-W7QB4mtifR.png" class="graf-image" /></figure>#### Here's some slightly more advanced boilerplate for you to use as a starting point in your projects. - -### HTML Language - -**Chapter 1: Formatting text** - -**Tags in HTML:** Tags are one of the most important parts in an HTML document. (We will get to what HTML document is after we know what tags are). HTML uses some predefined tags which tells the browser about content display property, that is how to display a particular given content. For Example, to create a paragraph, one must use the paragraph tags(<p> </p>) and to insert an image one must use the img tags(<img />). - -There are generally two types of tags in HTML: - -1. <span id="9de4">**Paired tags:** These tags come in pairs. That is they have both opening (< >) and closing(</ >) tags.</span> -2. <span id="4b61">**Singular tags:** These tags do not required to be closed</span> - -> i.e. - - <hr> - <p> The tag above me is a horizontal line that doesn't need a closing tag </p> - -HTML tags have two main types: **block-level** and **inline tags**. - -1. <span id="bd59">Block-level elements take up the full available space and always start a new line in the document. Headings and paragraphs are a great example of block tags.</span> -2. <span id="2479">Inline elements only take up as much space as they need and don't start a new line on the page. They usually serve to format the inner contents of block-level elements. Links and emphasized strings are good examples of inline tags.</span> - -### Block-Level Tags - -The three block level tags every HTML document needs to contain are **<html>**, **<head>**, and **<body>**. - -1. <span id="bd5d">The **<html></html>** tag is the highest level element that encloses every HTML page.</span> -2. <span id="c015">The **<head></head>** tag holds meta information such as the page's title and charset.</span> -3. <span id="5ca8">Finally, the **<body></body>** tag encloses all the content that appears on the page.</span> - -- <span id="7864">Paragraphs are enclosed by **_<p></p>_**, while blockquotes use the **_<blockquote></blockquote>_** tag.</span> -- <span id="82ad">Divisions are bigger content sections that typically contain several paragraphs, images, sometimes blockquotes, and other smaller elements. We can mark them up using the **_<div></div>_** tag. A div element can contain another div tag inside it as well.</span> -- <span id="39c6">You may also use **_<ol></ol>_** tags for ordered lists and **_<ul></ul>_** for unordered ones. Individual list items must be enclosed by the **_<li></li>_** tag. For example, this is how a basic unordered list looks like in HTML:</span> - -1. <span id="e470">**<ul>**</span> -2. <span id="b8c5">**<li>**List item 1**</li>**</span> -3. <span id="3c1d">**<li>**List item 2**</li>**</span> -4. <span id="97b4">**<li>**List item 3**</li>**</span> -5. <span id="b59a">**</ul>**</span> - -### **Structure of an HTML Document** - -An HTML Document is mainly divided into two parts: - -- <span id="0424">**HEAD**: This contains the information about the HTML document. For Example, Title of the page, version of HTML, Meta-Data etc.</span> - -HTML TAG Specifies an html document. The HTML element (or HTML root element) represents the root of an HTML document. All other elements must be descendants of this element. Since the element is the first in a document, it is called the root element. - -Although this tag can be implied, or not required, with HTML, it is required to be opened and closed in XHTML. - -- <span id="83fe">Divisions are bigger content sections that typically contain several paragraphs, images, sometimes blockquotes, and other smaller elements. We can mark them up using the **_<div></div>_** tag. A div element can contain another div tag inside it as well.</span> -- <span id="9d53">You may also use **_<ol></ol>_** tags for ordered lists and **_<ul></ul>_** for unordered ones. Individual list items must be enclosed by the **_<li></li>_** tag. For example, this is how a basic unordered list looks like in HTML:</span> - -1. <span id="4097">**<ul>**</span> -2. <span id="0103">**<li>**List item 1**</li>**</span> -3. <span id="1de2">**<li>**List item 2**</li>**</span> -4. <span id="dad0">**<li>**List item 3**</li>**</span> -5. <span id="592f">**</ul>**</span> - -### Inline Tags - -Many inline tags are used to format text. For example, a **<strong></strong>** tag would render an element in **bold**, whereas _<em></em>_ tags would show it in _italics_. - -Hyperlinks are also inline elements that require **_<a></a>_** tags and **href** attributes to indicate the link's destination: - -1. <span id="f67d">**<a** **href=**"https://example.com/"**>**Click me!**</a>**</span> - -Images are inline elements too. You can add one using **_<img>_** without any closing tag. But you will also need to use the **_src_** attribute to specify the image path, for example: - -1. <span id="3924">**<img** **src=**"/images/example.jpg" **alt=**"Example image"**>**</span> - -#### **BODY**: This contains everything you want to display on the Web Page. - - <body> - - <! — Everything the user sees on the webpage goes here! — ps… this is a comment → - - </body> - -Let us now have a look on the basic structure of HTML. That is the code which is must for every webpage to have: - -**_<!DOCTYPE html>_** - -#### Here is some boilerplate html you can use as a starting point:!!Every Webpage must contain this code.!! - ---- - -### **<!DOCTYPE html>** - ---- - -Below is the complete explanation of each of the tags used in the above piece of HTML code: - -**<!DOCTYPE html>:** This tag is used to tells the HTML version. This currently tells that the version is HTML 5. - -> **_<html>_:** This is called HTML root element and used to wrap all the code. - -> **<head>:** Head tag contains metadata, title, page CSS etc. All the HTML elements that can be used inside the <head> element are: - -> **<body>:** Body tag is used to enclosed all the data which a web page has from texts to links. All of the content that you see rendered in the browser is contained within this element. - -### Bold Text: - -<b> **this is bold** </b> - -<strong> ⇐ this is for strong, emergency emotions. - -\_\_\_\_\_\_\_\_\_\_\_ - -**HEADING/S:** - -_6 types from largest(h1) to smallest (h6)_ - -<h1> <h2> <h3> <h4> <h5> <h6> - -\_\_\_\_\_\_\_\_\_\_\_ - -**ITALICS:** There are two ways to use it, the first one is the <i> tag and the second one is the <em> tag. They both italicize the text<a href="https://emojipedia.org/person-shrugging/" class="markup--anchor markup--p-anchor">🤷</a> - -<i> _this is fancy text that's too good to for us_</i> - -\_\_\_\_\_\_\_\_\_\_\_ - -**PARAGRAPHS:** In order to make Paragraphs, just add <p>. - -<p> Hi there my name is Jason. </p> - -\_\_\_\_\_\_\_\_\_\_\_ - -**TITLES: not the same thing as a heading (which renders on the html page) but instead the title element represents the title of the page as shown in the tab of the browser.** - -<head> - -As such <title>This is the title</title> it is always found between <head> tags and not in the body of the page where all the content that gets rendered on the page is contained. - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*CSqPk3mD0fR-oOAb" class="graf-image" /></figure>### Here's a handy Cheat Sheet: - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*c9Vyer_N97InJsUB.png" class="graf-image" /></figure>Below I am going to Include a gist that contains html code that uses pretty much every tag I could think of off the top of my head… - -If it's not included here I promise you it's seldom used by most webpages. - -Below that I will embed an image of the webpage that it renders too…. - -that super small text at the bottom is actually one giant button: - -<figure><img src="https://cdn-images-1.medium.com/max/2560/1*gdM-6smOEc2ChCI_8_Ql_g.png" class="graf-image" /></figure> - -### If you found this guide helpful feel free to checkout my GitHub/gists where I host similar content: - -<a href="https://gist.github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://gist.github.com/bgoonz"><strong>bgoonz's gists</strong> -<br/> - -<em>Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…</em>gist.github.com</a><a href="https://gist.github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://github.com/bgoonz"><strong>bgoonz — Overview</strong> -<br/> - -<em>Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…</em>github.com</a><a href="https://github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -### Or Checkout my personal Resource Site: - -<a href="https://web-dev-resource-hub.netlify.app/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://web-dev-resource-hub.netlify.app/"><strong>Web-Dev-Hub</strong> -<br/> - -<em>Edit description</em>web-dev-resource-hub.netlify.app</a><a href="https://web-dev-resource-hub.netlify.app/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [March 13, 2021](https://medium.com/p/651d695f9bc). - -<a href="https://medium.com/@bryanguner/super-simple-intro-to-html-651d695f9bc" class="p-canonical">Canonical link</a> - -August 6, 2021. diff --git a/notes/articles/medium/markdown/Thank-you--you-re-far-to-kind-.md b/notes/articles/medium/markdown/Thank-you--you-re-far-to-kind-.md deleted file mode 100644 index 45aa43f3e3..0000000000 --- a/notes/articles/medium/markdown/Thank-you--you-re-far-to-kind-.md +++ /dev/null @@ -1,15 +0,0 @@ -# Thank you, you're far to kind! - -There's a bunch of unpublished articles on my personal blog but it's under construction and so a fair number of them are dysfunctional… - ---- - -Thank you, you're far to kind! You might like this one... depending on what you do in relation to computer science: <a href="https://medium.com/codex/these-are-a-few-of-my-favorite-things-82e8b6e61879" class="markup--anchor markup--p-anchor">https://medium.com/codex/these-are-a-few-of-my-favorite-things-82e8b6e61879</a> - -There's a bunch of unpublished articles on my personal blog but it's under construction and so a fair number of them are dysfunctional, incomplete or even someone else's work just acting as a placeholder until I get around to creating similar content. <a href="https://bgoonz-blog.netlify.app/" class="markup--anchor markup--p-anchor">https://bgoonz-blog.netlify.app/</a> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [July 5, 2021](https://medium.com/p/249be2cc2b3d). - -<a href="https://medium.com/@bryanguner/thank-you-youre-far-to-kind-249be2cc2b3d" class="p-canonical">Canonical link</a> - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Thank-you--you-re-far-to-kind.md b/notes/articles/medium/markdown/Thank-you--you-re-far-to-kind.md deleted file mode 100644 index 4671bfd0a5..0000000000 --- a/notes/articles/medium/markdown/Thank-you--you-re-far-to-kind.md +++ /dev/null @@ -1,15 +0,0 @@ -# Thank you, you're far to kind! - -There's a bunch of unpublished articles on my personal blog but it's under construction and so a fair number of them are dysfunctional… - ---- - -Thank you, you're far to kind! You might like this one... depending on what you do in relation to computer science: <a href="https://medium.com/codex/these-are-a-few-of-my-favorite-things-82e8b6e61879" class="markup--anchor markup--p-anchor">https://medium.com/codex/these-are-a-few-of-my-favorite-things-82e8b6e61879</a> - -There's a bunch of unpublished articles on my personal blog but it's under construction and so a fair number of them are dysfunctional, incomplete or even someone else's work just acting as a placeholder until I get around to creating similar content. <a href="https://bgoonz-blog.netlify.app/" class="markup--anchor markup--p-anchor">https://bgoonz-blog.netlify.app/</a> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [July 5, 2021](https://medium.com/p/249be2cc2b3d). - -<a href="https://medium.com/@bryanguner/thank-you-youre-far-to-kind-249be2cc2b3d" class="p-canonical">Canonical link</a> - -August 6, 2021. diff --git a/notes/articles/medium/markdown/The-Beginner-s-Guide-To-JavaScript.md b/notes/articles/medium/markdown/The-Beginner-s-Guide-To-JavaScript.md deleted file mode 100644 index ba7a84f625..0000000000 --- a/notes/articles/medium/markdown/The-Beginner-s-Guide-To-JavaScript.md +++ /dev/null @@ -1,246 +0,0 @@ -# The Beginner's Guide To JavaScript - -Part 1 - ---- - -### The Beginner's Guide To JavaScript - -#### Part 1 - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*Cg0j-L4ZHN7_5g2In-K-Ew.png" class="graf-image" /></figure> - -### How to learn effectively - -**Learning**: The acquisition of skills and the ability to apply them in the future. - -**What makes an Effective learner?** - -- <span id="8498">They are active listeners.</span> -- <span id="bc0a">They are engaged with the material.</span> -- <span id="99d3">They are receptive of feedback.</span> -- <span id="b615">They are open to difficulty.</span> - -**Why do active learning techniques feel difficult?** - -- <span id="9a75">It feels difficult because you are constantly receiving feedback, and so you are constantly adapting and perfecting the material.</span> - -**Desirable Difficulty** - -- <span id="3c8a">The skills we wish to obtain is often a difficult one.</span> -- <span id="a83e">We want challenging but possible lessons based on current level of skill.</span> - -**Effective learners space their practice** - -- <span id="a7b3">Consistent effort > cramming => for **durable knowledge**</span> - ---- - -#### Here's a REPL to practice with: - -<a href="https://replit.com/@bgoonz/lambda-prep#README.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://replit.com/@bgoonz/lambda-prep#README.html"><strong>lambda-prep</strong> -<br/> - -<em>pre-course-work</em>replit.com</a><a href="https://replit.com/@bgoonz/lambda-prep#README.html" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - ---- - -<a href="https://lambda-prep.netlify.app/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://lambda-prep.netlify.app/"><strong>INTRO@JSWEB</strong> -<br/> - -<em>Resource-sharing-hub</em>lambda-prep.netlify.app</a><a href="https://lambda-prep.netlify.app/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - ---- - -### Hello World - -- <span id="d452">**console.log** : command used to print something onto the screen.</span> -- <span id="99ad">**syntax** : the exact arrangement of the symbols, characters, and keywords in our code.</span> -- <span id="a287">**//** : notation for creating a code comment in JS.</span> -- <span id="e2e6">**code comment** : useful for annotating pieces of code to explain how something works, ignored by computer.</span> - -> **_"Simplicity is prerequisite for reliability." — Edsger W. Dijkstra_** - ---- - -### The Number Data Type - -The **number** data type in JS is used to represent any numerical values, including integers and decimal numbers. - -**Basic Arithmetic Operators** - -Operators are the symbols that perform particular operations. - -- <span id="b0ed">**+** (addition)</span> -- <span id="53d9">**-** (subtraction)</span> -- <span id="93f2">**asterisk** (multiplication)</span> -- <span id="92d8">**/** (division)</span> -- <span id="21c1">**%** (modulo)</span> - -JS evaluates more complex expressions using the general math order of operations aka PEMDAS. - -- <span id="d1a4">**PEMDAS** : Parentheses, Exponents, Multiplication, Division, Modulo, Addition, Subtraction.</span> -- <span id="81a2">_To force a specific order of operation, use the group operator ( ) around a part of the expression._</span> - -**Modulo** : Very useful operation to check divisibility of numbers, check for even & odd, whether a number is prime, and much more! _(Discrete Math concept, circular problems can be solved with modulo)_ - -- <span id="20ad">Whenever you have a smaller number % a larger number, the answer will just be the initial small number.</span> -- <span id="2fbf">`console.log(7 % 10); // => 7;`</span> - ---- - -### The String Data Type - -The **string** data type is a primitive data type that used to represent textual data. - -- <span id="310e">can be wrapped by either **single** or **double** quotation marks, _best to choose one and stick with it for consistency_.</span> -- <span id="664c">If your string contains quotation marks inside, can layer single or double quotation marks to allow it to work.</span> -- <span id="46e7">`"That's a great string"; (valid)`</span> -- <span id="4667">`'Shakespeare wrote, "To be or not to be"'; (valid)`</span> -- <span id="9674">`'That's a bad string'; (invalid)`</span> -- <span id="74cb">Alt. way to add other quotes within strings is to use template literals.</span> -- <span id="caf5">`` `This is a temp'l'ate literal ${function}` // use ${} to invoke functions within. ``</span> -- <span id="9144">**.length** : property that can be appended to data to return the length.</span> -- <span id="afa8">empty strings have a length of zero.</span> -- <span id="69ac">**indices** : indexes of data that begin at 0, can call upon index by using the bracket notation \[ \].</span> - -`console.log("bootcamp"[0]); // => "b"` - -`console.log("bootcamp"[10]); // => "undefined"` - -`console.log("boots"[1 * 2]); // => "o"` - -`console.log("boots"["boot".length - 1]); // => "t"` - -- <span id="cb8b">we can pass expressions through the brackets as well since JS always evaluates expressions first.</span> -- <span id="a30f">The index of the last character of a string is always one less than it's length.</span> -- <span id="3080">**indexOf()** : method used to find the first index of a given character within a string.</span> -- <span id="442d">`console.log("bagel".indexOf("b")); // => 0 console.log("bagel".indexOf("z")); // => -1`</span> -- <span id="7ddd">if the character inside the indexOf() search does not exist in the string, the output will be -1.</span> -- <span id="7e6a">the indexOf() search will return the first instanced index of the the char in the string.</span> -- <span id="8729">**concatenate** : word to describe joining strings together into a single string.</span> - ---- - -### The Boolean Data Type - -The **boolean** data type is the simplest data type since there are only two values: **true** and **false**. - -- <span id="fcde">**Logical Operators** (B*oolean Operators*) are used to establish logic in our code.</span> -- <span id="bd34">**!** (not) : reverses a boolean value.</span> -- <span id="bdba">`console.log(!true); // => false console.log(!!false); // => false`</span> -- <span id="cc27">**&&** (and) **Truth Table**</span> - -<figure><img src="https://cdn-images-1.medium.com/max/800/1*Aw4iCm7-FQ7znEcBVH3FTw.png" class="graf-image" /></figure>- <span id="a087">**Logical Order of Operations** : JS will evaluate !, then &&, then ||.</span> -- <span id="295f">**De Morgan's Law** : Common mistake in boolean logic is incorrectly distributing ! across parentheses.</span> -- <span id="7400">`!(A || B) === !A && !B; !(A && B) === !A || !B;`</span> -- <span id="26c2">In summary, to correctly distribute ! across parentheses we must also flip the operation within.</span> -- <span id="a8c1">**Short-Circuit Evaluation** : Because JS evalutes from left to right, expressions can "short-circuit". For example if we have true on the left of an || logical comparison, it will stop evaluating and yield true instead of wasting resources on processing the rest of the statement.</span> -- <span id="58a3">`console.log(true || !false); // => stops after it sees "true ||"`</span> - ---- - -### Comparison Operators - -All comparison operators will result in a boolean output. - -**The relative comparators** - -- <span id="0e52">**>** (greater than)</span> -- <span id="f979">**<** (less than)</span> -- <span id="73da">**>=** (greater than or equal to)</span> -- <span id="1620">**<=** (less than or equal to)</span> -- <span id="fb41">**===** (equal to)</span> -- <span id="0fd1">**!==** (not equal to)</span> - -> _Fun Fact: "a" < "b" is considered valid JS Code because string comparisons are compared lexicographically (meaning dictionary order), so "a" is less than "b" because it appears earlier!_ - -> _If there is ever a standstill comparison of two string lexicographically (i.e. app vs apple) the comparison will deem the shorter string lesser._ - -**Difference between == and ===** - -- <span id="8cc0">**===** : Strict Equality, will only return true if the two comparisons are entirely the same.</span> -- <span id="b25c">**==** : Loose Equality, will return true even if the values are of a different type, due to coercion. (Avoid using this)</span> - ---- - -### Variables - -Variables are used to store information to be referenced and manipulated in a program. - -- <span id="e2b7">We initialize a variable by using the **let** keyword and a **=** single equals sign (assignment operator).</span> -- <span id="e03b">`let bootcamp = "Lambda"; console.log(bootcamp); // "Lambda"`</span> -- <span id="2e71">JS variable names can contain any alphanumeric characters, underscores, or dollar signs (cannot being with a number).</span> -- <span id="6ab7">If you do not declare a value for a variable, undefined is automatically set.</span> -- <span id="0c6f">`let bootcamp; console.log(bootcamp); // undefined`</span> -- <span id="1f9a">We can change the value of a previously declared variable (let, not const) by re-assigning it another value.</span> -- <span id="9e00">**let** is the updated version of **var**; there are some differences in terms of hoisting and global/block scope — will be covered later in the course (common interview question!)</span> - -**Assignment Shorthand** - - let num = 0; - num += 10; // same as num = num + 10 - num -= 2; // same as num = num - 2 - num /= 4; // same as num = num / 4 - num *= 7; // same as num = num * 7 - -- <span id="ab22">In general, any nonsensical arithmetic will result in **NaN** ; usually operations that include undefined.</span> -- <span id="22c2">**declaration** : process of simply introducing a variable name.</span> -- <span id="caeb">**initialization** : process of both declaring and assigning a variable on the same line.</span> - ---- - -### Functions - -A function is a procedure of code that will run when called. Functions are used so that we do not have to rewrite code to do the same thing over and over. (Think of them as 'subprograms') - -- <span id="4c89">**Function Declaration** : Process when we first initially write our function.</span> -- <span id="d3fe">Includes three things:</span> -- <span id="b57c">Name of the function.</span> -- <span id="dfea">A list of _parameters_ ()</span> -- <span id="da88">The code to execute {}</span> -- <span id="8eb3">**Function Calls** : We can call upon our function whenever and wherever\* we want. (\*wherever is only after the initial declaration)</span> -- <span id="cb1d">JS evaluates code top down, left to right.</span> -- <span id="9cb4">When we execute a declared function later on in our program we refer to this as **invoking** our function.</span> -- <span id="fde3">Every function in JS returns undefined unless otherwise specified.</span> -- <span id="059e">When we hit a **return** statement in a function we immediately exit the function and return to where we called the function.</span> -- <span id="d906">When naming functions in JS always use camelCase and name it something appropriate. > Greate code reads like English and almost explains itself. Think: Elegant, readable, and maintainable!</span> - ---- - -### Parameters and Arguments - -- <span id="eb19">**Parameters** : Comma seperated variables specified as part of a function's declaration.</span> -- <span id="6abb">**Arguments** : Values passed to the function when it is invoked.</span> -- <span id="ab31">_If the number of arguments passed during a function invocation is different than the number of parameters listed, it will still work._</span> -- <span id="12ee">However, is there are not enough arguments provided for parameters our function will likely yield **Nan**.</span> - -#### Further resources: - -<strong>A list of all of my articles to link to future posts</strong> -<br/> - -<em>You should probably skip this one… seriously it's just for internal use!</em> - -<a href="https://gist.github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://gist.github.com/bgoonz"><strong>bgoonz's gists</strong> -<br/> - -<em>Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…</em>gist.github.com</a><a href="https://gist.github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://github.com/bgoonz"><strong>bgoonz — Overview</strong> -<br/> - -<em>Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…</em>github.com</a><a href="https://github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://web-dev-resource-hub.netlify.app/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://web-dev-resource-hub.netlify.app/"><strong>Web-Dev-Resource-Hub</strong> -<br/> - -<em>Edit description</em>web-dev-resource-hub.netlify.app</a><a href="https://web-dev-resource-hub.netlify.app/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -_More content at_ <a href="https://plainenglish.io/" class="markup--anchor markup--p-anchor"><strong><em>plainenglish.io</em></strong></a> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [April 4, 2021](https://medium.com/p/e222d166b6e1). - -<a href="https://medium.com/@bryanguner/absolute-beginners-guide-to-javascript-part-1-e222d166b6e1" class="p-canonical">Canonical link</a> - -August 31, 2021. diff --git a/notes/articles/medium/markdown/The-Beginner-s-Guide-To.md b/notes/articles/medium/markdown/The-Beginner-s-Guide-To.md deleted file mode 100644 index 3c3eb697fb..0000000000 --- a/notes/articles/medium/markdown/The-Beginner-s-Guide-To.md +++ /dev/null @@ -1,246 +0,0 @@ -# The Beginner's Guide To JavaScript - -Part 1 - ---- - -### The Beginner's Guide To JavaScript - -#### Part 1 - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*Cg0j-L4ZHN7_5g2In-K-Ew.png" class="graf-image" /></figure> - -### How to learn effectively - -**Learning**: The acquisition of skills and the ability to apply them in the future. - -**What makes an Effective learner?** - -- <span id="8498">They are active listeners.</span> -- <span id="bc0a">They are engaged with the material.</span> -- <span id="99d3">They are receptive of feedback.</span> -- <span id="b615">They are open to difficulty.</span> - -**Why do active learning techniques feel difficult?** - -- <span id="9a75">It feels difficult because you are constantly receiving feedback, and so you are constantly adapting and perfecting the material.</span> - -**Desirable Difficulty** - -- <span id="3c8a">The skills we wish to obtain is often a difficult one.</span> -- <span id="a83e">We want challenging but possible lessons based on current level of skill.</span> - -**Effective learners space their practice** - -- <span id="a7b3">Consistent effort > cramming => for **durable knowledge**</span> - ---- - -#### Here's a REPL to practice with: - -<a href="https://replit.com/@bgoonz/lambda-prep#README.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://replit.com/@bgoonz/lambda-prep#README.html"><strong>lambda-prep</strong> -<br/> - -<em>pre-course-work</em>replit.com</a><a href="https://replit.com/@bgoonz/lambda-prep#README.html" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - ---- - -<a href="https://lambda-prep.netlify.app/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://lambda-prep.netlify.app/"><strong>INTRO@JSWEB</strong> -<br/> - -<em>Resource-sharing-hub</em>lambda-prep.netlify.app</a><a href="https://lambda-prep.netlify.app/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - ---- - -### Hello World - -- <span id="d452">**console.log** : command used to print something onto the screen.</span> -- <span id="99ad">**syntax** : the exact arrangement of the symbols, characters, and keywords in our code.</span> -- <span id="a287">**//** : notation for creating a code comment in JS.</span> -- <span id="e2e6">**code comment** : useful for annotating pieces of code to explain how something works, ignored by computer.</span> - -> **_"Simplicity is prerequisite for reliability." — Edsger W. Dijkstra_** - ---- - -### The Number Data Type - -The **number** data type in JS is used to represent any numerical values, including integers and decimal numbers. - -**Basic Arithmetic Operators** - -Operators are the symbols that perform particular operations. - -- <span id="b0ed">**+** (addition)</span> -- <span id="53d9">**-** (subtraction)</span> -- <span id="93f2">**asterisk** (multiplication)</span> -- <span id="92d8">**/** (division)</span> -- <span id="21c1">**%** (modulo)</span> - -JS evaluates more complex expressions using the general math order of operations aka PEMDAS. - -- <span id="d1a4">**PEMDAS** : Parentheses, Exponents, Multiplication, Division, Modulo, Addition, Subtraction.</span> -- <span id="81a2">_To force a specific order of operation, use the group operator ( ) around a part of the expression._</span> - -**Modulo** : Very useful operation to check divisibility of numbers, check for even & odd, whether a number is prime, and much more! _(Discrete Math concept, circular problems can be solved with modulo)_ - -- <span id="20ad">Whenever you have a smaller number % a larger number, the answer will just be the initial small number.</span> -- <span id="2fbf">`console.log(7 % 10); // => 7;`</span> - ---- - -### The String Data Type - -The **string** data type is a primitive data type that used to represent textual data. - -- <span id="310e">can be wrapped by either **single** or **double** quotation marks, _best to choose one and stick with it for consistency_.</span> -- <span id="664c">If your string contains quotation marks inside, can layer single or double quotation marks to allow it to work.</span> -- <span id="46e7">`"That's a great string"; (valid)`</span> -- <span id="4667">`'Shakespeare wrote, "To be or not to be"'; (valid)`</span> -- <span id="9674">`'That's a bad string'; (invalid)`</span> -- <span id="74cb">Alt. way to add other quotes within strings is to use template literals.</span> -- <span id="caf5">`` `This is a temp'l'ate literal ${function}` // use ${} to invoke functions within. ``</span> -- <span id="9144">**.length** : property that can be appended to data to return the length.</span> -- <span id="afa8">empty strings have a length of zero.</span> -- <span id="69ac">**indices** : indexes of data that begin at 0, can call upon index by using the bracket notation \[ \].</span> - -`console.log("bootcamp"[0]); // => "b"` - -`console.log("bootcamp"[10]); // => "undefined"` - -`console.log("boots"[1 * 2]); // => "o"` - -`console.log("boots"["boot".length - 1]); // => "t"` - -- <span id="cb8b">we can pass expressions through the brackets as well since JS always evaluates expressions first.</span> -- <span id="a30f">The index of the last character of a string is always one less than it's length.</span> -- <span id="3080">**indexOf()** : method used to find the first index of a given character within a string.</span> -- <span id="442d">`console.log("bagel".indexOf("b")); // => 0 console.log("bagel".indexOf("z")); // => -1`</span> -- <span id="7ddd">if the character inside the indexOf() search does not exist in the string, the output will be -1.</span> -- <span id="7e6a">the indexOf() search will return the first instanced index of the the char in the string.</span> -- <span id="8729">**concatenate** : word to describe joining strings together into a single string.</span> - ---- - -### The Boolean Data Type - -The **boolean** data type is the simplest data type since there are only two values: **true** and **false**. - -- <span id="fcde">**Logical Operators** (B*oolean Operators*) are used to establish logic in our code.</span> -- <span id="bd34">**!** (not) : reverses a boolean value.</span> -- <span id="bdba">`console.log(!true); // => false console.log(!!false); // => false`</span> -- <span id="cc27">**&&** (and) **Truth Table**</span> - -<figure><img src="https://cdn-images-1.medium.com/max/800/1*Aw4iCm7-FQ7znEcBVH3FTw.png" class="graf-image" /></figure>- <span id="a087">**Logical Order of Operations** : JS will evaluate !, then &&, then ||.</span> -- <span id="295f">**De Morgan's Law** : Common mistake in boolean logic is incorrectly distributing ! across parentheses.</span> -- <span id="7400">`!(A || B) === !A && !B; !(A && B) === !A || !B;`</span> -- <span id="26c2">In summary, to correctly distribute ! across parentheses we must also flip the operation within.</span> -- <span id="a8c1">**Short-Circuit Evaluation** : Because JS evalutes from left to right, expressions can "short-circuit". For example if we have true on the left of an || logical comparison, it will stop evaluating and yield true instead of wasting resources on processing the rest of the statement.</span> -- <span id="58a3">`console.log(true || !false); // => stops after it sees "true ||"`</span> - ---- - -### Comparison Operators - -All comparison operators will result in a boolean output. - -**The relative comparators** - -- <span id="0e52">**>** (greater than)</span> -- <span id="f979">**<** (less than)</span> -- <span id="73da">**>=** (greater than or equal to)</span> -- <span id="1620">**<=** (less than or equal to)</span> -- <span id="fb41">**===** (equal to)</span> -- <span id="0fd1">**!==** (not equal to)</span> - -> _Fun Fact: "a" < "b" is considered valid JS Code because string comparisons are compared lexicographically (meaning dictionary order), so "a" is less than "b" because it appears earlier!_ - -> _If there is ever a standstill comparison of two string lexicographically (i.e. app vs apple) the comparison will deem the shorter string lesser._ - -**Difference between == and ===** - -- <span id="8cc0">**===** : Strict Equality, will only return true if the two comparisons are entirely the same.</span> -- <span id="b25c">**==** : Loose Equality, will return true even if the values are of a different type, due to coercion. (Avoid using this)</span> - ---- - -### Variables - -Variables are used to store information to be referenced and manipulated in a program. - -- <span id="e2b7">We initialize a variable by using the **let** keyword and a **=** single equals sign (assignment operator).</span> -- <span id="e03b">`let bootcamp = "Lambda"; console.log(bootcamp); // "Lambda"`</span> -- <span id="2e71">JS variable names can contain any alphanumeric characters, underscores, or dollar signs (cannot being with a number).</span> -- <span id="6ab7">If you do not declare a value for a variable, undefined is automatically set.</span> -- <span id="0c6f">`let bootcamp; console.log(bootcamp); // undefined`</span> -- <span id="1f9a">We can change the value of a previously declared variable (let, not const) by re-assigning it another value.</span> -- <span id="9e00">**let** is the updated version of **var**; there are some differences in terms of hoisting and global/block scope — will be covered later in the course (common interview question!)</span> - -**Assignment Shorthand** - - let num = 0; - num += 10; // same as num = num + 10 - num -= 2; // same as num = num - 2 - num /= 4; // same as num = num / 4 - num *= 7; // same as num = num * 7 - -- <span id="ab22">In general, any nonsensical arithmetic will result in **NaN** ; usually operations that include undefined.</span> -- <span id="22c2">**declaration** : process of simply introducing a variable name.</span> -- <span id="caeb">**initialization** : process of both declaring and assigning a variable on the same line.</span> - ---- - -### Functions - -A function is a procedure of code that will run when called. Functions are used so that we do not have to rewrite code to do the same thing over and over. (Think of them as 'subprograms') - -- <span id="4c89">**Function Declaration** : Process when we first initially write our function.</span> -- <span id="d3fe">Includes three things:</span> -- <span id="b57c">Name of the function.</span> -- <span id="dfea">A list of _parameters_ ()</span> -- <span id="da88">The code to execute {}</span> -- <span id="8eb3">**Function Calls** : We can call upon our function whenever and wherever\* we want. (\*wherever is only after the initial declaration)</span> -- <span id="cb1d">JS evaluates code top down, left to right.</span> -- <span id="9cb4">When we execute a declared function later on in our program we refer to this as **invoking** our function.</span> -- <span id="fde3">Every function in JS returns undefined unless otherwise specified.</span> -- <span id="059e">When we hit a **return** statement in a function we immediately exit the function and return to where we called the function.</span> -- <span id="d906">When naming functions in JS always use camelCase and name it something appropriate. > Greate code reads like English and almost explains itself. Think: Elegant, readable, and maintainable!</span> - ---- - -### Parameters and Arguments - -- <span id="eb19">**Parameters** : Comma seperated variables specified as part of a function's declaration.</span> -- <span id="6abb">**Arguments** : Values passed to the function when it is invoked.</span> -- <span id="ab31">_If the number of arguments passed during a function invocation is different than the number of parameters listed, it will still work._</span> -- <span id="12ee">However, is there are not enough arguments provided for parameters our function will likely yield **Nan**.</span> - -#### Further resources: - -<strong>A list of all of my articles to link to future posts</strong> -<br/> - -<em>You should probably skip this one… seriously it's just for internal use!</em> - -<a href="https://gist.github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://gist.github.com/bgoonz"><strong>bgoonz's gists</strong> -<br/> - -<em>Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…</em>gist.github.com</a><a href="https://gist.github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://github.com/bgoonz"><strong>bgoonz — Overview</strong> -<br/> - -<em>Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…</em>github.com</a><a href="https://github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://web-dev-resource-hub.netlify.app/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://web-dev-resource-hub.netlify.app/"><strong>Web-Dev-Resource-Hub</strong> -<br/> - -<em>Edit description</em>web-dev-resource-hub.netlify.app</a><a href="https://web-dev-resource-hub.netlify.app/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -_More content at_ <a href="https://plainenglish.io/" class="markup--anchor markup--p-anchor"><strong><em>plainenglish.io</em></strong></a> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [April 4, 2021](https://medium.com/p/e222d166b6e1). - -<a href="https://medium.com/@bryanguner/absolute-beginners-guide-to-javascript-part-1-e222d166b6e1" class="p-canonical">Canonical link</a> - -August 6, 2021. diff --git a/notes/articles/medium/markdown/The-Best-Cloud-Based-Code-Playgrounds-of-2021--Part-1-.md b/notes/articles/medium/markdown/The-Best-Cloud-Based-Code-Playgrounds-of-2021--Part-1-.md deleted file mode 100644 index 36173fef5a..0000000000 --- a/notes/articles/medium/markdown/The-Best-Cloud-Based-Code-Playgrounds-of-2021--Part-1-.md +++ /dev/null @@ -1,183 +0,0 @@ -# The Best Cloud-Based Code Playgrounds of 2021 (Part 1) - -A plethora of front-end code playgrounds have appeared over the years. They offer a convenient way to experiment with client-side code and… - ---- - -### The Best Cloud-Based Code Playgrounds of 2021 (Part 1) - -#### **A plethora of front-end code playgrounds have appeared over the years. They offer a convenient way to experiment with client-side code and teach/share with others without the hassle of configuring a development environment.** - -<figure><img src="https://cdn-images-1.medium.com/max/800/1*oUZy2IkIQGDbkSVQRGCvKQ.png" class="graf-image" /></figure> - ---- - -### Typical features of these online playgrounds include: - -- <span id="3386">**_color-coded HTML, CSS and JavaScript editors_**</span> -- <span id="152b">**_a preview window — many update on the fly without a refresh_**</span> -- <span id="c746">**_HTML pre-processors such as HAML_**</span> -- <span id="bf6f">**_LESS, SASS and Stylus CSS pre-processing_**</span> -- <span id="8093">**_inclusion of popular JavaScript libraries_**</span> -- <span id="b6d5">**_developer consoles and code validation tools_**</span> -- <span id="98e5">**_sharing via a short URL_**</span> -- <span id="e7c5">**_embedding demonstrations in other pages_**</span> -- <span id="2e11">**_code forking_**</span> -- <span id="efa6">**_zero cost (or payment for premium services only)_**</span> -- <span id="782a">**_showing off your coding skills to the world!_**</span> - ---- - -#### The following list is in no particular order and which playground you use is a matter of application and personal taste, they each have their own specialities. - ---- - -### 1.) REPL.IT - -### My personal favorite for it's simplicity, versatility and capabilities. - -### ⚫No downloads, no configs, no setups - -In your browser. Repl.it runs fully in your browser, so you can get started coding in seconds. No more ZIPs, PKGs, DMGs and WTFs. - -> Any OS, any device**_(I'm looking at you chromebook coders)_**. You can use Repl.it on macOS, Windows, Linux, or any other OS . - -### ⚫Clone, commit and push to any GitHub repo. - -Repl from Repo. Get started with any Github repo, right from your browser. Commit and push without touching your terminal. - -### ⚫<a href="https://blog.replit.com/markdown-preview" class="markup--anchor markup--h3-anchor">Markdown Preview</a> - -**>A new but fundamentally important feature** - -### ⚫<a href="https://blog.replit.com/unit-tests" class="markup--anchor markup--h3-anchor">No-setup Unit Testing</a> - -**>Unit testing is a powerful way to verify that code works as intended and creates a quick feedback loop for development & learning. However, setting up a reproducible unit-testing environment is a time-consuming and delicate affair. Repl.it now features zero-setup unit testing!** - -### ⚫<a href="https://blog.replit.com/https" class="markup--anchor markup--h3-anchor">HTTPS by default</a> - -#### In the example below I have 72 solved Javascript Leetcode Problems but REPL.IT can handle almost any language you can think of. - -### Here's another one that contains the Repl.it Docs: - ---- - -### JS-Fiddle - -> <a href="https://jsfiddle.net/" class="markup--anchor markup--blockquote-anchor"><strong><em>jsFiddle</em></strong></a> **_is a cloud-based JavaScript code playground that allows web developers to tweak their code and see the results of this tweaking in real time. The editor supports not only JavaScript and its variants but also HTML and CSS code, and it further supports popular JavaScript frameworks, such as jQuery, AngularJS, ReactiveJS and D3. The ad-supported site is also completely free to use._** - -### ⚫Entering and running code - -> JSFiddle has the notion of panels (or tabs if you switch into the tabbed layout), there are 4 panels, 3 where you can enter code, and 1 to see the result. - -- <span id="0c0b">**HTML** — structure code, no need to add `body` `doctype` `head`, that's added automatically</span> -- <span id="b95b">**CSS** — styles. You can switch pre-pocessor to SCSS</span> -- <span id="1709">**JavaScript** — behavior. There are many frameworks and code pre-processors you can use</span> - -Once you enter code, just hit **Run** in the top actions bar, and the fourth panel with results will appear. - -### ⚫Saving and Forking code - -- <span id="f034">**Save** / **Update** will do what you think, it'll save a new fiddle or update an existing one (and add a version number to it)</span> -- <span id="f634">**Fork** will split out an existing fiddle into a new one, starting with version 0</span> - ---- - -### StackBlitz - -<a href="https://stackblitz.com/" class="markup--anchor markup--p-anchor">StackBlitz</a> - -- <span id="9cf4">**Installs packages ≥5x faster than Yarn & NPM 🔥**</span> -- <span id="d50f">**Reduces the size of** `node_modules` **up to two orders of magnitude 😮**</span> -- <span id="288c">**Has multiple layers of redundancy for production grade reliability** 💪</span> -- <span id="ba5d">**Works _entirely_ within your web browser, enabling lightning fast dev environments ⚡️**</span> - -> Dependencies still slip into the install process as dev & sub-dependencies and are downloaded & extracted all the same, resulting in the infamous black hole known as `node_modules`: - -<figure><img src="https://cdn-images-1.medium.com/max/600/0*-6LsqMPgWtP9NSBl.png" class="graf-image" /></figure>**Dank, relevant meme (pictured Left)** - -**This is the crux of what prevents NPM from working natively in-browser. Resolving, downloading, and extracting the hundreds of megabytes (or gigabytes) typical frontend projects contain in their** `node_modules` **folder is a challenge browsers just aren't well suited for. Additionally, this is also why existing server side solutions to this problem have proven to be** <a href="https://github.com/unpkg/unpkg/issues/35#issuecomment-317128917" class="markup--anchor markup--p-anchor"><strong>slow, unreliable</strong></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/1*sl4vb3fP9-MErkioiCOyKQ.png" class="graf-image" /></figure>### Then just paste the embed code in an iframe and you're good to go! - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*PjhrjtInF1dPudtO.png" class="graf-image" /></figure><a href="https://stackblitz.com/" class="markup--anchor markup--blockquote-anchor"><strong><em>On StackBlitz.com</em></strong></a>**, you can create new projects and get the embed code from the 'Share' dropdown link in the top navigation like so:** - -### Embed Options - -> **_<iframe src="https://stackblitz.com/edit/angular?embed=1"></iframe>_** - -<figure><img src="https://cdn-images-1.medium.com/max/800/1*6QF4ywBOMVFtS_MukRkLKw.png" class="graf-image" /></figure><figure><img src="https://cdn-images-1.medium.com/max/600/1*5ekSGpNwJ28hI9Aog8V4DQ.png" class="graf-image" /></figure>🡩 **Alternatively, you can also use StackBlitz's** <a href="https://developer.stackblitz.com/docs/platform/embedding#open-and-embed-stackblitz-projects" class="markup--anchor markup--blockquote-anchor"><strong>Javascript SDK methods</strong></a> **for easily embedding StackBlitz projects on the page & avoid all the hassles of creating/configuring iframes.** - -<span class="graf-dropCap">H</span>**ere's a sample project of mine, it's a medium clone… _(So Metta)_… feel free to write a post… or don't …but either way … as you can see… Stack Blitz enables you to write serious web applications in a fraction of the time it would take with a conventional setup.** - ---- - -### Glitch - -### ⚫<a href="https://glitch.com/" class="markup--anchor markup--h3-anchor"><strong><em>Glitch</em></strong></a> ** provides two project templates that you can use to start creating your app:** - -1. <span id="9488">**Classic Website**</span> -2. <span id="ff69">**Node.js**</span> - -If you know the type of project that you would like to create, <a href="https://glitch.com/create-project" class="markup--anchor markup--p-anchor">click here to get started!</a> Or keep reading to learn more about the Classic Website and Node.js templates. - -### ⚫**Classic Website** - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*AMVRXebQBuww_n_P.png" class="graf-image" /></figure>The **Classic Website** template is your starting point for creating a **static** website that includes an index.html page and static HTML, JavaScript, and CSS. Just start typing and your work will be live on the internet! Static websites enjoy unlimited uptime too! This means that your website stays on 24/7 without using your <a href="https://glitch.happyfox.com/kb/article/17/#Uptime" class="markup--anchor markup--p-anchor">Project Hours</a>. - -An existing project will be identified by Glitch as a **static** site if it does not contain one of the following files: - -- <span id="69e6">**package.json**</span> -- <span id="fbe0">**requirements.txt**</span> -- <span id="4fe5">**glitch.json**</span> - -### ⚫**Node.js** - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*ppgGuMTHg-YxnImp.png" class="graf-image" /></figure>If you are looking to build a full-stack JavaScript application, choose the **Node.js** template. This template includes both front-end and back-end code using the popular <a href="https://expressjs.com/" class="markup--anchor markup--p-anchor">Express</a> Node.js application framework. - -### ⚫**Here are some other ways to get started on Glitch…** - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*duFOnYTuCHLsfxFi.png" class="graf-image" /></figure>- <span id="4b22">Create an app by <a href="https://glitch.happyfox.com/kb/article/20-can-i-import-code-from-a-github-repository/" class="markup--anchor markup--li-anchor">importing a GitHub repo</a>.</span> -- <span id="dbd9">Build an app that integrates with a popular third-party platform or framework, by remixing <a href="https://glitch.com/create" class="markup--anchor markup--li-anchor">one of these starter templates</a>.</span> - -**Still not sure where to start? Check out these categories of community-built apps for inspiration:** - -- <span id="53a7"><a href="https://glitch.com/@glitch/games" class="markup--anchor markup--li-anchor">Games</a></span> -- <span id="05b5"><a href="https://glitch.com/@glitch/bots" class="markup--anchor markup--li-anchor">Bots</a></span> -- <span id="a9e4"><a href="https://glitch.com/@glitch/music" class="markup--anchor markup--li-anchor">Music</a></span> -- <span id="0d44"><a href="https://glitch.com/@glitch/art" class="markup--anchor markup--li-anchor">Art</a></span> -- <span id="8927"><a href="https://glitch.com/@glitch/tools-for-work" class="markup--anchor markup--li-anchor">Productivity</a></span> -- <span id="7068"><a href="https://glitch.com/@glitch/hardware" class="markup--anchor markup--li-anchor">Hardware</a></span> -- <span id="5dd4"><a href="https://glitch.com/@glitch/building-blocks" class="markup--anchor markup--li-anchor">Building Blocks</a></span> -- <span id="0c79"><a href="https://glitch.com/@glitch/learn-to-code" class="markup--anchor markup--li-anchor">Learn to Code</a></span> - -### Here's a (temporarily) broken version of my personal portfolio .. hosted on glitch - -#### Click 'view app' below to see how it renders - ---- - -### If you found this guide helpful feel free to checkout my GitHub/gists where I host similar content: - -<a href="https://gist.github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://gist.github.com/bgoonz"><strong>bgoonz's gists</strong> -<br/> - -<em>Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…</em>gist.github.com</a><a href="https://gist.github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://github.com/bgoonz"><strong>bgoonz — Overview</strong> -<br/> - -<em>Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…</em>github.com</a><a href="https://github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -### Or Checkout my personal Resource Site: - -<a href="https://web-dev-resource-hub.netlify.app/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://web-dev-resource-hub.netlify.app/"><strong>Web-Dev-Resource-Hub</strong> -<br/> - -<em>Edit description</em>web-dev-resource-hub.netlify.app</a><a href="https://web-dev-resource-hub.netlify.app/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [March 20, 2021](https://medium.com/p/cdae9448db24). - -<a href="https://medium.com/@bryanguner/the-best-cloud-based-code-playgrounds-of-2021-part-1-cdae9448db24" class="p-canonical">Canonical link</a> - -August 31, 2021. diff --git a/notes/articles/medium/markdown/The-Best-Cloud-Based-Code-Playgrounds-of-2021--Part-1.md b/notes/articles/medium/markdown/The-Best-Cloud-Based-Code-Playgrounds-of-2021--Part-1.md deleted file mode 100644 index 44803d7f15..0000000000 --- a/notes/articles/medium/markdown/The-Best-Cloud-Based-Code-Playgrounds-of-2021--Part-1.md +++ /dev/null @@ -1,183 +0,0 @@ -# The Best Cloud-Based Code Playgrounds of 2021 (Part 1) - -A plethora of front-end code playgrounds have appeared over the years. They offer a convenient way to experiment with client-side code and… - ---- - -### The Best Cloud-Based Code Playgrounds of 2021 (Part 1) - -#### **A plethora of front-end code playgrounds have appeared over the years. They offer a convenient way to experiment with client-side code and teach/share with others without the hassle of configuring a development environment.** - -<figure><img src="https://cdn-images-1.medium.com/max/800/1*oUZy2IkIQGDbkSVQRGCvKQ.png" class="graf-image" /></figure> - ---- - -### Typical features of these online playgrounds include: - -- <span id="3386">**_color-coded HTML, CSS and JavaScript editors_**</span> -- <span id="152b">**_a preview window — many update on the fly without a refresh_**</span> -- <span id="c746">**_HTML pre-processors such as HAML_**</span> -- <span id="bf6f">**_LESS, SASS and Stylus CSS pre-processing_**</span> -- <span id="8093">**_inclusion of popular JavaScript libraries_**</span> -- <span id="b6d5">**_developer consoles and code validation tools_**</span> -- <span id="98e5">**_sharing via a short URL_**</span> -- <span id="e7c5">**_embedding demonstrations in other pages_**</span> -- <span id="2e11">**_code forking_**</span> -- <span id="efa6">**_zero cost (or payment for premium services only)_**</span> -- <span id="782a">**_showing off your coding skills to the world!_**</span> - ---- - -#### The following list is in no particular order and which playground you use is a matter of application and personal taste, they each have their own specialities. - ---- - -### 1.) REPL.IT - -### My personal favorite for it's simplicity, versatility and capabilities. - -### ⚫No downloads, no configs, no setups - -In your browser. Repl.it runs fully in your browser, so you can get started coding in seconds. No more ZIPs, PKGs, DMGs and WTFs. - -> Any OS, any device**_(I'm looking at you chromebook coders)_**. You can use Repl.it on macOS, Windows, Linux, or any other OS . - -### ⚫Clone, commit and push to any GitHub repo. - -Repl from Repo. Get started with any Github repo, right from your browser. Commit and push without touching your terminal. - -### ⚫<a href="https://blog.replit.com/markdown-preview" class="markup--anchor markup--h3-anchor">Markdown Preview</a> - -**>A new but fundamentally important feature** - -### ⚫<a href="https://blog.replit.com/unit-tests" class="markup--anchor markup--h3-anchor">No-setup Unit Testing</a> - -**>Unit testing is a powerful way to verify that code works as intended and creates a quick feedback loop for development & learning. However, setting up a reproducible unit-testing environment is a time-consuming and delicate affair. Repl.it now features zero-setup unit testing!** - -### ⚫<a href="https://blog.replit.com/https" class="markup--anchor markup--h3-anchor">HTTPS by default</a> - -#### In the example below I have 72 solved Javascript Leetcode Problems but REPL.IT can handle almost any language you can think of. - -### Here's another one that contains the Repl.it Docs: - ---- - -### JS-Fiddle - -> <a href="https://jsfiddle.net/" class="markup--anchor markup--blockquote-anchor"><strong><em>jsFiddle</em></strong></a> **_is a cloud-based JavaScript code playground that allows web developers to tweak their code and see the results of this tweaking in real time. The editor supports not only JavaScript and its variants but also HTML and CSS code, and it further supports popular JavaScript frameworks, such as jQuery, AngularJS, ReactiveJS and D3. The ad-supported site is also completely free to use._** - -### ⚫Entering and running code - -> JSFiddle has the notion of panels (or tabs if you switch into the tabbed layout), there are 4 panels, 3 where you can enter code, and 1 to see the result. - -- <span id="0c0b">**HTML** — structure code, no need to add `body` `doctype` `head`, that's added automatically</span> -- <span id="b95b">**CSS** — styles. You can switch pre-pocessor to SCSS</span> -- <span id="1709">**JavaScript** — behavior. There are many frameworks and code pre-processors you can use</span> - -Once you enter code, just hit **Run** in the top actions bar, and the fourth panel with results will appear. - -### ⚫Saving and Forking code - -- <span id="f034">**Save** / **Update** will do what you think, it'll save a new fiddle or update an existing one (and add a version number to it)</span> -- <span id="f634">**Fork** will split out an existing fiddle into a new one, starting with version 0</span> - ---- - -### StackBlitz - -<a href="https://stackblitz.com/" class="markup--anchor markup--p-anchor">StackBlitz</a> - -- <span id="9cf4">**Installs packages ≥5x faster than Yarn & NPM 🔥**</span> -- <span id="d50f">**Reduces the size of** `node_modules` **up to two orders of magnitude 😮**</span> -- <span id="288c">**Has multiple layers of redundancy for production grade reliability** 💪</span> -- <span id="ba5d">**Works _entirely_ within your web browser, enabling lightning fast dev environments ⚡️**</span> - -> Dependencies still slip into the install process as dev & sub-dependencies and are downloaded & extracted all the same, resulting in the infamous black hole known as `node_modules`: - -<figure><img src="https://cdn-images-1.medium.com/max/600/0*-6LsqMPgWtP9NSBl.png" class="graf-image" /></figure>**Dank, relevant meme (pictured Left)** - -**This is the crux of what prevents NPM from working natively in-browser. Resolving, downloading, and extracting the hundreds of megabytes (or gigabytes) typical frontend projects contain in their** `node_modules` **folder is a challenge browsers just aren't well suited for. Additionally, this is also why existing server side solutions to this problem have proven to be** <a href="https://github.com/unpkg/unpkg/issues/35#issuecomment-317128917" class="markup--anchor markup--p-anchor"><strong>slow, unreliable</strong></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/1*sl4vb3fP9-MErkioiCOyKQ.png" class="graf-image" /></figure>### Then just paste the embed code in an iframe and you're good to go! - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*PjhrjtInF1dPudtO.png" class="graf-image" /></figure><a href="https://stackblitz.com/" class="markup--anchor markup--blockquote-anchor"><strong><em>On StackBlitz.com</em></strong></a>**, you can create new projects and get the embed code from the 'Share' dropdown link in the top navigation like so:** - -### Embed Options - -> **_<iframe src="https://stackblitz.com/edit/angular?embed=1"></iframe>_** - -<figure><img src="https://cdn-images-1.medium.com/max/800/1*6QF4ywBOMVFtS_MukRkLKw.png" class="graf-image" /></figure><figure><img src="https://cdn-images-1.medium.com/max/600/1*5ekSGpNwJ28hI9Aog8V4DQ.png" class="graf-image" /></figure>🡩 **Alternatively, you can also use StackBlitz's** <a href="https://developer.stackblitz.com/docs/platform/embedding#open-and-embed-stackblitz-projects" class="markup--anchor markup--blockquote-anchor"><strong>Javascript SDK methods</strong></a> **for easily embedding StackBlitz projects on the page & avoid all the hassles of creating/configuring iframes.** - -<span class="graf-dropCap">H</span>**ere's a sample project of mine, it's a medium clone… _(So Metta)_… feel free to write a post… or don't …but either way … as you can see… Stack Blitz enables you to write serious web applications in a fraction of the time it would take with a conventional setup.** - ---- - -### Glitch - -### ⚫<a href="https://glitch.com/" class="markup--anchor markup--h3-anchor"><strong><em>Glitch</em></strong></a> ** provides two project templates that you can use to start creating your app:** - -1. <span id="9488">**Classic Website**</span> -2. <span id="ff69">**Node.js**</span> - -If you know the type of project that you would like to create, <a href="https://glitch.com/create-project" class="markup--anchor markup--p-anchor">click here to get started!</a> Or keep reading to learn more about the Classic Website and Node.js templates. - -### ⚫**Classic Website** - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*AMVRXebQBuww_n_P.png" class="graf-image" /></figure>The **Classic Website** template is your starting point for creating a **static** website that includes an index.html page and static HTML, JavaScript, and CSS. Just start typing and your work will be live on the internet! Static websites enjoy unlimited uptime too! This means that your website stays on 24/7 without using your <a href="https://glitch.happyfox.com/kb/article/17/#Uptime" class="markup--anchor markup--p-anchor">Project Hours</a>. - -An existing project will be identified by Glitch as a **static** site if it does not contain one of the following files: - -- <span id="69e6">**package.json**</span> -- <span id="fbe0">**requirements.txt**</span> -- <span id="4fe5">**glitch.json**</span> - -### ⚫**Node.js** - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*ppgGuMTHg-YxnImp.png" class="graf-image" /></figure>If you are looking to build a full-stack JavaScript application, choose the **Node.js** template. This template includes both front-end and back-end code using the popular <a href="https://expressjs.com/" class="markup--anchor markup--p-anchor">Express</a> Node.js application framework. - -### ⚫**Here are some other ways to get started on Glitch…** - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*duFOnYTuCHLsfxFi.png" class="graf-image" /></figure>- <span id="4b22">Create an app by <a href="https://glitch.happyfox.com/kb/article/20-can-i-import-code-from-a-github-repository/" class="markup--anchor markup--li-anchor">importing a GitHub repo</a>.</span> -- <span id="dbd9">Build an app that integrates with a popular third-party platform or framework, by remixing <a href="https://glitch.com/create" class="markup--anchor markup--li-anchor">one of these starter templates</a>.</span> - -**Still not sure where to start? Check out these categories of community-built apps for inspiration:** - -- <span id="53a7"><a href="https://glitch.com/@glitch/games" class="markup--anchor markup--li-anchor">Games</a></span> -- <span id="05b5"><a href="https://glitch.com/@glitch/bots" class="markup--anchor markup--li-anchor">Bots</a></span> -- <span id="a9e4"><a href="https://glitch.com/@glitch/music" class="markup--anchor markup--li-anchor">Music</a></span> -- <span id="0d44"><a href="https://glitch.com/@glitch/art" class="markup--anchor markup--li-anchor">Art</a></span> -- <span id="8927"><a href="https://glitch.com/@glitch/tools-for-work" class="markup--anchor markup--li-anchor">Productivity</a></span> -- <span id="7068"><a href="https://glitch.com/@glitch/hardware" class="markup--anchor markup--li-anchor">Hardware</a></span> -- <span id="5dd4"><a href="https://glitch.com/@glitch/building-blocks" class="markup--anchor markup--li-anchor">Building Blocks</a></span> -- <span id="0c79"><a href="https://glitch.com/@glitch/learn-to-code" class="markup--anchor markup--li-anchor">Learn to Code</a></span> - -### Here's a (temporarily) broken version of my personal portfolio .. hosted on glitch - -#### Click 'view app' below to see how it renders - ---- - -### If you found this guide helpful feel free to checkout my GitHub/gists where I host similar content: - -<a href="https://gist.github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://gist.github.com/bgoonz"><strong>bgoonz's gists</strong> -<br/> - -<em>Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…</em>gist.github.com</a><a href="https://gist.github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://github.com/bgoonz"><strong>bgoonz — Overview</strong> -<br/> - -<em>Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…</em>github.com</a><a href="https://github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -### Or Checkout my personal Resource Site: - -<a href="https://web-dev-resource-hub.netlify.app/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://web-dev-resource-hub.netlify.app/"><strong>Web-Dev-Resource-Hub</strong> -<br/> - -<em>Edit description</em>web-dev-resource-hub.netlify.app</a><a href="https://web-dev-resource-hub.netlify.app/" class="js-mixtapeImage mixtapeImage mixtapeImage--empty u-ignoreBlock"></a> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [March 20, 2021](https://medium.com/p/cdae9448db24). - -<a href="https://medium.com/@bryanguner/the-best-cloud-based-code-playgrounds-of-2021-part-1-cdae9448db24" class="p-canonical">Canonical link</a> - -August 6, 2021. diff --git a/notes/articles/medium/markdown/The-Complete-JavaScript-Reference-Guide.md b/notes/articles/medium/markdown/The-Complete-JavaScript-Reference-Guide.md deleted file mode 100644 index fde2ea4070..0000000000 --- a/notes/articles/medium/markdown/The-Complete-JavaScript-Reference-Guide.md +++ /dev/null @@ -1,5683 +0,0 @@ -# The Complete JavaScript Reference Guide - -You will want to bookmark this - ---- - -### The Complete JavaScript Reference Guide - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*In5wB-29T0Ud_zs3.jpg" class="graf-image" /></figure>### How to learn effectively - -**Learning**: The acquisition of skills and the ability to apply them in the future. - -**What makes an Effective learner?** - -- <span id="7504">They are active listeners.</span> -- <span id="179b">They are engaged with the material.</span> -- <span id="3193">They are receptive of feedback.</span> -- <span id="17d8">They are open to difficulty.</span> - -**Why do active learning techniques feel difficult?** - -- <span id="7848">It feels difficult because you are constantly receiving feedback, and so you are constantly adapting and perfecting the material.</span> - -**Desirable Difficulty** - -- <span id="67c9">The skills we wish to obtain is often a difficult one.</span> -- <span id="c939">We want challenging but possible lessons based on current level of skill.</span> - -**Effective learners space their practice** - -- <span id="59a4">Consistent effort > cramming => for **durable knowledge**</span> - ---- - -### Getting visual feedback in your programs - -The first command we'll learn in JavaScript is `console.log`. This command is used to _print_ something onto the screen. As we write our first lines of code, we'll be using `console.log` frequently as a way to visually see the output of our programs. Let's write our first program: - - console.log("hello world"); - console.log("how are you?"); - -Executing the program above would print out the following: - - hello world - how are you? - -Nothing too ground breaking here, but pay close attention to the exact way we wrote the program. In particular, notice how we lay out the periods, parentheses, and quotation marks. We'll also terminate lines with semicolons (;). - -> _Depending on how you structure your code, sometimes you'll be able to omit semicolons at the end of lines. For now, you'll want to include them just as we do._ - -### Syntax - -We refer to the exact arrangement of the symbols, characters, and keywords as **syntax**. These details matter — your computer will only be able to "understand" proper JavaScript syntax. A programming language is similar to a spoken language. A spoken language like English has grammar rules that we should follow in order to be understood by fellow speakers. In the same way, a programming language like JavaScript has syntax rules that we ought to follow! - -As you write your first lines of code in this new language, you may make many syntax errors. Don't get frustrated! This is normal — all new programmers go through this phase. Every time we recognize an error in our code, we have an opportunity to reinforce your understanding of correct syntax. Adopt a growth mindset and learn from your mistakes. - -Additionally, one of the best things about programming is that we can get such immediate feedback from our creations. There is no penalty for making a mistake when programming. Write some code, run the code, read the errors, fix the errors, rinse and repeat! - -### Code comments - -Occasionally we'll want to leave **comments** or notes in our code. Commented lines will be ignored by our computer. This means that we can use comments to write plain english or temporarily avoid execution of some JavaScript lines. The proper _syntax_ for writing a comment is to begin the line with double forward slashes (`//`): - - // let's write another program!!! - console.log("hello world"); - - // console.log("how are you?"); - - console.log("goodbye moon"); - -The program above would only print: - - hello world - goodbye moon - -Comments are useful when annotating pieces of code to offer an explanation of how the code works. We'll want to strive to write straightforward code that is self-explanatory when possible, but we can also use comments to add additional clarity. The real art of programming is to write code so elegantly that it is easy to follow. - -**The Number Data Type** - -The **number** data type in JS is used to represent any numerical values, including integers and decimal numbers. - -**Basic Arithmetic Operators** - -Operators are the symbols that perform particular operations. - -- <span id="f533">**+** (addition)</span> -- <span id="5b9f">**-** (subtraction)</span> -- <span id="b98b">**asterisk** (multiplication)</span> -- <span id="9a15">**/** (division)</span> -- <span id="c752">**%** (modulo)</span> - -JS evaluates more complex expressions using the general math order of operations aka PEMDAS. - -- <span id="b6e3">**PEMDAS** : Parentheses, Exponents, Multiplication, Division, Modulo, Addition, Subtraction.</span> -- <span id="9c25">_To force a specific order of operation, use the group operator ( ) around a part of the expression._</span> - -**Modulo** : Very useful operation to check divisibility of numbers, check for even & odd, whether a number is prime, and much more! _(Discrete Math concept, circular problems can be solved with modulo)_ - -- <span id="cf5b">Whenever you have a smaller number % a larger number, the answer will just be the initial small number. - console.log(7 % 10) // => 7;</span> - -**The String Data Type** - -The **string** data type is a primitive data type that used to represent textual data. - -- <span id="e1b0">can be wrapped by either **single** or **double** quotation marks, _best to choose one and stick with it for consistency_.</span> -- <span id="f8ad">If your string contains quotation marks inside, can layer single or double quotation marks to allow it to work. - "That's a great string"; (valid) - 'Shakespeare wrote, "To be or not to be"'; (valid) - 'That's a bad string'; (invalid)</span> -- <span id="b2cb">Alt. way to add other quotes within strings is to use template literals. - \`This is a temp'l'ate literal ${function}\` // use ${} to invoke functions within.</span> -- <span id="7b1a">**.length** : property that can be appended to data to return the length.</span> -- <span id="f633">empty strings have a length of zero.</span> -- <span id="0a07">**indices** : indexes of data that begin at 0, can call upon index by using the bracket notation \[ \]. - console.log("bootcamp"\[0\]); // => "b" - console.log("bootcamp"\[10\]); // => "undefined" - console.log("boots"\[1 \* 2\]); // => "o" - console.log("boots"\["boot".length-1\]); // => "t"</span> -- <span id="6482">we can pass expressions through the brackets as well since JS always evaluates expressions first.</span> -- <span id="e2f5">The index of the last character of a string is always one less than it's length.</span> -- <span id="2271">**indexOf()** : method used to find the first index of a given character within a string. - console.log("bagel".indexOf("b")); // => 0 - console.log("bagel".indexOf("z")); // => -1</span> -- <span id="8d68">if the character inside the indexOf() search does not exist in the string, the output will be -1.</span> -- <span id="d15e">the indexOf() search will return the first instanced index of the the char in the string.</span> -- <span id="a275">**concatenate** : word to describe joining strings together into a single string.</span> - -**The Boolean Data Type** - -The **Boolean** data type is the simplest data type since there are only two values: **true** and **false**. - -- <span id="60da">**Logical Operators** (B*oolean Operators*) are used to establish logic in our code.</span> -- <span id="139b">**!** (not) : reverses a Boolean value. - console.log(!true); // => false - console.log(!!false); // => false</span> -- <span id="e412">**Logical Order of Operations** : JS will evaluate !, then &&, then ||.</span> -- <span id="99ad">**Short-Circuit Evaluation** : Because JS evalutes from left to right, expressions can "short-circuit". For example if we have true on the left of an || logical comparison, it will stop evaluating and yield true instead of wasting resources on processing the rest of the statement. - console.log(true || !false) // => stops after it sees "true ||"</span> - -**Comparison Operators** - -All comparison operators will result in a boolean output. - -**The relative comparators** - -- <span id="6fee">**>** (greater than)</span> -- <span id="0437">**<** (less than)</span> -- <span id="17ff">**>=** (greater than or equal to)</span> -- <span id="b2b4">**<=** (less than or equal to)</span> -- <span id="0c13">**===** (equal to)</span> -- <span id="b73a">**!==** (not equal to)</span> - -Fun Fact: "a" < "b" is considered valid JS Code because string comparisons are compared lexicographically (meaning dictionary order), so "a" is less than "b" because it appears earlier! - -If there is ever a standstill comparison of two string lexicographically (i.e. app vs apple) the comparison will deem the shorter string lesser. - -**Difference between == and ===** - -#### === - -Strict Equality, will only return true if the two comparisons are entirely the same. - -#### == - -Loose Equality, will return true even if the values are of a different type, due to coercion. (Avoid using this) - -**Variables** - -Variables are used to store information to be referenced and manipulated in a program. - -- <span id="c73d">We initialize a variable by using the **let** keyword and a **=** single equals sign (assignment operator). - let bootcamp = "App Academy"; - console.log(bootcamp); // "App Academy"</span> -- <span id="7849">JS variable names can contain any alphanumeric characters, underscores, or dollar signs (cannot being with a number).</span> -- <span id="ad76">If you do not declare a value for a variable, undefined is automatically set. - let bootcamp; - console.log(bootcamp); // undefined</span> -- <span id="2188">We can change the value of a previously declared variable (let, not const) by re-assigning it another value.</span> -- <span id="47ca">**let** is the updated version of **var**; there are some differences in terms of hoisting and global/block scope</span> - -**Assignment Shorthand** - -let num = 0; - num += 10; // same as num = num + 10 - num -= 2; // same as num = num — 2 - num /= 4; // same as num = num / 4 - num \*= 7; // same as num = num \* 7 - -- <span id="9c05">In general, any nonsensical arithmetic will result in **NaN** ; usually operations that include undefined.</span> - -**Functions** - -A function is a procedure of code that will run when called. Functions are used so that we do not have to rewrite code to do the same thing over and over. (Think of them as 'subprograms') - -- <span id="366f">**Function Declaration** : Process when we first initially write our function.</span> -- <span id="676f">Includes three things:</span> -- <span id="80c2">Name of the function.</span> -- <span id="f3a4">A list of _parameters_ ()</span> -- <span id="2b0e">The code to execute {}</span> -- <span id="6879">**Function Calls** : We can call upon our function whenever and wherever\* we want. (\*wherever is only after the initial declaration)</span> -- <span id="8374">JS evaluates code top down, left to right.</span> -- <span id="2687">When we execute a declared function later on in our program we refer to this as **invoking** our function.</span> -- <span id="0c3a">Every function in JS returns undefined unless otherwise specified.</span> -- <span id="4207">When we hit a **return** statement in a function we immediately exit the function and return to where we called the function.</span> -- <span id="e39f">When naming functions in JS always use camelCase and name it something appropriate.</span> - -Greate code reads like English and almost explains itself. Think: Elegant, readable, and maintainable! - -**Parameters and Arguments** - -- <span id="e94e">**Parameters** : Comma seperated variables specified as part of a function's declaration.</span> -- <span id="6740">**Arguments** : Values passed to the function when it is invoked.</span> -- <span id="004c">_If the number of arguments passed during a function invocation is different than the number of paramters listed, it will still work._</span> -- <span id="7da5">However, is there are not enough arguments provided for parameters our function will likely yield **Nan**.</span> - -### Including Comments - -Comments are important because they help other people understand what is going on in your code or remind you if you forgot something yourself. Keep in mind that they have to be marked properly so the browser won't try to execute them. - -In JavaScript you have two different options: - -- <span id="356d">Single-line comments — To include a comment that is limited to a single line, precede it with `//`</span> -- <span id="ee3a">Multi-line comments — In case you want to write longer comments between several lines, wrap it in `/*` and `*/` to avoid it from being executed</span> - -### Variables in JavaScript - -Variables are stand-in values that you can use to perform operations. You should be familiar with them from math class. - -### var, const, let - -You have three different possibilities for declaring a variable in JavaScript, each with their own specialties: - -- <span id="4b29">`var` — The most common variable. It can be reassigned but only accessed within a function. Variables defined with `var` move to the top when the code is executed.</span> -- <span id="d234">`const` — Can not be reassigned and not accessible before they appear within the code.</span> -- <span id="0e3b">`let` — Similar to `const`, the `let` variable can be reassigned but not re-declared.</span> - -### Data Types - -Variables can contain different types of values and data types. You use `=` to assign them: - -- <span id="b276">Numbers — `var age = 23`</span> -- <span id="5571">Variables — `var x`</span> -- <span id="e26c">Text (strings) — `var a = "init"`</span> -- <span id="1312">Operations — `var b = 1 + 2 + 3`</span> -- <span id="9880">True or false statements — `var c = true`</span> -- <span id="335a">Constant numbers — `const PI = 3.14`</span> -- <span id="7221">Objects — `var name = {firstName:"John", lastName:"Doe"}`</span> - -There are more possibilities. Note that variables are case sensitive. That means `lastname` and `lastName` will be handled as two different variables. - -### Objects - -Objects are certain kinds of variables. They are variables that can have their own values and methods. The latter are actions that you can perform on objects. - -var person = { - -firstName:"John", - -lastName:"Doe", - -age:20, - -nationality:"German" - -}; - -### The Next Level: Arrays - -Next up in our JavaScript cheat sheet are arrays. Arrays are part of many different programming languages. They are a way of organizing variables and properties into groups. Here's how to create one in JavaScript: - -var fruit = \["Banana", "Apple", "Pear"\]; - -Now you have an array called `fruit` which contains three items that you can use for future operations. - -### Array Methods - -Once you have created arrays, there are a few things you can do with them: - -- <span id="4e4b">`concat()` — Join several arrays into one</span> -- <span id="5c02">`indexOf()` — Returns the first position at which a given element appears in an array</span> -- <span id="45cd">`join()` — Combine elements of an array into a single string and return the string</span> -- <span id="3a4e">`lastIndexOf()` — Gives the last position at which a given element appears in an array</span> -- <span id="8fbb">`pop()` — Removes the last element of an array</span> -- <span id="28e4">`push()` — Add a new element at the end</span> -- <span id="0be2">`reverse()` — Sort elements in a descending order</span> -- <span id="775e">`shift()` — Remove the first element of an array</span> -- <span id="1063">`slice()` — Pulls a copy of a portion of an array into a new array</span> -- <span id="53fd">`sort()` — Sorts elements alphabetically</span> -- <span id="f551">`splice()` — Adds elements in a specified way and position</span> -- <span id="c46b">`toString()` — Converts elements to strings</span> -- <span id="ef66">`unshift()` —Adds a new element to the beginning</span> -- <span id="4598">`valueOf()` — Returns the primitive value of the specified object</span> - -### Operators - -If you have variables, you can use them to perform different kinds of operations. To do so, you need operators. - -### Basic Operators - -- <span id="5d34">`+` — Addition</span> -- <span id="5fd9">`-` — Subtraction</span> -- <span id="3b13">`*` — Multiplication</span> -- <span id="521a">`/` — Division</span> -- <span id="cf0f">`(...)` — Grouping operator, operations within brackets are executed earlier than those outside</span> -- <span id="bb2a">`%` — Modulus (remainder )</span> -- <span id="e837">`++` — Increment numbers</span> -- <span id="71ea">`--` — Decrement numbers</span> - -### Comparison Operators - -- <span id="a2b0">`==` — Equal to</span> -- <span id="5105">`===` — Equal value and equal type</span> -- <span id="c79c">`!=` — Not equal</span> -- <span id="1f7f">`!==` — Not equal value or not equal type</span> -- <span id="78c3">`>` — Greater than</span> -- <span id="d40b">`<` — Less than</span> -- <span id="081b">`>=` — Greater than or equal to</span> -- <span id="d065">`<=` — Less than or equal to</span> -- <span id="174d">`?` — Ternary operator</span> - -### Logical Operators - -- <span id="cb7b">`&&` — Logical and</span> -- <span id="b1ee">`||` — Logical or</span> -- <span id="96d4">`!` — Logical not</span> - -### Bitwise Operators - -- <span id="8cf7">`&` — AND statement</span> -- <span id="02d5">`|` — OR statement</span> -- <span id="e576">`~` — NOT</span> -- <span id="9c66">`^` — XOR</span> -- <span id="b343">`<<` — Left shift</span> -- <span id="52b1">`>>` — Right shift</span> -- <span id="1b5c">`>>>` — Zero fill right shift</span> - -### Functions - -JavaScript functions are blocks of code that perform a certain task. A basic function looks like this: - -function name(parameter1, parameter2, parameter3) { - -// what the function does - -} - -As you can see, it consists of the `function` keyword plus a name. The function's parameters are in the brackets and you have curly brackets around what the function performs. You can create your own, but to make your life easier - there are also a number of default functions. - -### Outputting Data - -A common application for functions is the output of data. For the output, you have the following options: - -- <span id="a7a7">`alert()` — Output data in an alert box in the browser window</span> -- <span id="0c44">`confirm()` — Opens up a yes/no dialog and returns true/false depending on user click</span> -- <span id="9690">`console.log()` — Writes information to the browser console, good for debugging purposes</span> -- <span id="0d4d">`document.write()` — Write directly to the HTML document</span> -- <span id="16aa">`prompt()` — Creates a dialogue for user input</span> - -### Global Functions - -Global functions are functions built into every browser capable of running JavaScript. - -- <span id="f4f1">`decodeURI()` — Decodes a <a href="https://en.wikipedia.org/wiki/Uniform_Resource_Identifier" class="markup--anchor markup--li-anchor">Uniform Resource Identifier (URI)</a> created by `encodeURI` or similar</span> -- <span id="c203">`decodeURIComponent()` — Decodes a URI component</span> -- <span id="176a">`encodeURI()` — Encodes a URI into UTF-8</span> -- <span id="6720">`encodeURIComponent()` — Same but for URI components</span> -- <span id="e97b">`eval()` — Evaluates JavaScript code represented as a string</span> -- <span id="390b">`isFinite()` — Determines whether a passed value is a finite number</span> -- <span id="5d46">`isNaN()` — Determines whether a value is NaN or not</span> -- <span id="f668">`Number()` —- Returns a number converted from its argument</span> -- <span id="a5ff">`parseFloat()` — Parses an argument and returns a floating-point number</span> -- <span id="a666">`parseInt()` — Parses its argument and returns an integer</span> - -### JavaScript Loops - -Loops are part of most programming languages. They allow you to execute blocks of code desired number of times with different values: - -for (before loop; condition **for** loop; execute after loop) { - -// what to do during the loop - -} - -You have several parameters to create loops: - -- <span id="ff62">`for` — The most common way to create a loop in JavaScript</span> -- <span id="7ad1">`while` — Sets up conditions under which a loop executes</span> -- <span id="c2f4">`do while` — Similar to the `while` loop but it executes at least once and performs a check at the end to see if the condition is met to execute again</span> -- <span id="7157">`break` —Used to stop and exit the cycle at certain conditions</span> -- <span id="f5c0">`continue` — Skip parts of the cycle if certain conditions are met</span> - -### If — Else Statements - -These types of statements are easy to understand. Using them, you can set conditions for when your code is executed. If certain conditions apply, something is done, if not — something else is executed. - -if (condition) { - -// what to do if condition is met - -} **else** { - -// what to do if condition is not met - -} - -A similar concept to `if else` is the `switch` statement. However, using the switch you select one of several code blocks to execute. - -### Strings - -Strings are what JavaScript calls to text that does not perform a function but can appear on the screen. - -var person = "John Doe"; - -In this case, `John Doe` is the string. - -### Escape Characters - -In JavaScript, strings are marked with single or double-quotes. If you want to use quotation marks in a string, you need to use special characters: - -- <span id="b4b1">`\'` — Single quote</span> -- <span id="3b22">`\"` — Double quote</span> - -Aside from that you also have additional escape characters: - -- <span id="b412">`\\` — Backslash</span> -- <span id="1592">`\b` — Backspace</span> -- <span id="3a72">`\f` — Form feed</span> -- <span id="145a">`\n` — New line</span> -- <span id="1416">`\r` — Carriage return</span> -- <span id="95d4">`\t` — Horizontal tabulator</span> -- <span id="d962">`\v` — Vertical tabulator</span> - -### String Methods - -There are many different ways to work with strings: - -- <span id="2021">`charAt()` — Returns a character at a specified position inside a string</span> -- <span id="d3e5">`charCodeAt()` — Gives you the Unicode of a character at that position</span> -- <span id="fdd1">`concat()` — Concatenates (joins) two or more strings into one</span> -- <span id="009c">`fromCharCode()` — Returns a string created from the specified sequence of UTF-16 code units</span> -- <span id="7ed3">`indexOf()` — Provides the position of the first occurrence of a specified text within a string</span> -- <span id="2937">`lastIndexOf()` — Same as `indexOf()` but with the last occurrence, searching backward</span> -- <span id="142d">`match()` — Retrieves the matches of a string against a search pattern</span> -- <span id="6c18">`replace()` — Find and replace specified text in a string</span> -- <span id="e279">`search()` — Executes a search for a matching text and returns its position</span> -- <span id="6bcd">`slice()` — Extracts a section of a string and returns it as a new string</span> -- <span id="e4ee">`split()` — Splits a string object into an array of strings at a specified position</span> -- <span id="3a27">`substr()` — Similar to `slice()` but extracts a substring depending on a specified number of characters</span> -- <span id="3d14">`substring()` — Also similar to `slice()` but can't accept negative indices</span> -- <span id="fa33">`toLowerCase()` — Convert strings to lower case</span> -- <span id="3485">`toUpperCase()` — Convert strings to upper case</span> -- <span id="4f96">`valueOf()` — Returns the primitive value (that has no properties or methods) of a string object</span> - -### Regular Expression Syntax - -Regular expressions are search patterns used to match character combinations in strings. The search pattern can be used for text search and text to replace operations. - -### Pattern Modifiers - -- <span id="bb29">`e` — Evaluate replacement</span> -- <span id="b6b8">`i` — Perform case-insensitive matching</span> -- <span id="4f50">`g` — Perform global matching</span> -- <span id="4add">`m` — Perform multiple line matching</span> -- <span id="a073">`s` — Treat strings as a single line</span> -- <span id="482b">`x` — Allow comments and whitespace in the pattern</span> -- <span id="f6ad">`U` — Ungreedy pattern</span> - -### Brackets - -- <span id="aae1">`[abc]` — Find any of the characters between the brackets</span> -- <span id="e048">`[^abc]` — Find any character which is not in the brackets</span> -- <span id="f9b5">`[0-9]` — Used to find any digit from 0 to 9</span> -- <span id="ac71">`[A-z]` — Find any character from uppercase A to lowercase z</span> -- <span id="6fce">`(a|b|c)` — Find any of the alternatives separated with `|`</span> - -### Metacharacters - -- <span id="dcd6">`.` — Find a single character, except newline or line terminator</span> -- <span id="e944">`\w` — Word character</span> -- <span id="c4bf">`\W` — Non-word character</span> -- <span id="7b81">`\d` — A digit</span> -- <span id="a533">`\D` — A non-digit character</span> -- <span id="1fcc">`\s` — Whitespace character</span> -- <span id="374c">`\S` — Non-whitespace character</span> -- <span id="72d0">`\b` — Find a match at the beginning/end of a word</span> -- <span id="2d38">`\B` — A match not at the beginning/end of a word</span> -- <span id="859b">`\0` — NUL character</span> -- <span id="df4d">`\n` — A new line character</span> -- <span id="5acd">`\f` — Form feed character</span> -- <span id="833f">`\r` — Carriage return character</span> -- <span id="4f31">`\t` — Tab character</span> -- <span id="e618">`\v` — Vertical tab character</span> -- <span id="dcfc">`\xxx` — The character specified by an octal number xxx</span> -- <span id="cf5e">`\xdd` — Character specified by a hexadecimal number dd</span> -- <span id="978f">`\uxxxx` — The Unicode character specified by a hexadecimal number XXXX</span> - -### Quantifiers - -- <span id="e4cf">`n+` — Matches any string that contains at least one n</span> -- <span id="be07">`n*` — Any string that contains zero or more occurrences of n</span> -- <span id="4a93">`n?` — A string that contains zero or one occurrence of n</span> -- <span id="91f0">`n{X}` — String that contains a sequence of X n's</span> -- <span id="097b">`n{X,Y}` — Strings that contain a sequence of X to Y n's</span> -- <span id="e9f2">`n{X,}` — Matches any string that contains a sequence of at least X n's</span> -- <span id="15b3">`n$` — Any string with n at the end of it</span> -- <span id="5fc9">`^n` — String with n at the beginning of it</span> -- <span id="2b42">`?=n` — Any string that is followed by a specific string n</span> -- <span id="6ffa">`?!n` — String that is not followed by a specific string ni</span> - -### Numbers and Math - -In JavaScript, you can also work with numbers, constants and perform mathematical functions. - -### Number Properties - -- <span id="3554">`MAX_VALUE` — The maximum numeric value representable in JavaScript</span> -- <span id="c55d">`MIN_VALUE` — Smallest positive numeric value representable in JavaScript</span> -- <span id="49e0">`NaN` — The "Not-a-Number" value</span> -- <span id="3024">`NEGATIVE_INFINITY` — The negative Infinity value</span> -- <span id="0bf4">`POSITIVE_INFINITY` — Positive Infinity value</span> - -### Number Methods - -- <span id="9478">`toExponential()` — Returns the string with a rounded number written as exponential notation</span> -- <span id="2ad0">`toFixed()` — Returns the string of a number with a specified number of decimals</span> -- <span id="d464">`toPrecision()` — String of a number written with a specified length</span> -- <span id="2244">`toString()` — Returns a number as a string</span> -- <span id="bc1e">`valueOf()` — Returns a number as a number</span> - -### Math Properties - -- <span id="9f68">`E` — Euler's number</span> -- <span id="a4df">`LN2` — The natural logarithm of 2</span> -- <span id="0f06">`LN10` — Natural logarithm of 10</span> -- <span id="1a92">`LOG2E` — Base 2 logarithm of E</span> -- <span id="42e7">`LOG10E` — Base 10 logarithm of E</span> -- <span id="1fbe">`PI` — The number PI</span> -- <span id="2a56">`SQRT1_2` — Square root of 1/2</span> -- <span id="aab4">`SQRT2` — The square root of 2</span> - -### Math Methods - -- <span id="8836">`abs(x)` — Returns the absolute (positive) value of x</span> -- <span id="ddb9">`acos(x)` — The arccosine of x, in radians</span> -- <span id="a0c3">`asin(x)` — Arcsine of x, in radians</span> -- <span id="c2ca">`atan(x)` — The arctangent of x as a numeric value</span> -- <span id="8b93">`atan2(y,x)` — Arctangent of the quotient of its arguments</span> -- <span id="b103">`ceil(x)` — Value of x rounded up to its nearest integer</span> -- <span id="c68a">`cos(x)` — The cosine of x (x is in radians)</span> -- <span id="d480">`exp(x)` — Value of Ex</span> -- <span id="2954">`floor(x)` — The value of x rounded down to its nearest integer</span> -- <span id="ff4d">`log(x)` — The natural logarithm (base E) of x</span> -- <span id="b6a9">`max(x,y,z,...,n)` — Returns the number with the highest value</span> -- <span id="dfb0">`min(x,y,z,...,n)` — Same for the number with the lowest value</span> -- <span id="a6f1">`pow(x,y)` — X to the power of y</span> -- <span id="8851">`random()` — Returns a random number between 0 and 1</span> -- <span id="d32e">`round(x)` — The value of x rounded to its nearest integer</span> -- <span id="fe9a">`sin(x)` — The sine of x (x is in radians)</span> -- <span id="c244">`sqrt(x)` — Square root of x</span> -- <span id="b5ef">`tan(x)` — The tangent of an angle</span> - -### Dealing with Dates in JavaScript - -You can also work with and modify dates and time with JavaScript. This is the next chapter in the JavaScript cheat sheet. - -### Setting Dates - -- <span id="b187">`Date()` — Creates a new date object with the current date and time</span> -- <span id="42f8">`Date(2017, 5, 21, 3, 23, 10, 0)` — Create a custom date object. The numbers represent a year, month, day, hour, minutes, seconds, milliseconds. You can omit anything you want except for a year and month.</span> -- <span id="4e80">`Date("2017-06-23")` — Date declaration as a string</span> - -### Pulling Date and Time Values - -- <span id="465e">`getDate()` — Get the day of the month as a number (1-31)</span> -- <span id="1b08">`getDay()` — The weekday as a number (0-6)</span> -- <span id="6d9e">`getFullYear()` — Year as a four-digit number (yyyy)</span> -- <span id="a216">`getHours()` — Get the hour (0-23)</span> -- <span id="388a">`getMilliseconds()` — The millisecond (0-999)</span> -- <span id="a97f">`getMinutes()` — Get the minute (0-59)</span> -- <span id="2427">`getMonth()` — Month as a number (0-11)</span> -- <span id="b964">`getSeconds()` — Get the second (0-59)</span> -- <span id="505d">`getTime()` — Get the milliseconds since January 1, 1970</span> -- <span id="7c14">`getUTCDate()` — The day (date) of the month in the specified date according to universal time (also available for day, month, full year, hours, minutes etc.)</span> -- <span id="d6b6">`parse` — Parses a string representation of a date and returns the number of milliseconds since January 1, 1970</span> - -### Set Part of a Date - -- <span id="9a97">`setDate()` — Set the day as a number (1-31)</span> -- <span id="d4f0">`setFullYear()` — Sets the year (optionally month and day)</span> -- <span id="1a45">`setHours()` — Set the hour (0-23)</span> -- <span id="8020">`setMilliseconds()` — Set milliseconds (0-999)</span> -- <span id="7feb">`setMinutes()` — Sets the minutes (0-59)</span> -- <span id="d7ca">`setMonth()` — Set the month (0-11)</span> -- <span id="795d">`setSeconds()` — Sets the seconds (0-59)</span> -- <span id="1d7f">`setTime()` — Set the time (milliseconds since January 1, 1970)</span> -- <span id="78e1">`setUTCDate()` — Sets the day of the month for a specified date according to universal time (also available for day, month, full year, hours, minutes etc.)</span> - -### DOM Mode - -The DOM is the <a href="https://en.wikipedia.org/wiki/Document_Object_Model" class="markup--anchor markup--p-anchor">Document Object Model</a> of a page. It is the code of the structure of a webpage. JavaScript comes with a lot of different ways to create and manipulate HTML elements (called nodes). - -### Node Properties - -- <span id="cfb7">`attributes` — Returns a live collection of all attributes registered to an element</span> -- <span id="6138">`baseURI` — Provides the absolute base URL of an HTML element</span> -- <span id="34da">`childNodes` — Gives a collection of an element's child nodes</span> -- <span id="58ec">`firstChild` — Returns the first child node of an element</span> -- <span id="2f34">`lastChild` — The last child node of an element</span> -- <span id="fdea">`nextSibling` — Gives you the next node at the same node tree level</span> -- <span id="1ca4">`nodeName` —Returns the name of a node</span> -- <span id="d4ee">`nodeType` — Returns the type of a node</span> -- <span id="cd22">`nodeValue` — Sets or returns the value of a node</span> -- <span id="a9a3">`ownerDocument` — The top-level document object for this node</span> -- <span id="51b4">`parentNode` — Returns the parent node of an element</span> -- <span id="31ef">`previousSibling` — Returns the node immediately preceding the current one</span> -- <span id="ec40">`textContent` — Sets or returns the textual content of a node and its descendants</span> - -### Node Methods - -- <span id="7f05">`appendChild()` — Adds a new child node to an element as the last child node</span> -- <span id="3b3a">`cloneNode()` — Clones an HTML element</span> -- <span id="661c">`compareDocumentPosition()` — Compares the document position of two elements</span> -- <span id="86d2">`getFeature()` — Returns an object which implements the APIs of a specified feature</span> -- <span id="059c">`hasAttributes()` — Returns true if an element has any attributes, otherwise false</span> -- <span id="5d0d">`hasChildNodes()` — Returns true if an element has any child nodes, otherwise false</span> -- <span id="4c86">`insertBefore()` — Inserts a new child node before a specified, existing child node</span> -- <span id="4b38">`isDefaultNamespace()` — Returns true if a specified namespaceURI is the default, otherwise false</span> -- <span id="8c4e">`isEqualNode()` — Checks if two elements are equal</span> -- <span id="2f6a">`isSameNode()` — Checks if two elements are the same node</span> -- <span id="944e">`isSupported()` — Returns true if a specified feature is supported on the element</span> -- <span id="b7ef">`lookupNamespaceURI()` — Returns the namespace URI associated with a given node</span> -- <span id="5f59">`lookupPrefix()` — Returns a DOMString containing the prefix for a given namespace URI if present</span> -- <span id="6670">`normalize()` — Joins adjacent text nodes and removes empty text nodes in an element</span> -- <span id="c80a">`removeChild()` — Removes a child node from an element</span> -- <span id="8108">`replaceChild()` — Replaces a child node in an element</span> - -### Element Methods - -- <span id="9530">`getAttribute()` — Returns the specified attribute value of an element node</span> -- <span id="0dd1">`getAttributeNS()` — Returns string value of the attribute with the specified namespace and name</span> -- <span id="8a0d">`getAttributeNode()` — Gets the specified attribute node</span> -- <span id="fc41">`getAttributeNodeNS()` — Returns the attribute node for the attribute with the given namespace and name</span> -- <span id="2a3e">`getElementsByTagName()` — Provides a collection of all child elements with the specified tag name</span> -- <span id="11a4">`getElementsByTagNameNS()` — Returns a live HTMLCollection of elements with a certain tag name belonging to the given namespace</span> -- <span id="e2ae">`hasAttribute()` — Returns true if an element has any attributes, otherwise false</span> -- <span id="17dd">`hasAttributeNS()` — Provides a true/false value indicating whether the current element in a given namespace has the specified attribute</span> -- <span id="f28c">`removeAttribute()` — Removes a specified attribute from an element</span> -- <span id="8cd0">`removeAttributeNS()` — Removes the specified attribute from an element within a certain namespace</span> -- <span id="e6c3">`removeAttributeNode()` — Takes away a specified attribute node and returns the removed node</span> -- <span id="a7b9">`setAttribute()` — Sets or changes the specified attribute to a specified value</span> -- <span id="bf42">`setAttributeNS()` — Adds a new attribute or changes the value of an attribute with the given namespace and name</span> -- <span id="2322">`setAttributeNode()` — Sets or changes the specified attribute node</span> -- <span id="0540">`setAttributeNodeNS()` — Adds a new namespaced attribute node to an element</span> - -### Working with the User Browser - -Besides HTML elements, JavaScript is also able to take into account the user browser and incorporate its properties into the code. - -### Window Properties - -- <span id="1b1f">`closed` — Checks whether a window has been closed or not and returns true or false</span> -- <span id="805f">`defaultStatus` — Sets or returns the default text in the status bar of a window</span> -- <span id="458e">`document` — Returns the document object for the window</span> -- <span id="93ee">`frames` — Returns all `<iframe>` elements in the current window</span> -- <span id="c42a">`history` — Provides the History object for the window</span> -- <span id="3a5d">`innerHeight` — The inner height of a window's content area</span> -- <span id="c609">`innerWidth` — The inner width of the content area</span> -- <span id="5167">`length` — Find out the number of `<iframe>` elements in the window</span> -- <span id="4f05">`location` — Returns the location object for the window</span> -- <span id="4125">`name` — Sets or returns the name of a window</span> -- <span id="3d7f">`navigator` — Returns the Navigator object for the window</span> -- <span id="c601">`opener` — Returns a reference to the window that created the window</span> -- <span id="734e">`outerHeight` — The outer height of a window, including toolbars/scrollbars</span> -- <span id="9b0a">`outerWidth` — The outer width of a window, including toolbars/scrollbars</span> -- <span id="3140">`pageXOffset` — Number of pixels the current document has been scrolled horizontally</span> -- <span id="0bcc">`pageYOffset` — Number of pixels the document has been scrolled vertically</span> -- <span id="a2af">`parent` — The parent window of the current window</span> -- <span id="3634">`screen` — Returns the Screen object for the window</span> -- <span id="9566">`screenLeft` — The horizontal coordinate of the window (relative to the screen)</span> -- <span id="1245">`screenTop` — The vertical coordinate of the window</span> -- <span id="5656">`screenX` — Same as `screenLeft` but needed for some browsers</span> -- <span id="21e7">`screenY` — Same as `screenTop` but needed for some browsers</span> -- <span id="d000">`self` — Returns the current window</span> -- <span id="99af">`status` — Sets or returns the text in the status bar of a window</span> -- <span id="0a0f">`top` — Returns the topmost browser window</span> - -### Window Methods - -- <span id="5715">`alert()` — Displays an alert box with a message and an OK button</span> -- <span id="4afc">`blur()` — Removes focus from the current window</span> -- <span id="ef9a">`clearInterval()` — Clears a timer set with `setInterval()`</span> -- <span id="fa72">`clearTimeout()` — Clears a timer set with `setTimeout()`</span> -- <span id="7bce">`close()` — Closes the current window</span> -- <span id="ccbf">`confirm()` — Displays a dialogue box with a message and an _OK_ and _Cancel_ button</span> -- <span id="e6f2">`focus()` — Sets focus to the current window</span> -- <span id="5eb7">`moveBy()` — Moves a window relative to its current position</span> -- <span id="16b6">`moveTo()` — Moves a window to a specified position</span> -- <span id="32d8">`open()` — Opens a new browser window</span> -- <span id="4198">`print()` — Prints the content of the current window</span> -- <span id="3bec">`prompt()` — Displays a dialogue box that prompts the visitor for input</span> -- <span id="e16a">`resizeBy()` — Resizes the window by the specified number of pixels</span> -- <span id="31c8">`resizeTo()` — Resizes the window to a specified width and height</span> -- <span id="6c44">`scrollBy()` — Scrolls the document by a specified number of pixels</span> -- <span id="959f">`scrollTo()` — Scrolls the document to specified coordinates</span> -- <span id="704a">`setInterval()` — Calls a function or evaluates an expression at specified intervals</span> -- <span id="87c3">`setTimeout()` — Calls a function or evaluates an expression after a specified interval</span> -- <span id="1cde">`stop()` — Stops the window from loading</span> - -### Screen Properties - -- <span id="7e50">`availHeight` — Returns the height of the screen (excluding the Windows Taskbar)</span> -- <span id="d7ea">`availWidth` — Returns the width of the screen (excluding the Windows Taskbar)</span> -- <span id="4feb">`colorDepth` — Returns the bit depth of the color palette for displaying images</span> -- <span id="f2f7">`height` — The total height of the screen</span> -- <span id="8e22">`pixelDepth` — The color resolution of the screen in bits per pixel</span> -- <span id="bc5a">`width` — The total width of the screen</span> - -### JavaScript Events - -Events are things that can happen to HTML elements and are performed by the user. The programming language can listen for these events and trigger actions in the code. No JavaScript cheat sheet would be complete without them. - -### Mouse - -- <span id="9546">`onclick` — The event occurs when the user clicks on an element</span> -- <span id="9b50">`oncontextmenu` — User right-clicks on an element to open a context menu</span> -- <span id="147a">`ondblclick` — The user double-clicks on an element</span> -- <span id="3720">`onmousedown` — User presses a mouse button over an element</span> -- <span id="a40a">`onmouseenter` — The pointer moves onto an element</span> -- <span id="345e">`onmouseleave` — Pointer moves out of an element</span> -- <span id="79b1">`onmousemove` — The pointer is moving while it is over an element</span> -- <span id="fa70">`onmouseover` — When the pointer is moved onto an element or one of its children</span> -- <span id="94f8">`onmouseout` — User moves the mouse pointer out of an element or one of its children</span> -- <span id="486e">`onmouseup` — The user releases a mouse button while over an element</span> - -### Keyboard - -- <span id="6a8f">`onkeydown` — When the user is pressing a key down</span> -- <span id="0647">`onkeypress` — The moment the user starts pressing a key</span> -- <span id="ff0f">`onkeyup` — The user releases a key</span> - -### Frame - -- <span id="9d29">`onabort` — The loading of a media is aborted</span> -- <span id="baa4">`onbeforeunload` — Event occurs before the document is about to be unloaded</span> -- <span id="740e">`onerror` — An error occurs while loading an external file</span> -- <span id="be95">`onhashchange` — There have been changes to the anchor part of a URL</span> -- <span id="d0fd">`onload` — When an object has loaded</span> -- <span id="65e5">`onpagehide` — The user navigates away from a webpage</span> -- <span id="aae6">`onpageshow` — When the user navigates to a webpage</span> -- <span id="e3dc">`onresize` — The document view is resized</span> -- <span id="96c8">`onscroll` — An element's scrollbar is being scrolled</span> -- <span id="f2fa">`onunload` — Event occurs when a page has unloaded</span> - -### Form - -- <span id="731a">`onblur` — When an element loses focus</span> -- <span id="facf">`onchange` — The content of a form element changes (for `<input>`, `<select>` and `<textarea>`)</span> -- <span id="7a0a">`onfocus` — An element gets focus</span> -- <span id="5188">`onfocusin` — When an element is about to get focus</span> -- <span id="594a">`onfocusout` — The element is about to lose focus</span> -- <span id="700e">`oninput` — User input on an element</span> -- <span id="dd0f">`oninvalid` — An element is invalid</span> -- <span id="6cad">`onreset` — A form is reset</span> -- <span id="f4f2">`onsearch` — The user writes something in a search field (for `<input="search">`)</span> -- <span id="32a9">`onselect` — The user selects some text (for `<input>` and `<textarea>`)</span> -- <span id="3e1d">`onsubmit` — A form is submitted</span> - -### Drag - -- <span id="912c">`ondrag` — An element is dragged</span> -- <span id="6897">`ondragend` — The user has finished dragging the element</span> -- <span id="8225">`ondragenter` — The dragged element enters a drop target</span> -- <span id="cf37">`ondragleave` — A dragged element leaves the drop target</span> -- <span id="5bc3">`ondragover` — The dragged element is on top of the drop target</span> -- <span id="2b0c">`ondragstart` — User starts to drag an element</span> -- <span id="8e24">`ondrop` — Dragged element is dropped on the drop target</span> - -### Clipboard - -- <span id="c299">`oncopy` — User copies the content of an element</span> -- <span id="267c">`oncut` — The user cuts an element's content</span> -- <span id="e33c">`onpaste` — A user pastes the content in an element</span> - -### Media - -- <span id="e0ab">`onabort` — Media loading is aborted</span> -- <span id="0758">`oncanplay` — The browser can start playing media (e.g. a file has buffered enough)</span> -- <span id="0bc2">`oncanplaythrough` — The browser can play through media without stopping</span> -- <span id="4c27">`ondurationchange` — The duration of the media changes</span> -- <span id="aa9a">`onended` — The media has reached its end</span> -- <span id="25b8">`onerror` — Happens when an error occurs while loading an external file</span> -- <span id="cdf4">`onloadeddata` — Media data is loaded</span> -- <span id="edce">`onloadedmetadata` — Metadata (like dimensions and duration) are loaded</span> -- <span id="7928">`onloadstart` — The browser starts looking for specified media</span> -- <span id="159c">`onpause` — Media is paused either by the user or automatically</span> -- <span id="057f">`onplay` — The media has been started or is no longer paused</span> -- <span id="ce2a">`onplaying` — Media is playing after having been paused or stopped for buffering</span> -- <span id="2655">`onprogress` — The browser is in the process of downloading the media</span> -- <span id="a11c">`onratechange` — The playing speed of the media changes</span> -- <span id="f8bb">`onseeked` — User is finished moving/skipping to a new position in the media</span> -- <span id="9895">`onseeking` — The user starts moving/skipping</span> -- <span id="c636">`onstalled` — The browser is trying to load the media but it is not available</span> -- <span id="6480">`onsuspend` — The browser is intentionally not loading media</span> -- <span id="f94b">`ontimeupdate` — The playing position has changed (e.g. because of fast forward)</span> -- <span id="e96b">`onvolumechange` — Media volume has changed (including mute)</span> -- <span id="9fe8">`onwaiting` — Media paused but expected to resume (for example, buffering)</span> - -### Animation - -- <span id="4497">`animationend` — A CSS animation is complete</span> -- <span id="fc16">`animationiteration` — CSS animation is repeated</span> -- <span id="0f40">`animationstart` — CSS animation has started</span> - -### Other - -- <span id="614b">`transitionend` — Fired when a CSS transition has completed</span> -- <span id="5a40">`onmessage` — A message is received through the event source</span> -- <span id="0dad">`onoffline` — The browser starts to work offline</span> -- <span id="058e">`ononline` — The browser starts to work online</span> -- <span id="090a">`onpopstate` — When the window's history changes</span> -- <span id="d940">`onshow` — A `<menu>` element is shown as a context menu</span> -- <span id="3062">`onstorage` — A Web Storage area is updated</span> -- <span id="2681">`ontoggle` — The user opens or closes the `<details>` element</span> -- <span id="6a40">`onwheel` — Mouse wheel rolls up or down over an element</span> -- <span id="7178">`ontouchcancel` — Screen-touch is interrupted</span> -- <span id="bec5">`ontouchend` — User's finger is removed from a touch-screen</span> -- <span id="3b60">`ontouchmove` — A finger is dragged across the screen</span> -- <span id="3c0e">`ontouchstart` — A finger is placed on the touch-screen</span> - -### Errors - -When working with JavaScript, different errors can occur. There are several ways of handling them: - -- <span id="54c9">`try` — Lets you define a block of code to test for errors</span> -- <span id="cb14">`catch` — Set up a block of code to execute in case of an error</span> -- <span id="6a5b">`throw` — Create custom error messages instead of the standard JavaScript errors</span> -- <span id="6aea">`finally` — Lets you execute code, after try and catch, regardless of the result</span> - -### Error Name Values - -JavaScript also has a built-in error object. It has two properties: - -- <span id="ca3b">`name` — Sets or returns the error name</span> -- <span id="7047">`message` — Sets or returns an error message in a string from</span> - -The error property can return six different values as its name: - -- <span id="b389">`EvalError` — An error has occurred in the `eval()` function</span> -- <span id="570c">`RangeError` — A number is "out of range"</span> -- <span id="2352">`ReferenceError` — An illegal reference has occurred</span> -- <span id="5019">`SyntaxError` — A syntax error has occurred</span> -- <span id="0527">`TypeError` — A type error has occurred</span> -- <span id="02a3">`URIError` — An `encodeURI()` error has occurred</span> - -### Explicit Conversions - -The simplest way to perform an explicit type conversion is to use the `Boolean(), Number()`, and `String()` functions. - -Any value other than `null `or `undefined `has a` toString()` method. - -`n.toString(2);` - -binary - -`n.toString(8);` - -octal - -`n.toString(16);` - -hex - -`let n = 123456.789;` - -`n.toFixed(0)` - -"123457" - -`n.toFixed(5)` - -"123456.78900" - -`n.toExponential(3)` - -"1.235e+5" - -`n.toPrecision(7)` - -"123456.8" - -`n.toPrecision(10)` - -"123456.7890" - -`parseInt("3 blind mice")` - -3 - -`parseFloat(" 3.14 meters")` - -3.14 - -`parseInt("-12.34")` - --12 - -`parseInt("0xFF")` - -255 - -### Types, Values, and Variables - -### Links - -**Resource** - -**URL** - -MDN - -<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript" class="markup--anchor markup--p-anchor">https://developer.mozilla.org/en-US/docs/Web/JavaScript</a> - -Run Snippets - -<a href="https://developers.google.com/web/tools/chrome-devtools/javascript/snippets" class="markup--anchor markup--p-anchor">https://developers.google.com/web/tools/chrome-devtools/javascript/snippets</a> - -### Explicit Conversions - -The simplest way to perform an explicit type conversion is to use the `Boolean(), Number()`, and `String()` functions. - -Any value other than `null `or `undefined `has a` toString()` method. - -`n.toString(2);` - -binary - -`n.toString(8);` - -octal - -`n.toString(16);` - -hex - -`let n = 123456.789;` - -`n.toFixed(0)` - -"123457" - -`n.toFixed(5)` - -"123456.78900" - -`n.toExponential(3)` - -"1.235e+5" - -`n.toPrecision(7)` - -"123456.8" - -`n.toPrecision(10)` - -"123456.7890" - -`parseInt("3 blind mice")` - -3 - -`parseFloat(" 3.14 meters")` - -3.14 - -`parseInt("-12.34")` - --12 - -`parseInt("0xFF")` - -255 - -`parseInt("0xff")` - -255 - -`parseInt("-0XFF")` - --255 - -`parseInt("0.1")` - -0 - -`parseInt(".1")` - -NaN: integers can't start with "." - -`parseFloat("$72.47")` - -NaN: numbers can't start with "$" - -Supply Radix - -`parseInt("11", 2)` - -3 - -`parseInt("ff", 16)` - -255 - -`parseInt("077", 8)` - -63 - -### Conversion Idioms - -`x + ""` - -`String(x)` - -`+x` - -`Number(x)` - -`x-0` - -`Number(x)` - -`!!x` - -`Boolean(x)` - -### Destructuring Assignment - -`let [x,y] = [1,2];` - -let x=1, y=2 - -`[x,y] = [x + 1,y + 1];` - -x = x + 1, y = y + 1 - -`[x,y] = [y,x];` - -Swap the value of the two variables - -Destructuring assignment makes it easy to work with functions that return arrays of values: - -`let [r,theta] = toPolar(1.0, 1.0);` - - function toPolar(x, y) { - - return [Math.sqrt(x*x+y*y), Math.atan2(y,x)]; - - } - -Variable destructuring in loops: - -`let o = { x: 1, y: 2 };` - - for(const [name, value] of Object.entries(o)) { - - console.log(name, value); // Prints "x 1" and "y 2" - - } - -**Note**: The `Object.entries()` method returns an array of a given object's own enumerable string-keyed property `[key, value]` pairs, in the same order as that provided by a `for...in` loop. (The only important difference is that a `for...in` loop enumerates properties in the prototype chain as well). - -The list of variables on the left can include extra commas to skip certain values on the right - -`[,x,,y] = [1,2,3,4];` - -x == 2; y == 4 - -**Note**: the last comma does not stand for a value. - -To collect all unused or remaining values into a single variable when destructuring an array, use three dots `(...) `before the last variable name on the left-hand side - -`let [x, ...y] = [1,2,3,4];` - -y == \[2,3,4\] - -`let [first, ...rest] = "Hello";` - -first == "H"; rest ==\["e","l","l","o"\] - -Destructuring assignment can also be performed when the righthand side is an object value. - -`let transparent = {r: 0.0, g: 0.0, b: 0.0, a: 1.0};` - -`let {r, g, b} = transparent;` - -r == 0.0; g == 0.0; b == 0.0 - -`const {sin, cos, tan} = Math;` - -sin=Math.sin, cos=Math.cos, tan=Math.tan - -### Expressions and Operators - -In JavaScript, the values `null `and `undefined `are the only two values that do not have properties. In a regular property access expression using . or \[\], you get a `TypeError` if the expression on the left evaluates to `null `or `undefined`. You can use `?.` and `?.[]` syntax to guard against errors of this type. - -You can also invoke a function using `?.()` instead of `()`. - -With the `new ?.()` invocation syntax, if the expression to the left of the `?.` evaluates to `null` or `undefined`, then the entire invocation expression evaluates to `undefined `and no exception is thrown. - -Write the function invocation using `?.(),` knowing that invocation will only happen if there is actually a value to be invoked - - function square(x, log) { - - log?.(x); // Call the function if there is one - - return x * x; - - } - -Note that expression `x++` is not always the same as `x = x + 1`.The `++` operator never performs string concatenation: it always converts its operand to a number and increments it. If x is the string "1", `++x` is the number 2, but` x + 1` is the string "11". - -JavaScript objects are compared by reference, not by value. An object is equal to itself, but not to any other object. If two distinct objects have the same number of properties, with the same names and values, they are still not equal. Similarly, two arrays that have the same elements in the same order are not equal to each other. - -`NaN `value is never equal to any other value, including itself! To check whether a value `x` is `NaN`, use `x !== `, or the global `isNaN()` function. - -If both values refer to the same object, array, or function, they are equal. If they refer to different objects, they are not equal, even if both objects have identical properties. - -### Evaluating Expressions - -JavaScript has the ability to interpret strings of JavaScript source code, evaluating them to produce a value. - -`eval("3+2")` - -Because of security issues, some web servers use the HTTP "Content-Security-Policy" header to disable` eval()` for an entire website. - -### First-Defined (??) - -The first-defined operator `??` evaluates to its first defined operand: if its left operand is not `null` and not `undefined`, it returns that value. - -`a ?? b` is equivalent to `(a !== null && a !== undefined) ? a : b` - -`??` is a useful alternative to `||.` The problem with this idiomatic use is that zero, the empty string, and false are all `falsy `values that may be perfectly valid in some circumstances. In this code example, if `maxWidth `is zero, that value will be ignored. But if we change the `||` operator to `??`, we end up with an expression where zero is a valid value. - -`let max = maxWidth || preferences.maxWidth || 500;` - -`let max = maxWidth ?? preferences.maxWidth ?? 500;` - -### delete Operator - -Deleting an array element leaves a "hole" in the array and does not change the array's length. The resulting array is sparse. - -### void Operator - -Using the `void` operator makes sense only if the operand has side effects. - -`let counter = 0;` - -`const increment = () => void counter++;` - -`increment()` - -undefined - -`counter` - -1 - -### Statements - -Expressions are evaluated to produce a value, but statements are executed to make something happen. - -Expressions with side effects, such as assignments and function invocations, can stand alone as statements, and when used this way are known as expression statements. - -A similar category of statements are the declaration statements that declare new variables and define new functions. - -If a function does not have any side effects, there is no sense in calling it, unless it is part of a larger expression or an assignment statement. - -### for/of - -The `for/of` loop works with iterable objects. Arrays, strings, sets, and maps are iterable. - -Array - - let data = [1, 2, 3, 4, 5, 6, 7, 8, 9], sum = 0; - - for(let element of data) { - - sum += element; - - } - - let text = "Na na na na na na na na"; - - let wordSet = new Set(text.split(" ")); - - let unique = []; - - for(let word of wordSet) { - - unique.push(word); - - } - -String - - let frequency = {}; - - for(let letter of "mississippi") { - - if (frequency[letter]) { - - frequency[letter]++; - - } - - else { - - frequency[letter] = 1; - - } - - } - -Map - - let m = new Map([[1, "one"]]); - - for(let [key, value] of m) { - - key // => 1 - - value // => "one" - - } - -Objects are not (by default) iterable. Attempting to use `for/of` on a regular object throws a `TypeError` at runtime. - -If you want to iterate through the properties of an object, you can use the `for/in` loop. - -Note: `for/of` can be used on objects with `Object.entries` property, but it will not pick properties from object's prototype. - -### for/in - -`for/in` loop works with any object after the `in`. - - for(let p in o) { - - console.log(o[p]); - - } - -Note: this will enumerate array indexes, not values. - - for(let i in a) console.log(i); - -The `for/in` loop does not actually enumerate all properties of an object. It does not enumerate properties whose names are symbols. And of the properties whose names are strings, it only loops over the `enumerable`properties. - -### with - -The with statement runs a block of code as if the properties of a specified object were variables in scope for that code. - -The `with `statement is forbidden in strict mode and should be considered deprecated in non-strict mode: avoid using it whenever possible. - - document.forms[0].address.value - - with(document.forms[0]) { - - name.value = ""; - - address.value = ""; - - email.value = ""; - - } - -### debugger - -If a debugger program is available and is running, then an implementation may (but is not required to) perform some kind of debugging action. - -In practice, this statement acts like a breakpoint: execution of JavaScript code stops, and you can use the debugger to print variables' values, examine the call stack, and so on. - -Note that it is not enough to have a debugger available: the debugger statement won't start the debugger for you. If you're using a web browser and have the developer tools console open, however, this statement will cause a breakpoint. - -### use strict - -Strict mode is a restricted subset of the language that fixes important language deficiencies and provides stronger error checking and increased security. - -The differences between strict mode and non-strict mode are the following: - -· The `with `statement is not allowed in strict mode. - -· In strict mode, all variables must be declared: a `ReferenceError `is thrown if you assign a value to an identifier that is not a declared variable, function, function parameter, catch clause parameter, or property of the global object. - -· In non-strict mode, this implicitly declares a global variable by adding a new property to the global object. - -· In strict mode, functions invoked as functions (rather than as methods) have a `this `value of undefined. (In non-strict mode, functions invoked as functions are always passed the global object as their `this `value.) - -· A function is invoked with `call() `or `apply()` , the `this `value is exactly the value passed as the first argument to `call()` or `apply()`. (In non-strict mode, `null `and `undefined `values are replaced with the global object and non-object values are converted to objects.) - -· In strict mode, assignments to non-writable properties and attempts to create new properties on non-extensible objects throw a `TypeError`. (In non-strict mode, these attempts fail silently.) - -· In strict mode, code passed to `eval() `cannot declare variables or define functions in the caller's scope as it can in non-strict mode. Instead, variable and function definitions live in a new scope created for the `eval()`. This scope is discarded when the `eval()` returns. - -· In strict mode, the Arguments object in a function holds a static copy of the values passed to the function. In non-strict mode, the Arguments object has "magical" behavior in which elements of the array and named function parameters both refer to the same value. - -· In strict mode, a `SyntaxError `is thrown if the `delete `operator is followed by an unqualified identifier such as a variable, function, or function parameter. (In non-strict mode, such a `delete `expression does nothing and evaluates to false.) - -· In strict mode, an attempt to delete a non-configurable property throws a `TypeError`. (In non-strict mode, the attempt fails and the delete expression evaluates to false.) - -· In strict mode, it is a syntax error for an object literal to define two or more properties by the same name. (In non-strict mode, no error occurs.) - -### Objects - -In addition to its name and value, each property has three property attributes: - -· The `writable `attribute specifies whether the value of the property can be set. - -· The `enumerable `attribute specifies whether the property name is returned by a `for/in` loop. - -· The `configurable `attribute specifies whether the property can be deleted and whether its attributes can be altered. - -### Prototypes - -All objects created by object literals have the same prototype object, `Object.prototype.` - -Objects created using the `new `keyword and a constructor invocation use the value of the prototype property of the constructor function as their prototype. - -Object created by `new Object()` inherits from `Object.prototype`, just as the object created by `{}` does. Similarly, the object created by `new Array()` uses `Array.prototype` as its prototype, and the object created by` new Date()` uses `Date.prototype` as its prototype. - -Almost all objects have a prototype, but only a relatively small number of objects have a `prototype `property. It is these objects with prototype properties that define the prototypes for all the other objects. - -Most built-in constructors (and most user-defined constructors) have a prototype that inherits from `Object.prototype`. - -`Date.prototype` inherits properties from `Object.prototype`, so a Date object created by `new Date()` inherits properties from both `Date.prototype` and `Object.prototype`. This linked series of prototype objects is known as a prototype chain. - -### Creating Objects - -Objects can be created with object literals, with the `new` keyword, and with the `Object.create()` function. - -Literal - -`let empty = {};` - -`let point = { x: 0, y: 0 };` - - let book = { - - "main title": "JavaScript", - - "sub-title": "The Definitive Guide", - - for: "all audiences", - - author: { - - firstname: "David", . - - surname: "Flanagan" - - } - - }; - -`new` - -`let o = new Object(); ` - `let a = new Array(); ` - `let d = new Date(); ` - `let r = new Map();` - -`Object.create` - -`let o3 = Object.create(Object.prototype);` - -Use `Object.create` to guard against accidental modifications: - - let o = { x: "don't change this value" }; - - library.function(Object.create(o)); - -Note: the library function can modify the passed in object, but not the original `o` object - -### Access Object Properties with an array (\[\]) notation - - let addr = ""; - - for(let i = 0; i < 4; i++) { - - addr += customer[`address${i}`] + "\n"; - - } - -### Inheritance - -`let o = {};` - -`o.x = 1;` - -`let p = Object.create(o);` - -`p.y = 2;` - -`let q = Object.create(p);` - -`q.z = 3;` - -Property `x` and `y` available on object `q` - -`q.x + q.y` - -### How to query for property which may be undefined - -`surname = book && book.author && book.author.surname;` - -`let surname = book?.author?.surname;` - -### Deleting properties - -The `delete` operator only deletes own properties, not inherited ones. (To delete an inherited property, you must delete it from the prototype object in which it is defined. Doing this affects every object that inherits from that prototype.) - -`delete` does not remove properties that have a `configurable `attribute of false. - -Certain properties of built-in objects are non-configurable, as are properties of the global object created by variable declaration and function declaration. - -`delete Object.prototype` - -false: property is non-configurable - -`var x = 1;` - -`delete globalThis.x` - -false: can't delete `this `property - -`function f() {}` - -`delete globalThis.f` - -false - -`globalThis.x = 1;` - -`delete globalThis.x` - -true - -### Testing properties - -To check whether an object has a property with a given name. You can do this with the `in` operator, with the `hasOwnProperty()` and `propertyIsEnumerable()` methods, or simply by querying the property - -( `!= undefined`). - -### in & query - -`let o = { x: 1 };` - -`"x" in o` - -true - -`o.x !== undefined` - -`"y" in o` - -false - -`o.y !== undefined` - -`"toString" in o` - -true: o inherits a `toString `property - -`o.toString !== undefined` - -Advantage of using in: `in` can distinguish between properties that do not exist and properties that exist but have been set to `undefined`. - -### hasOwnProperty - -`let o = { x: 1 };` - -`o.hasOwnProperty("x")` - -true - -`o.hasOwnProperty("y")` - -false - -`o.hasOwnProperty("toString")` - -false: toString is an inherited property - -The `propertyIsEnumerable()` returns true only if the named property is an own property and its `enumerable` attribute is true. - -`let o = { x: 1 };` - -`o.propertyIsEnumerable("x")` - -true - -`o.propertyIsEnumerable("toString")` - -false: not an own property - -`Object.prototype.propertyIsEnumerable("toString")` - -false: not enumerable - -### Enumerating properties - -To guard against enumerating inherited properties with `for/in`, you can add an explicit check inside the loop body: - - for(let p in o) { - - if (!o.hasOwnProperty(p)) continue; - - } - - for(let p in o) { - - if (typeof o[p] === "function") continue; - - } - -Functions you can use to get an array of property names - -· `Object.keys()` returns an array of the names of the enumerable own properties of an object. It does not include non-enumerable properties, inherited properties, or properties whose name is a Symbol. - -· `Object.getOwnPropertyNames()` works like `Object.keys() `but returns an array of the names of nonenumerable own properties as well. - -· `Object.getOwnPropertySymbols()` returns own properties whose names are Symbols, whether or not they are enumerable. - -· `Reflect.ownKeys()` returns all own property names, both enumerable and non-enumerable, and both string and Symbol. - -### Extending Objects - -To copy the properties of one object to another object - - let target = {x: 1}, source = {y: 2, z: 3}; - - for(let key of Object.keys(source)) { - - target[key] = source[key]; - - } - -One reason to assign properties from one object into another is when you have an object that defines default values for many properties and you want to copy those default properties into another object if a property by that name does not already exist in that object. Using `Object.assign()` naively will not do what you want: - - Object.assign(o, defaults); - -overwrites everything in o with defaults - -Instead, use one of the following:, - -`o = Object.assign({}, defaults, o);` - -`o = {...defaults, ...o};` - -### Serializing Objects - -The functions `JSON.stringify()` and` JSON.parse()` serialize and restore JavaScript objects. - -`let o = {x: 1, y: {z: [false, null, ""]}};` - -`let s = JSON.stringify(o);` - -s == '{"x":1,"y":{"z":\[false,null,""\]}}' - -`let p = JSON.parse(s);` - -p == {x: 1, y: {z: \[false,null, ""\]}} - -### Object methods - -`toString(), valueOf(), loLocaleString(), toJSON()` - -`let s = { x: 1, y: 1 }.toString();` - -s == "\[object Object\]" - -### Extended Object Literal Syntax - -### Shorthand Properties - - let x = 1, y = 2; - - let o = { - - x: x, - - y: y - - }; - -←> - -`let x = 1, y = 2;` - `let o = { x, y };` - -### Computer Property Names - -`const PROPERTY_NAME = "p1";` - `function computePropertyName() { return "p" + 2; }` - - let o = {}; - - o[PROPERTY_NAME] = 1; - - o[computePropertyName()] = 2; - -←> - - let p = { - - [PROPERTY_NAME]: 1, - - [computePropertyName()]: 2 - - }; - -### Symbols as Property Names - - const extension = Symbol("my extension symbol"); - - let o = { - - [extension]: {} - - }; - - o[extension].x = 0; - -Two Symbols created with the same string argument are still different from one another. - -The point of Symbols is not security, but to define a safe extension mechanism for JavaScript objects. If you get an object from third-party code that you do not control and need to add some of your own properties to that object but want to be sure that your properties will not conflict with any properties that may already exist on the object, you can safely use Symbols as your property names. - -### Spread Operator - -You can copy the properties of an existing object into a new object using the "spread operator" … inside an object literal: - -`let position = { x: 0, y: 0 };` - `let dimensions = { width: 100, height: 75 };` - `let rect = { ...position, ...dimensions };` - `rect.x + rect.y + rect.width + rect.height` - -### Shorthand Methods - - let square = { - - area: function() { - - return this.side * this.side; }, - - side: 10 - - }; - -←> - - let square = { - - area() { - - return this.side * this.side; }, - - side: 10 - - }; - -When you write a method using this shorthand syntax, the property name can take any of the forms that are legal in an object literal: in addition to a regular JavaScript identifier like the name area above, you can also use string literals and computed property names, which can include Symbol property names: - - const METHOD_NAME = "m"; - - const symbol = Symbol(); - - let weirdMethods = { - - "method With Spaces"(x) { return x + 1; }, - - [METHOD_NAME](x) { return x + 2; }, - - [symbol](x) { return x + 3; } - - }; - -`weirdMethods["method With Spaces"](1)` - -2 - -`weirdMethods[METHOD_NAME](1)` - -3 - -`weirdMethods[symbol](1)` - -4 - -### Property Getters and Setters - - let o = { - - dataProp: value, - - get accessorProp() { return this.dataProp; }, - - set accessorProp(value) { this.dataProp = value; } - - }; - -### Arrays - -### Creating Arrays - -· Array literals - -· The … spread operator on an iterable object - -· The `Array()` constructor - -· The `Array.of()` and `Array.from()` factory methods - -### Array literals - -`let empty = [];` - -`let primes = [2, 3, 5, 7, 11];` - -`let misc = [ 1.1, true, "a", ];` - -`let b = [[1, {x: 1, y: 2}], [2, {x: 3, y: 4}]];` - -If an array literal contains multiple commas in a row, with no value between, the array is sparse - -`let count = [1,,3];` - -`let undefs = [,,];` - -Array literal syntax allows an optional trailing comma, so `[,,]` has a length of 2, not 3. - -### The Spread Operator - -`let a = [1, 2, 3];` - -`let b = [0, ...a, 4];` - -\[0, 1, 2, 3, 4\] - -create a copy of an array — modifying the copy does not change the original - -`let original = [1,2,3];` - `let copy = [...original];` - -`let digits = [..."0123456789ABCDEF"];` - -\["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"\] - -`let letters = [..."hello world"];` - -\["h","e","l","l""o","","w","o""r","l","d"\] - -`[...new Set(letters)]` - -\["h","e","l","o","","w","r","d"\] - -### Array.of() - -When the `Array()` constructor function is invoked with one numeric argument, it uses that argument as an array length. But when invoked with more than one numeric argument, it treats those arguments as elements for the array to be created. This means that the `Array()` constructor cannot be used to create an array with a single numeric element. - -`Array.of()` - -\[\] - -`Array.of(10)` - -\[10\] - -`Array.of(1,2,3)` - -\[1, 2, 3\] - -### Array.from() - -It is also a simple way to make a copy of an array: - -`let copy = Array.from(original);` - -`Array.from()` is also important because it defines a way to make a true-array copy of an array-like object. Array-like objects are non-array objects that have a numeric length property and have values stored with properties whose names happen to be integers. - -`let truearray = Array.from(arraylike);` - -`Array.from()` also accepts an optional second argument. If you pass a function as the second argument, then as the new array is being built, each element from the source object will be passed to the function you specify, and the return value of the function will be stored in the array instead of the original value. - -### Reading and Writing Array Elements - -What is special about arrays is that when you use property names that are non-negative integers , the array automatically maintains the value of the `length` property for you. - -JavaScript converts the numeric array index you specify to a string — the index 1 becomes the string "1", then uses that string as a property name. - -It is helpful to clearly distinguish an array index from an object property name. All indexes are property names, but only property names that are integers between 0 and 231 are indexes. All arrays are objects, and you can create properties of any name on them. If you use properties that are array indexes, however, arrays have the special behavior of updating their `length` property as needed. - -Note that you can index an array using numbers that are negative or that are not integers. When you do this, the number is converted to a string, and that string is used as the property name. Since the name is not a non-negative integer, it is treated as a regular object property, not an array index. - -`a[-1.23] = true;` - -This creates a property named "-1.23" - -`a["1000"] = 0;` - -This the 1001st element of the array - -`a[1.000] = 1;` - -Array index 1. Same as a\[1\] = 1; - -The fact that array indexes are simply a special type of object property name means that JavaScript arrays have no notion of an "out of bounds" error. When you try to query a nonexistent property of any object, you don't get an error; you simply get `undefined`. - -### Sparse Arrays - -Sparse arrays can be created with the `Array()` constructor or simply by assigning to an array index larger than the current array length. - -`a[1000] = 0;` - -Assignment adds one element but sets length to 1001. - -you can also make an array sparse with the `delete` operator. - -Note that when you omit a value in an array literal (using repeated commas as in `[1,,3]`), the resulting array is sparse, and the omitted elements simply do not exist - -### Array Length - -if you set the length property to a nonnegative integer `n` smaller than its current value, any array elements whose index is greater than or equal to n are deleted from the array. - -`a = [1,2,3,4,5];` - -`a.length = 3;` - -a is now \[1,2,3\]. - -`a.length = 0;` - -Delete all elements. a is \[\]. - -`a.length = 5;` - -Length is 5, but no elements, like `new Array(5)` - -You can also set the length property of an array to a value larger than its current value. Doing this does not actually add any new elements to the array; it simply creates a sparse area at the end of the array. - -### Adding and Deleting Array Elements - -`let a = [];` - -`a[0] = "zero";` - -`a[1] = "one";` - -add elements to it. - -You can also use the `push()` method to add one or more values to the end of an array. - -You can use the` unshift()` method to insert a value at the beginning of an array, shifting the existing array elements to higher indexes. - -The `pop()` method is the opposite of `push()`: it removes the last element of the array and returns it, reducing the length of an array by 1. - -Similarly, the `shift()` method removes and returns the first element of the array, reducing the length by 1 and shifting all elements down to an index one lower than their current index. - -You can delete array elements with the delete operator - -`let a = [1,2,3];` - -`delete a[2];` - -a now has no element at index 2 - -`2 in a` - -false - -`a.length` - -3: delete does not affect array length - -### Iterating Arrays - -The easiest way to loop through each of the elements of an array (or any iterable object) is with the `for/of`loop - - let letters = [..."Hello world"]; - - let string = ""; - - for(let letter of letters) { - - string += letter; - - } - -It has no special behavior for sparse arrays and simply returns `undefined` for any array elements that do not exist. - -If you want to use a `for/of` loop for an array and need to know the index of each array element, use the `entries()` method of the array - - let letters = [..."Hello world"]; - - let everyother = ""; - - for(let [index, letter] of letters.entries()) { - - if (index % 2 === 0) everyother += letter; - - } - -Another good way to iterate arrays is with `forEach()`. This is not a new form of the for loop, but an array method that offers a functional approach to array iteration. - - let letters = [..."Hello world"]; - - let uppercase = ""; - - letters.forEach(letter => { - - uppercase += letter.toUpperCase(); - - }); - -You can also loop through the elements of an array with a `for` loop. - - for(let i = 0, len = letters.length; i < len; i++) { - - // loop body - - } - -### Multidimensional Arrays - -### Create a multidimensional array - -`let table = new Array(10);` - - for(let i = 0; i < table.length; i++) { - - table[i] = new Array(10); - - } - - for(let row = 0; row < table.length; row++) { - - for(let col = 0; col < table[row].length; col++) { - - table[row][col] = row * col; - - } - - } - -### Array Methods - -### Array Iterator Methods - -First, all of these methods accept a function as their first argument and invoke that function once for each element (or some elements) of the array. If the array is sparse, the function you pass is not invoked for nonexistent elements. In most cases, the function you supply is invoked with three arguments: the value of the array element, the index of the array element, and the array itself. - -FOREACH() - -`let data = [1,2,3,4,5], sum = 0;` - - data.forEach(value => { sum += value; }); - - data.forEach(function(v, i, a) { - - a[i] = v + 1; - - }); - -15 - -\[2,3,4,5,6\] - -MAP() - -`let a = [1, 2, 3];` - `a.map(x => x*x)` - -\[1, 4, 9\] - -FILTER() - -`let a = [5, 4, 3, 2, 1];` - `a.filter(x => x < 3) ` - `a.filter((x,i) => i % 2 === 0)` - -\[2, 1\]; - -\[5, 3, 1\]; - -FIND() - -FINDINDEX() - -`let a = [1,2,3,4,5];` - -`a.findIndex(x => x === 3)` - -`a.find(x => x % 5 === 0)` - -`a.find(x => x % 7 === 0)` - -2 - -5 - -undefined - -EVERY() - -SOME() - -`let a = [1,2,3,4,5];` - -`a.every(x => x < 10)` - -`a.some(x => x % 2 === 0)` - -`a.some(isNaN)` - -true - -true - -false - -REDUCE() - -ReduceRight() - -l`et a = [1,2,3,4,5];` - -`a.reduce((x,y) => x+y, 0)` - -`a.reduce((x,y) => x*y, 1)` - -`a.reduce((x,y) => (x > y) ? x : y)` - -15 - -120 - -5 - -Note that `map()` returns a new array: it does not modify the array it is invoked on. If that array is sparse, your function will not be called for the missing elements, but the returned array will be sparse in the same way as the original array: it will have the same length and the same missing elements. - -To close the gaps in a sparse array, you can do this: - -`let dense = sparse.filter(() => true);` - -And to close gaps and remove undefined and null elements, you can use filter, like this: - -`a = a.filter(x => x !== undefined && x !== null);` - -Unlike `filter()`, however,` find()` and `findIndex()` stop iterating the first time the predicate finds an element. When that happens, `find()` returns the matching element, and `findIndex()` returns the index of the matching element. If no matching element is found,` find()` returns `undefined` and` findIndex()`returns -1. - -When you invoke `reduce()` with no initial value, it uses the first element of the array as the initial value. - -`reduceRight()` works just like `reduce()`, except that it processes the array from highest index to lowest (right-to-left), rather than from lowest to highest. You might want to do this if the reduction operation has right-to-left associativity - -### Flattening arrays with `flat()` and `flatMap()` - -`[1, [2, 3]].flat()` - -\[1, 2, 3\] - -`[1, [2, [3]]].flat()` - -\[1, 2, \[3\]\] - -`let a = [1, [2, [3, [4]]]];` - -`a.flat(1)` - -`a.flat(2)` - -`a.flat(3)` - -`a.flat(4)` - -\[1, 2, \[3, \[4\]\]\] - -\[1, 2, 3, \[4\]\] - -\[1, 2, 3, 4\] - -\[1, 2, 3, 4\] - -`let phrases = ["hello world", "the definitive guide"];` - `let words = phrases.flatMap(phrase => phrase.split(" "));` - -\["hello", "world", "the", "definitive", "guide"\]; - -Calling `a.flatMap(f)` is the same as (but more efficient than) `a.map(f).flat()`: - -### Adding arrays with concat() - -`let a = [1,2,3];` - -`a.concat(4, 5)` - -\[1,2,3,4,5\] - -`a.concat([4,5],[6,7])` - -\[1,2,3,4,5,6,7\] - -### Stacks and Queues with push(), pop(), shift(), and unshift() - -The `push()` and` pop()` methods allow you to work with arrays as if they were stacks. The `push()` method appends one or more new elements to the end of an array and returns the new length of the array. - -The `unshift()` and `shift()` methods behave much like `push()` and` pop()`, except that they insert and remove elements from the beginning of an array rather than from the end. - -You can implement a queue data structure by using `push()` to add elements at the end of an array and `shift()` to remove them from the start of the array. Note differences in `unshift `with single and multiple values. - -`let a = [];` - -`a.unshift(1)` - -\[1\] - -`a.unshift(2)` - -\[2, 1\] - -`a = [];` - -`a.unshift(1,2)` - -\[1, 2\] - -### Subarrays with `slice(), splice(), fill()`, and `copyWithin()` - -SLICE() - -`let a = [1,2,3,4,5];` - -`a.slice(0,3);` - -`a.slice(3);` - -`a.slice(1,-1);` - -`a.slice(-3,-2);` - -\[1,2,3\] - -\[4,5\] - -\[2,3,4\] - -\[3\] - -SPLICE - -`let a = [1,2,3,4,5,6,7,8];` - -`a.splice(4)` - -`a.splice(1,2)` - -`a.splice(1,1)` - -`let a = [1,2,3,4,5];` - -`a.splice(2,0,"a","b")` - -`a.splice(2,2,[1,2],3)` - -\[5,6,7,8\]; `a` is now \[1,2,3,4\] - -\[2,3\]; a is now \[1,4\] - -\[4\]; a is now \[1\] - -\[\]; a is now \[1,2,"a","b",3,4,5\] - -\["a","b"\]; a is now \[1,2,\[1,2\],3,3,4,5\] - -FILL() - -`let a = new Array(5);` - -`a.fill(0)` - -`a.fill(9, 1)` - -`a.fill(8, 2, -1)` - -\[0,0,0,0,0\] - -\[0,9,9,9,9\] - -\[0,9,8,8,9\] - -COPYWITHIN() - -`let a = [1,2,3,4,5];` - -`a.copyWithin(1)` - -`a.copyWithin(2, 3, 5)` - -`a.copyWithin(0, -2)` - -\[1,1,2,3,4\] - -\[1,1,3,4,4\] - -\[4,4,3,4,4\] - -`splice()` is a general-purpose method for inserting or removing elements from an array.` splice()` can delete elements from an array, insert new elements into an array, or perform both operations at the same time. - -The first argument to `splice()` specifies the array position at which the insertion and/or deletion is to begin. The second argument specifies the number of elements that should be deleted from (spliced out of) the array. - -Unlike `concat(), splice()` inserts arrays themselves, not the elements of those arrays. - -`copyWithin()` copies a slice of an array to a new position within the array. It modifies the array in place and returns the modified array, but it will not change the length of the array. - -### Array Searching and Sorting Methods - -INDEXOF() - LASTINDEXOF() - -`let a = [0,1,2,1,0];` - -`a.indexOf(1)` - -`a.lastIndexOf(1)` - -`a.indexOf(3)` - -1 - -3 - --1 - -SORT() - -`let a = [33, 4, 1111, 222];` - -`a.sort();` - -`a.sort((a,b) => a - b);` - -Case-insensitive sort - - let a = ["ant", "Bug", "cat", "Dog"]; - - a.sort(); // a == ["Bug","Dog","ant","cat"]; - - a.sort(function(s,t) { - - let a = s.toLowerCase(); - - let b = t.toLowerCase(); - - if (a < b) return -1; - - if (a > b) return 1; - - return 0; - - }); - -`[1111, 222, 33, 4];` - -`[4, 33, 222, 1111]` - -REVERSE() - -`let a = [1,2,3];` - `a.reverse();` - -\[3,2,1\] - -`indexOf()` and `lastIndexOf()` compare their argument to the array elements using the equivalent of the === operator. If your array contains objects instead of primitive values, these methods check to see if two references both refer to exactly the same object. If you want to actually look at the content of an object, try using the `find()` method with your own custom predicate function instead. - -`indexOf()` and `lastIndexOf()` take an optional second argument that specifies the array index at which to begin the search. Negative values are allowed for the second argument and are treated as an offset from the end of the array. - -`indexOf()` will not detect the NaN value in an array, but `includes()` will - -When `sort()` is called with no arguments, it sorts the array elements in alphabetical order. To sort an array into some order other than alphabetical, you must pass a comparison function as an argument to `sort()`. - -### Array to String Conversions - -The `join()` method converts all the elements of an array to strings and concatenates them, returning the resulting string. - -`let a = [1, 2, 3];` - -`a.join()` - -`a.join(" ")` - -`a.join("")` - -"1,2,3" - -"1 2 3" - -"123" - -`let b = new Array(10);` - -`b.join("-")` - -" — — — — -" - -Arrays, like all JavaScript objects, have a `toString()` method. For an array, this method works just like the `join()` method with no arguments: - -`[1,2,3].toString()` - -"1,2,3" - -`["a", "b", "c"].toString()` - -"a,b,c" - -`[1, [2,"c"]].toString()` - -"1,2,c" - -### Static Array Functions - -`Array.isArray([])` - -true - -`Array.isArray({})` - -false - -### Array-Like Objects - -It is often perfectly reasonable to treat any object with a numeric `length` property and corresponding non-negative integer properties as a kind of array. - - let a = {}; - - let i = 0; - - while(i < 10) { - - a[i] = i * i; - - i++; - - } - - a.length = i; - - // Now iterate through it as if it were a real array - - let total = 0; - - for(let j = 0; j < a.length; j++) { - - total += a[j]; - - } - -Since array-like objects do not inherit from `Array.prototype`, you cannot invoke array methods on them directly. You can invoke them indirectly using the `Function.call` method. - -`let a = {"0": "a", "1": "b", "2": "c", length: 3};` - -// An array-like object - -`Array.prototype.join.call(a, "+")` - -"a+b+c" - -`Array.prototype.join.call("JavaScript", " ")` - -"J a v a S c r i p t" - -`Array.prototype.map.call(a, x => x.toUpperCase())` - -\["A","B","C"\] - -`Array.from(a)` - -\["a","b","c"\] - -### Strings as Arrays - -`let s = "test";` - -`s.charAt(0)` - -t - -`s[1]` - -e - -### Functions - -In addition to the arguments, each invocation has another value — the invocation context — that is the value of the `this` keyword. - -### Function Declarations - - function printprops(o) { - - for(let p in o) { - - console.log(`${p}: ${o[p]}\n`); - - } - - } - -Function declaration statements are "hoisted" to the top of the enclosing script, function, or block so that functions defined in this way may be invoked from code that appears before the definition. - -### Function Expressions - -`const square = function(x) { return x*x; };` - - const f = function fact(x) { - - if (x <= 1) return 1; - - return x * fact(x-1); - - } - -Function expressions can include names, which is useful for recursion - -`[3,2,1].sort(function(a,b) { return a - b; });` - -Function expressions can also be used as arguments to other functions - -`let tensquared = (function(x) {return x*x;}(10));` - -Function expressions are sometimes defined and immediately invoked - -### Arrow Functions - -`const sum = (x, y) => { return x + y; };` - -`const sum = (x, y) => x + y;` - -no need for `return` - -`const polynomial = x => x*x + 2*x + 3;` - -omit parens with single parameter - -`const constantFunc = () => 42;` - -usage for no params - -If the body of your arrow function is a single return statement but the expression to be returned is an object literal, then you have to put the object literal inside parentheses to avoid syntactic ambiguity between the curly braces of a function body and the curly braces of an object literal - -`const f = x => { return { value: x }; };` - -good - -`const g = x => ({ value: x });` - -good - -`const h = x => { value: x };` - -returns nothing - -`const i = x => { v: x, w: x };` - -syntax error - -Arrow functions differ from functions defined in other ways in one critical way: they inherit the value of the `this` keyword from the environment in which they are defined rather than defining their own invocation context as functions defined in other ways do. - -### Nested Functions - - function hypotenuse(a, b) { - - function square(x) { return x*x; } - - return Math.sqrt(square(a) + square(b)); - - } - -### Invoking Functions - -For function invocation in non-strict mode, the invocation context (the `this` value) is the global object. In strict mode, however, the invocation context is `undefined`. - -`const strict = (function() { return !this; }())` - -Determine if we're in strict mode - -### Constructor Invocation - -A constructor invocation creates a new, empty object that inherits from the object specified by the `prototype`property of the constructor. - -### Indirect invocation - -JavaScript functions are objects, and like all JavaScript objects, they have methods. Two of these methods, `call()` and `apply()`, invoke the function indirectly. Both methods allow you to explicitly specify the `this `value for the invocation, which means you can invoke any function as a method of any object, even if it is not actually a method of that object. - -### Function Arguments and Parameters - -### Optional Parameters and Defaults - -When a function is invoked with fewer arguments than declared parameters, the additional parameters are set to their default value, which is normally `undefined`. - - function getPropertyNames(o, a) { - - a = a || []; - - for(let property in o) a.push(property); - - return a; - - } - - function getPropertyNames(o, a = []) { - - for(let property in o) a.push(property); - - return a; - - } - -One interesting case is that, for functions with multiple parameters, you can use the value of a previous parameter to define the default value of the parameters that follow it - - const rectangle = (width, height = width*2) => ({width, height}); - -### Rest Parameters and Variable-Length Argument Lists - -Rest parameters enable us to write functions that can be invoked with arbitrarily more arguments than parameters. - - function max(first=-Infinity, ...rest) { - - let maxValue = first; - - for(let n of rest) { - - if (n > maxValue) { - - maxValue = n; - - } - - } - - return maxValue; - - } - - max(1, 10, 100, 2, 3, 1000, 4, 5, 6) - -1000 - -within the body of a function, the value of a rest parameter will always be an array. The array may be empty, but a rest parameter will never be `undefined`. - -This type of function is called variadic functions, variable arity functions, or vararg functions. - -### The Arguments Object - -Within the body of any function, the identifier `arguments` refers to the Arguments object for that invocation. - - function max(x) { - - let maxValue = -Infinity; - - for(let i = 0; i < arguments.length; i++) { - - if (arguments[i] > maxValue) - - maxValue = arguments[i]; - - } - - return maxValue; - - } - - max(1, 10, 100, 2, 3, 1000, 4, 5, 6) - -1000 - -you should avoid using it in any new code you write. - -### The Spread Operator for Function Calls - - let numbers = [5, 2, 10, -1, 9, 100, 1]; - - Math.min(...numbers) - --1 - - function timed(f) { - - return function(...args) { - - console.log(`Entering function ${f.name}`); - - let startTime = Date.now(); - - try { - - return f(...args); - - } - - finally { - - console.log(`Exiting ${f.name} after ${Date.now() - startTime}ms`); - - } - - }; - - } - - // Compute the sum of the numbers between 1 and n by brute force - - function benchmark(n) { - - let sum = 0; - - for(let i = 1; i <= n; i++) sum += i; - - return sum; - - } - - // Now invoke the timed version of that test function - - timed(benchmark)(1000000) - -### Destructuring Function Arguments into Parameters - - function vectorAdd(v1, v2) { - - return [v1[0] + v2[0], v1[1] + v2[1]]; - - } - - vectorAdd([1,2], [3,4]) - -←> - - function vectorAdd([x1,y1], [x2,y2]) { - - return [x1 + x2, y1 + y2]; - - } - - vectorAdd([1,2], [3,4]) - - function vectorMultiply({x, y}, scalar) { - - return { x: x*scalar, y: y*scalar }; - - } - - vectorMultiply({x: 1, y: 2}, 2) - -←> - - function vectorMultiply({x,y}, scalar) { - - return { x: x*scalar, y: y*scalar}; - - } - - vectorMultiply({x: 1, y: 2}, 2) - -### Argument Types - -Adding code to check the types of arguments - - function sum(a) { - - let total = 0; - - for(let element of a) { - - if (typeof element !== "number") { - - throw new TypeError("sum(): elements must be numbers"); - - } - - total += element; - - } - - return total; - - } - -`sum([1,2,3])` - -6 - -`sum(1, 2, 3);` - -`TypeError`: 1 is not iterable - -`sum([1,2,"3"]);` - -`TypeError`: element 2 is not a number - -### Functions as Values - - function square(x) { return x * x; } - -`let s = square;` - -`square(4)` - -16 - -`s(4)` - -16 - -Functions can also be assigned to object properties rather than variables. - -`let o = {square: function(x) { return x*x; }};` - -`let y = o.square(16);` - -256 - -Functions don't even require names at all, as when they're assigned to array elements: - -`let a = [x => x*x, 20];` - -`a[0](a[1])` - -400 - -`a[0]` accesses first element of the array, which is "`x => x*x`", `(a[1])` passes parameter, which is 20. - -### Examples of using functions as data - - function add(x,y) { return x + y; } - - function subtract(x,y) { return x - y; } - - function multiply(x,y) { return x * y; } - - function divide(x,y) { return x / y; } - - function operate(operator, operand1, operand2) { - - return operator(operand1, operand2); - - } - -`let i = operate(add, operate(add, 2, 3), operate(multiply, 4,5));` - -`(2+3) + (4*5):` - -or: - - const operators = { - - add: (x,y) => x+y, - - subtract: (x,y) => x-y, - - multiply: (x,y) => x*y, - - divide: (x,y) => x/y, - - pow: Math.pow - - }; - - function operate2(operation, operand1, operand2) { - - if (typeof operators[operation] === "function") { - - return operators[operation](operand1, operand2); - - } - - else throw "unknown operator"; - - } - -`operate2("add", "hello", operate2("add", " ", "world"))` - -// "hello world" - -`operate2("pow", 10, 2)` - -100 - -### Defining Your Own Function Properties - -When a function needs a "static" variable whose value persists across invocations, it is often convenient to use a property of the function itself. - -For example, suppose you want to write a function that returns a unique integer whenever it is invoked. The function must never return the same value twice. In order to manage this, the function needs to keep track of the values it has already returned, and this information must persist across function invocations. - - uniqueInteger.counter = 0; - - function uniqueInteger() { - - return uniqueInteger.counter++; - - } - - uniqueInteger() - -0 - - uniqueInteger() - -1 - -Compute factorials and cache results as properties of the function itself. - - function factorial(n) { - - if (Number.isInteger(n) && n > 0) { - - if (!(n in factorial)) { - - factorial[n] = n * factorial(n-1); - - } - - return factorial[n]; - - } - - else { - - return NaN; - - } - - } - - factorial[1] = 1; - -Initialize the cache to hold this base case. - - factorial(6) - -720 - - factorial[5] - -120; the call above caches this value - -### Functions as Namespaces - -Variables declared within a function are not visible outside of the function. For this reason, it is sometimes useful to define a function simply to act as a temporary namespace in which you can define variables without cluttering the global namespace. - -Variables that would have been global become local to the function. Following code defines only a single global variable: the function name `chunkNamespace`. - - function chunkNamespace() { - - // Chunk of code goes here - - // Any variables defined in the chunk are local to this function - - // instead of cluttering up the global namespace. - - } - - chunkNamespace(); - -If defining even a single property is too much, you can define and invoke an anonymous function in a single expression — IIEF (immediately invoked function expression) - - (function() { - - // chunkNamespace() function rewritten as an unnamed expression. - - // Chunk of code goes here - - }()); - -### Closures - -JavaScript uses lexical scoping. This means that functions are executed using the variable scope that was in effect when they were defined, not the variable scope that is in effect when they are invoked. - -In order to implement lexical scoping, the internal state of a JavaScript function object must include not only the code of the function but also a reference to the scope in which the function definition appears. - -This combination of a function object and a scope (a set of variable bindings) in which the function's variables are resolved is called a closure. - -Closures become interesting when they are invoked from a different scope than the one they were defined in. This happens most commonly when a nested function object is returned from the function within which it was defined. - - let scope = "global scope"; - - function checkscope() { - - let scope = "local scope"; - - function f() { return scope; } - - return f(); - - } - -`checkscope()` - -"local scope" - - let scope = "global scope"; - - function checkscope() { - - let scope = "local scope"; - - function f() { return scope; } - - return f; - - } - -`let s = checkscope()();` - -"local scope" - -Closures capture the local variables of a single function invocation and can use those variables as private state. - - let uniqueInteger = (function() { - - let counter = 0; - - return function() { return counter++; }; - - }()); - -`uniqueInteger()` - -0 - -`uniqueInteger()` - -1 - -it is the return value of the function that is being assigned to `uniqueInteger`. - -Private variables like counter need not be exclusive to a single closure: it is perfectly possible for two or more nested functions to be defined within the same outer function and share the same scope. - - function counter() { - - let n = 0; - - return { - - count: function() { return n++; }, - - reset: function() { n = 0; } - - }; - - } - -`let c = counter(), d = counter();` - -`c.count()` - -0 - -`d.count()` - -0 - -`c.reset();` - -`c.count()` - -0 - -`d.count()` - -1 - -You can combine this closure technique with property getters and setters - - function counter(n) { - - return { - - get count() { return n++; }, - - set count(m) { - - if (m > n) n = m; - - else throw Error("count can only be set to a larger value") - - } - - }; - - } - -`let c = counter(1000);` - -`c.count` - -1000 - -`c.count` - -1001 - -`c.count = 2000;` - -`c.count` - -2000 - -`c.count = 2000;` - -Error: count can only be set to a larger value - -Define a private variable and two nested functions to get and set the value of that variable. - - function addPrivateProperty(o, name, predicate) { - - let value; - - o[`get${name}`] = function() { return value; }; - - o[`set${name}`] = function(v) { - - if (predicate && !predicate(v)) { - - throw new TypeError(`set${name}: invalid value ${v}`); - - } - - else { - - value = v; - - } - - }; - - } - -`let o = {};` - -`addPrivateProperty(o, "Name", x => typeof x === "string");` - -`o.setName("Frank");` - -`o.getName()` - -"Frank" - -`o.setName(0);` - -TypeError: try to set a value ofthe wrong type - -### Function Properties, Methods, and Constructor - -Since functions are objects, they can have properties and methods, just like any other object. - -### The length Property - -The read-only length property of a function specifies the arity of the function — the number of parameters it declares in its parameter list, which is usually the number of arguments that the function expects. - -### The name Property - -This property is primarily useful when writing debugging or error messages. - -### The prototype Property - -When a function is used as a constructor, the newly created object inherits properties from the prototype object. - -### The call() and apply() Methods - -`call()` and `apply()` allow you to indirectly invoke a function as if it were a method of some other object. The first argument to both `call()` and `apply()` is the object on which the function is to be invoked; this argument is the invocation context and becomes the value of the `this` keyword within the body of the function. - -To invoke the function` f()` as a method of the object o (passing no arguments), - -`f.call(o);` - -`f.apply(o);` - -To pass two numbers to the function `f()` and invoke it as if it were a method of the object o, - - f.call(o, 1, 2); - -The `apply()` method is like the `call()` method, except that the arguments to be passed to the function are specified as an array: - - f.apply(o, [1,2]); - -The `trace() `function defined uses the `apply() `method instead of a spread operator, and by doing that, it is able to invoke the wrapped method with the same arguments and the same this value as the wrapper method - - function trace(o, m) { - - let original = o[m]; - - o[m] = function(...args) { - - console.log(new Date(), "Entering:", m); - - let result = original.apply(this, args); - - console.log(new Date(), "Exiting:", m); - - return result; - - }; - - } - -### The bind() Method - -The primary purpose of `bind()` is to bind a function to an object. - -`function f(y) { return this.x + y; }` - -`let o = { x: 1 };` - -`let g = f.bind(o);` - -`g(2)` - -3 - -`let p = { x: 10, g };` - -`p.g(2)` - -3 // g is still bound to o, not p. - -The most common use case for calling `bind()` is to make non-arrow functions behave like arrow functions. - -Partial application is a common technique in functional programming and is sometimes called `currying`. - -`let sum = (x,y) => x + y;` - -`let succ = sum.bind(null, 1);` - -`succ(2)` - -3 - -### The toString() Method - -Most (but not all) implementations of this `toString()` method return the complete source code for the function - -### The Function() Constructor - -The Function() constructor is best thought of as a globally scoped version of `eval()` that defines new variables and functions in its own private scope. You will probably never need to use this constructor in your code. - -### Higher-Order Functions - -A higher-order function is a function that operates on functions, taking one or more functions as arguments and returning a new function. - - function not(f) { - - return function(...args) { - - let result = f.apply(this, args); - - return !result; - - }; - - } - -`const even = x => x % 2 === 0;` - -A function to determine if a number is even - -`const odd = not(even);` - -`[1,1,3,5,5].every(odd)` - -true - -Returns a new function that maps one array to another - - const map = function(a, ...args) { return a.map(...args); }; - - function mapper(f) { - - return a => map(a, f); - - } - - const increment = x => x + 1; - - const incrementAll = mapper(increment); - - incrementAll([1,2,3] - -\[2,3,4\] - -Example that takes two functions, f and g, and returns a new function that computes f(g()): - - function compose(f, g) { - - return function(...args) { - - return f.call(this, g.apply(this, args)); - - }; - - } - -`const sum = (x,y) => x+y;` - -`const square = x => x*x;` - -`compose(square, sum)(2,3)` - -25 - -### Memoization - -We defined a factorial function that cached its previously computed results. In functional programming, this kind of caching is called memoization. - -### Classes - -JavaScript's classes and prototype-based inheritance mechanism are substantially different from the classes and class-based inheritance mechanism of Java. - -### Classes and Prototypes - -If we define a prototype object and then use `Object.create()` to create objects that inherit from it, we have defined a JavaScript class. - -Factory function that returns a new range object: - - function range(from, to) { - - let r = Object.create(range.methods); - - r.from = from; - - r.to = to; - - return r; - - } - - range.methods = { - - includes(x) { return this.from <= x && x <= this.to; }, - - *[Symbol.iterator]() { - - for(let x = Math.ceil(this.from); x <= this.to; x++) - - yield x; - - }, - - toString() { return "(" + this.from + "..." + this.to +")"; } - - }; - -`let r = range(1,3);` - -`r.includes(2)` - -true - -`r.toString()` - -"(1…3)" - -`[...r]` - -\[1, 2, 3\] - -### Classes and Constructors - -A constructor is a function designed for the initialization of newly created objects. - -The critical feature of constructor invocations is that the `prototype` property of the constructor is used as the prototype of the new object. - -While almost all objects have a prototype, only a few objects have a `prototype` property. It is function objects that have a `prototype` property. - -This means that all objects created with the same constructor function inherit from the same object and are therefore members of the same class. - -A Range class using a constructor - - function Range(from, to) { - - this.from = from; - - this.to = to; - - } - - Range.prototype = { - - includes: function(x) { return this.from <= x && x <= this.to; }, - - [Symbol.iterator]: function*() { - - for(let x = Math.ceil(this.from); x <= this.to; x++) - - yield x; - - }, - - toString: function() { return "(" + this.from + "..." + this.to + ")"; } - - }; - -`let r = new Range(1,3);` - -`r.includes(2)` - -true - -`r.toString()` - -"(1…3)" - -`[...r]` - -\[1, 2, 3\] - -Because the `Range() `constructor is invoked with `new`, it does not have to call `Object.create()` or take any action to create a new object. - -In the first example, the prototype was `range.methods`. This was a convenient and descriptive name, but arbitrary. In the second example, the prototype is `Range.prototype`, and this name is mandatory. - -An invocation of the `Range()` constructor automatically uses `Range.prototype` as the prototype of the `new Range` object. - -### Constructors, Class Identity, and instanceof - -Two objects are instances of the same class if and only if they inherit from the same prototype object. - -The `instanceof` operator is not checking whether `r` was actually initialized by the Range constructor. Instead, it is checking whether `r` inherits from `Range.prototype`. - - function Strange() {} - - Strange.prototype = Range.prototype; - - new Strange() instanceof Range - -true - -If you want to test the prototype chain of an object for a specific prototype and do not want to use the constructor function as an intermediary, you can use the `isPrototypeOf()` method - - range.methods.isPrototypeOf(r); - -### The constructor Property - -Every regular JavaScript function automatically has a `prototype` property. The value of this property is an object that has a single, non-enumerable `constructor` property. - -The value of the `constructor` property is the function object - - let F = function() {}; - - let p = F.prototype; - - let c = p.constructor; - - c === F - -true - -`let o = new F();` - -`o.constructor === F` - -true - -Instances of the Range class, as defined, do not have a constructor property. We can remedy this problem by explicitly adding a constructor to the prototype: - - Range.prototype = { - - constructor: Range - - }; - -Another common technique that you are likely to see in older JavaScript code is to use the predefined prototype object with its constructor property and add methods to it one at a time with code like this: - - Range.prototype.includes = function(x) { - - return this.from <= x && x <= this.to; - - }; - - Range.prototype.toString = function() { - - return "(" + this.from + "..." + this.to + ")"; - - }; - -### Classes with the class Keyword - - class Range { - - constructor(from, to) { - - this.from = from; - - this.to = to; - - } - - includes(x) { return this.from <= x && x <= this.to; } - - *[Symbol.iterator]() { - - for(let x = Math.ceil(this.from); x <= this.to; x++) - - yield x; - - } - - toString() { return `(${this.from}...${this.to})`; } - - } - -`let r = new Range(1,3);` - -`r.includes(2)` - -true - -`r.toString()` - -(1…3) - -`[...r]` - -\[1, 2, 3\] - -Although class bodies are superficially similar to object literals, they are not the same thing. In particular, they do not support the definition of properties with name/value pairs. - -If your class does not need to do any initialization, you can omit the constructor keyword and its body, and an empty constructor function will be implicitly created for you. - -If you want to define a class that subclasses — or inherits from — another class, you can use the `extends` keyword with the class keyword: - - class Span extends Range { - - constructor(start, length) { - - if (length >= 0) { - - super(start, start + length); - - } - - else { - - super(start + length, start); - - } - - } - - } - -class declarations have both statement and expression forms - -`let Square = class { constructor(x) { this.area = x * x; } };` - -`new Square(3).area` - -9 - -### Static methods - -You can define a `static` method within a class body by prefixing the method declaration with the `static` keyword. Static methods are defined as properties of the constructor function rather than properties of the prototype object. - - static parse(s) { - - let matches = s.match(/^\((\d+)\.\.\.(\d+)\)$/); - - if (!matches) { - - throw new TypeError(`Cannot parse Range from "${s}".`) - - } - - return new Range(parseInt(matches[1]), - - parseInt(matches[2])); - - } - -The method defined by this code is `Range.parse()`, not `Range.prototype.parse()`, and you must invoke it through the constructor, not through an instance: - - let r = Range.parse('(1...10)'); - -### Getters, Setters, and other Method Forms - -Within a class body, you can define getter and setter methods just as you can in object literals. The only difference is that in class bodies, you don't put a comma after the getter or setter. - -### Public, Private, and Static Fields - -The ES6 standard only allows the creation of methods (including getters, setters, and generators) and static methods; it does not include syntax for defining fields. - -If you want to define a field on a class instance, you must do that in the constructor function or in one of the methods. And if you want to define a static field for a class, you must do that outside the class body, after the class has been defined. - -Standardization is underway, however, for extended class syntax that allows the definition of instance and static fields, in both public and private forms. - - class Buffer { - - constructor() { - - this.size = 0; - - this.capacity = 4096; - - this.buffer = new Uint8Array(this.capacity); - - } - - } - -←> - - class Buffer { - - size = 0; - - capacity = 4096; - - buffer = new Uint8Array(this.capacity); - - } - -The same proposal that seeks to standardize these instance fields also defines private (with the \# prefix) instance fields. - - class Buffer { - - #size = 0; - - get size() { return this.#size; } - - } - -A related proposal seeks to standardize the use of the `static` keyword for fields. - - static integerRangePattern = /^\((\d+)\.\.\.(\d+)\)$/; - - static parse(s) { - - let matches = s.match(Range.integerRangePattern); - - if (!matches) { - - throw new TypeError(`Cannot parse Range from "${s}".`) - - } - - return new Range(parseInt(matches[1]), matches[2]); - - } - -### Adding Methods to Existing Classes - -We can augment JavaScript classes simply by adding new methods to their prototype objects. - - if (!String.prototype.startsWith) { - - String.prototype.startsWith = function(s) { - - return this.indexOf(s) === 0; - - }; - - } - - Number.prototype.times = function(f, context) { - - let n = this.valueOf(); - - for(let i = 0; i < n; i++) f.call(context, i); - - }; - -### Subclasses - -### Subclasses and Prototypes - -Span subclass of the Range class. This subclass will work just like a Range, but instead of initializing it with a start and an end, we'll instead specify a start and a distance, or span. - - function Span(start, span) { - - if (span >= 0) { - - this.from = start; - - this.to = start + span; - - } - - else { - - this.to = start; - - this.from = start + span; - - } - - } - -Ensure that the `Span` prototype inherits from the `Range` - - Span.prototype = Object.create(Range.prototype); - -We don't want to inherit `Range.prototype.constructor`, so we define our own constructor property: - - Span.prototype.constructor = Span; - -`Span` overrides the `toString()` method - -`Span.prototype.toString = function() {` - `` return `(${this.from}... +${this.to - this.from})`; `` - `};` - -A robust subclassing mechanism needs to allow classes to invoke the methods and constructor of their superclass, but prior to ES6, JavaScript did not have a simple way to do these things. - -### Subclasses with extends and super - - class EZArray extends Array { - - get first() { return this[0]; } - - get last() { return this[this.length-1]; } - - } - -`let a = new EZArray();` - -`a instanceof EZArray` - -true - -`a instanceof Array` - -true - -`a.push(1,2,3,4);` - -`a.pop()` - -4 - -`a.first` - -1 - -`a.last` - -3 - -`Array.isArray(a)` - -true - -`EZArray.isArray(a)` - -true - -`Array.prototype.isPrototypeOf(EZArray.prototype` - -true - -`Array.isPrototypeOf(EZArray)` - -true - -Example demonstrates the use of the `super` keyword to invoke the constructor and methods of the superclass - - class TypedMap extends Map { - - constructor(keyType, valueType, entries) { - - if (entries) { - - for(let [k, v] of entries) { - - if (typeof k !== keyType || typeof v !== valueType) { - - throw new TypeError(`Wrong type for entry [${k}, ${v}]`); - - } - - } - - } - - super(entries); - - this.keyType = keyType; - - this.valueType = valueType; - - } - - set(key, value) { - - if (this.keyType && typeof key !== this.keyType) { - - throw new TypeError(`${key} is not of type${this.keyType}`); - - } - - if (this.valueType && typeof value !== this.valueType) - - { - - throw new TypeError(`${value} is not of type ${this.valueType}`); - - } - - return super.set(key, value); - - } - - } - -You may not use the `this` keyword in your constructor until after you have invoked the superclass constructor with `super()`. This enforces a rule that superclasses get to initialize themselves before subclasses do. - -Once private fields are supported, we could change these properties to `#keyType` and `#valueType` so that they could not be altered from the outside. - -### Class Hierarchies and Abstract Classes - -Define abstract classes — classes that do not include a complete implementation — to serve as a common superclass for a group of related subclasses. - -### Modules - -### Automating Closure-Based Modularity - -Imagine a tool that takes a set of files, wraps the content of each of those files within an immediately invoked function expression, keeps track of the return value of each function, and concatenates everything into one big file. - - const modules = {}; - - function require(moduleName) { return modules[moduleName]; } - - modules["sets.js"] = (function() { - - const exports = {}; - - exports.BitSet = class BitSet { ... }; - - return exports; - - }()); - - modules["stats.js"] = (function() { - - const exports = {}; - - const sum = (x, y) => x + y; - - const square = x = > x * x; - - exports.mean = function(data) { ... }; - - exports.stddev = function(data) { ... }; - - return exports; - - }()); - -writing code like the following to make use of those modules - - const stats = require("stats.js"); - - const BitSet = require("sets.js").BitSet; - - // Now write code using those modules - - let s = new BitSet(100); - - s.insert(10); - - s.insert(20); - - s.insert(30); - - let average = stats.mean([...s]); - -### Modules in ES6 - -ES6 adds import and export keywords to JavaScript and finally supports real modularity as a core language feature. - -ES6 modularity is conceptually the same as Node modularity: each file is its own module, and constants, variables, functions, and classes defined within a file are private to that module unless they are explicitly exported. - -### ES6 Exports - -To export a constant, variable, function, or class from an ES6 module, simply add the keyword export before the declaration - - export const PI = Math.PI; - - export function degreesToRadians(d) { return d * PI / 180; } - - export class Circle { - - constructor(r) { this.r = r; } - - area() { return PI * this.r * this.r; } - - } - -or: - - export { Circle, degreesToRadians, PI }; - -It is common to write modules that export only one value (typically a function or class), and in this case, we usually use export `default` instead of `export` - - export default class BitSet { - - // implementation omitted - - } - -### ES6 Imports - - import BitSet from './bitset.js'; - - import { mean, stddev } from "./stats.js"; - -When importing from a module that defines many exports, however, you can easily import everything with an import statement like this: - - import * as stats from "./stats.js"; - -With the wildcard import shown in the previous example, the importing module would use the imported `mean()` and` stddev()` functions through the stats object, invoking them as `stats.mean()` and `stats.stddev()`. - -Note: not finished. - -### The JavaScript Standard Library - -### The Set Class - -Sets are not ordered or indexed, and they do not allow duplicates. - - let s = new Set(); - - let t = new Set([1, s]); - - let t = new Set(s); - - let unique = new Set("Mississippi"); - -The argument to the `Set()` constructor need not be an array: any iterable object (including other Set objects) is allowed. - -The `add()` method takes a single argument; if you pass an array, it adds the array itself to the set, not the individual array elements. `add()` always returns the set it is invoked on, however, so if you want to add multiple values to a set, you can used chained method calls like. - -it is very important to understand that set membership is based on strict equality checks, like the === operator performs. - -The most important thing we do with sets is not to add and remove elements from them, but to check to see whether a specified value is a member of the set: - -`let oneDigitPrimes = new Set([2,3,5,7]);` - -`oneDigitPrimes.has(2)` - -The Set class is iterable, which means that you can use a `for/of` loop to enumerate all of the elements of a set: - - let sum = 0; - - for(let p of oneDigitPrimes) { - - sum += p; // and add them up - - } - -Because Set objects are iterable, you can convert them to arrays and argument lists with the … spread operator - -`[...oneDigitPrimes]` - -JavaScript Set class always remembers the order that elements were inserted in, and it always uses this order when you iterate a set: the first element inserted will be the first one iterated (assuming you haven't deleted it first), and the most recently inserted element will be the last one iterated. - -Set class also implements a `forEach()` method - - let product = 1; - - oneDigitPrimes.forEach(n => { product *= n; }); - -### The Map Class - - let m = new Map(); - - let n = new Map([["one", 1],["two", 2]]); - - let copy = new Map(n); - - let o = { x: 1, y: 2}; - - let p = new Map(Object.entries(o)); - -map is a set of keys, each of which has an associated value. This is not quite the same as a set of key/value pairs. - -use `has()` to check whether a map includes the specified key; use `delete()` to remove a key (and its associated value) from the map; use `clear()` to remove all key/value pairs from the map; and use the size property to find out how many keys a map contains. - -`set()` method of Map can be chained. - -Any JavaScript value can be used as a key or a value in a Map. This includes` null, undefined`, and `NaN`, as well as reference types like objects and arrays. - -Map compares keys by identity, not by equality. - -`let m = new Map();` - -`m.set({}, 1);` - -`m.set({}, 2);` - -Map a different empty object to the number 2. - -`m.get({})` - -undefined: - -`m.set(m, undefined);` - -`m.has(m)` - -true - -`m.get(m)` - -undefined - -Iterate over map: - -`let m = new Map([["x", 1], ["y", 2]]);` - -`[...m]` - -\[\["x", 1\], \["y", 2\]\] - -`for(let [key, value] of m) {...}` - -Map class iterates in insertion order - -If you want to iterate just the keys or just the associated values of a map, use the `keys()` and `values()` methods: these return iterable objects that iterate keys and values, in insertion order. (The - `entries()` method returns an iterable object that iterates key/value pairs, but this is exactly the same as iterating the map directly.) - - [...m.keys()] - - [...m.values()] - - [...m.entries()] - -Map objects can also be iterated using the `forEach()` - - m.forEach((value, key) => {...} - -Note that the value parameter comes before the key parameter. - -### WeakMap and WeakSet - -The `WeakMap `class is a variant (but not an actual subclass) of the Map class that does not prevent its key values from being garbage collected. - -`WeakMap `keys must be objects or arrays; primitive values are not subject to garbage collection and cannot be used as keys. - -WeakMap implements only the` get(), set(), has(),` and `delete()` methods. In particular, `WeakMap` is not iterable and does not define `keys(), values(),` or `forEach()`. If WeakMap was iterable, then its keys would be reachable and it wouldn't be weak. - -Similarly, WeakMap does not implement the size property because the `size` of a WeakMap could change at any time as objects are garbage collected - -### Typed Arrays and Binary Data - -They differ from regular arrays in some very important ways - -· The elements of a typed array are all numbers. Unlike regular JavaScript numbers, however, typed arrays allow you to specify the type (signed and unsigned integers and IEEE-754 floating point) and size (8 bits to 64 bits) of the numbers to be stored in the array. - -· You must specify the length of a typed array when you create it, and that length can never change. - -· The elements of a typed array are always initialized to 0 when the array is created. - - Int8Array() - - Uint8Array() - - Uint8ClampedArray() - - Int16Array() - - Uint32Array() - - Uint16Array() - - Int32Array() - - BigInt64Array() - - BigUint64Array() - - Float32Array() - - let bytes = new Uint8Array(1024); - - let matrix = new Float64Array(9); - - let sudoku = new Int8Array(81); - -Initialize with values - - let white = Uint8ClampedArray.of(255, 255, 255, 0); - - let ints = Uint32Array.from(white); - -one more way to create typed arrays that involves the `ArrayBuffer` type - - let buffer = new ArrayBuffer(1024*1024); - - buffer.byteLength - -1024\*1024 - -Typed arrays are not true arrays, but they re-implement most array methods, so you can use them pretty much just like you'd use regular arrays: - -`let ints = new Int16Array(10);` - -10 short integers - -`ints.fill(3).map(x=>x*x).join("")` - -"9999999999" - -Remember that typed arrays have fixed lengths, so the length property is read-only, and methods that change the length of the array (such as` push(), pop(), unshift(), shift(),` and `splice()`) are not implemented for typed arrays. Methods that alter the contents of an array without changing the length (such as `sort(), reverse()`, and `fill()`) are implemented. - -### Determine Endianess and DataView - - let littleEndian = new Int8Array(new Int32Array([1]).buffer) - - [0] === 1; - -You can use the `DataView` class, which defines methods for reading and writing values from an `ArrayBuffer` with explicitly specified byte ordering. Refer to book for more examples. - -### Pattern Matching with Regular Expressions - -RegExp objects may be created with the `RegExp()` constructor, of course, but they are more often created using a special literal syntax. - - let pattern = /s$/; - -←> - - let pattern = new RegExp("s$"); - -Regular expressions can also have one or more flag characters that affect how they work - - let pattern = /s$/i; - -i = case insensitive - -Punctuation characters have special meanings in regular expressions: `^ $ . * + ? = ! : | \ / ( ) [ ] { }. `Other punctuation characters, such as quotation marks and @, do not have special meaning and simply match themselves literally in a regular expression. - -If you use the `RegExp()` constructor, keep in mind that any backslashes in your regular expression need to be doubled, since strings also use backslashes as an escape character. - -**Character** - -**Matches** - -`[...]` - -Any one character between the brackets. - -`[^...]` - -Any one character not between the brackets - -`.` - -Any character except newline or another Unicode line terminator. Or, if the `RegExp` uses the s flag, then a period matches any character, including line terminators. - -`\w` - -Any ASCII word character. Equivalent to \[a-zA-Z0-9\_\]. - -`\W` - -Equivalent to \[^a-zA-Z0-9\_\] - -`\s` - -Any Unicode whitespace character. - -`\S` - -Any character that is not Unicode whitespace. - -`\d` - -Equivalent to \[0-9\]. - -`\D` - -Equivalent to \[⁰-9\]. - -`[\b]` - -A literal backspace (special case). - -`[\s\d]` - -Any one whitespace character or digit - -REPETITIONS - -**Character** - -**Meaning** - -`{n,m}` - -Match the previous item at least n times but no more than m times - -`{n,}` - -Match the previous item n or more times. - -`{n}` - -Match exactly n occurrences of the previous item. - -`?` - -Equivalent to {0,1}. - -`+` - -Equivalent to {1,} - -\* - -Equivalent to {0,}. - -**Example** - -**Description** - - let r = /\d{2,4}/; - -Match between two and four digits - - r = /\w{3}\d?/; - -Match exactly three word characters and an optional digit - - r = /\s+java\s+/; - -Match "java" with one or more spaces before and after - - r = /[^(]*/; - -Match zero or more characters that are not open parens - -If you want to match repetitions of more complicated expressions, you'll need to define a group with parentheses - -Be careful when using the \* and ? repetition characters. Since these characters may match zero instances of whatever precedes them, they are allowed to match nothing. - -### NON-GREEDY REPETITION - -It is also possible to specify that repetition should be done in a non-greedy way. Simply follow the repetition character or characters with a question mark: `??, +?, *?`, or even {1,5}?. - -**String** - -**Pattern** - -**Match** - - "aaa" - - /a+/ - - "aaa" - - "aaa" - - /a+?/ - - "a" - -Note that using non-greedy repetition may not always produce the results you expect. This is because regular expression pattern matching is done by findingthe first position in the string at which a match is possible. Since a match is possible starting at the first character of the string, shorter matches starting at subsequent characters are never even considered. - -### ALTERNATION, GROUPING, AND REFERENCES - -**Char** - -**Pattern** - -**Pattern** - -`|` - -`/ab|cd|ef/` - -"ab" or the string "cd" or the string "ef". - -`/\d{3}|[a-z]{4}/` - -either three digits or four lowercase letters. - -`/a|ab/` - -matches only the first letter "a" - -`()` - -`/java(script)?/` - -matches "java" followed by the optional "script" - -`/(ab|cd)+|ef/` - -matches "java" followed by the optional "script" - -If the left alternative matches, the right alternative is ignored, even if it would have produced a "better" match - -Another purpose of parentheses in regular expressions is to define subpatterns within the complete pattern. When a regular expression is successfully matched against a target string, it is possible to extract the portions of the target string that matched any particular parenthesized subpattern. For example, suppose you are looking for one or more lowercase letters followed by one or more digits. You might use the pattern `/[a-z]+\d+/`. But suppose you only really care about the digits at the end of each match. If you put that part of the pattern in parentheses (/\[a-z\]+(\\d+)/), you can extract the digits from any matches you find, - -A related use of parenthesized subexpressions is to allow you to refer back to a subexpression later in the same regular expression. This is done by following a \\ character by a digit or digits. The digits refer to the position of the parenthesized subexpression within the regular expression. For example, \\1 refers back to the first subexpression, and \\3 refers to the third. - -**Match** - -**Pattern** - -zero or more characters within single or double quotes. However, it does not - require the opening and closing quotes to match - - /['"][^'"]*['"]/ - -To require the quotes to match,use a reference - - /(['"])[^'"]*\1/ - -**Character** - -**Meaning** - -| - -match either the subexpression to the left or the subexpression to the right. - -(…) - -Grouping: group items into a single unit that can be used with \*, +, ?, |, and so on. Also remember the characters that match this group for use with later references - -(?:…) - -group items into a single unit, but do not remember the characters that match this group. - -Note` (?:...)` syntax: - -In pattern` "/([Jj]ava(?:[Ss]cript)?)\sis\s(fun\w*)/`" `\2` refers to the text matched by `(fun\w*)` since `(?:[Ss]cript)?)` in not remembered. - -### SPECIFYING MATCH POSITION - -_regular expression anchors_ because they anchor the pattern to a specific position in the search string. The most commonly used anchor elements are ^, which ties the pattern to the beginning of the string, and $, which anchors the pattern to the end of the string. - -**Example** - -**Pattern** - -match the word "JavaScript" on a line by itself - -`/^JavaScript$/` - -To search for "Java" as a word by itself you can try the pattern `/\sJava\s/`, which requires a space before and after the word. But there are two problems with this solution. First, it does not match "Java" at the beginning or the end of a string, but only if it appears with space on either side. Second, when this pattern does find a match, the matched string it returns has leading and trailing spaces, which is not quite what's needed. So instead of matching actual space characters with \\s, match (or anchor to) word boundaries with \\b. The resulting expression is `/\bJava\b/`. - -The element `\B` anchors the match to a location that is not a word boundary. Thus, the pattern `/\B[Ss]cript/` matches "JavaScript" and "postscript", but not "script" or "Scripting". - -You can also use arbitrary regular expressions as anchor conditions. - -If you include an expression within `(?= and )` characters, it is a lookahead assertion, and it specifies that the enclosed characters must match, without actually matching them. - -**Example** - -**Pattern** - -**Matches** - -to match the name of a common programming language, but only if it is followed by a colon - -`/[Jj]ava([Ss]cript)?(?=\:)/` - -matches the word "JavaScript" in "JavaScript: The DefinitiveGuide" - -does not match "Java" in "Java in a Nutshell" - -If you instead introduce an assertion with `(?!`, it is a negative lookahead assertion. - -### FLAGS - -Flags are specified after the second / character of a regular expression literal or as a string passed as the second argument to the RegExp() constructor. - -**Flag** - -**Meaning** - -g - -"global" — that is,that we intend to use it to find all matches within a string rather than just finding the first <a href="http://match.it/" class="markup--anchor markup--p-anchor">match.it</a> does alter the behavior of the String `match()` method and the `RegExp exec()` method in important ways. - -i - -case-insensitive - -m - -"multiline" mode - -s - -useful when working with text that includes newlines.Normally, a "." in a regular expression matches any character except a line terminator. When the s flag is used, however, "." will match any character, including line terminators. - -u - -Unicode. - -Setting the u flag on a RegExp also allows you to use the new `\u{...}` escape sequence for Unicode character and also enables the \\p{...} notation for Unicode character classes. - -y - -"sticky". should match at the beginning of a string or at the first character following the previous match - -### String Methods for Pattern Matching - -### SEARCH() - -Strings support four methods that use regular expressions. - -`"JavaScript".search(/script/ui)` - -4 - -`"Python".search(/script/ui)` - --1 - -`search()` does not support global searches; it ignores the `g` flag of its regular expression argument. - -REPLACE() - -`text.replace(/javascript/gi, "JavaScript");` - -No matter how it is capitalized, replace it with the correct capitalization - -parenthesized subexpressions of a regular expression are numbered from left to right and that the regular expression remembers the text that each subexpression matches. - -to replace quotation marks in a string with other characters: - -`let quote = /"([^"]*)"/g;` - -`'He said "stop"'.replace(quote, '«$1»')` - -'He said «stop»' - -If your RegExp uses named capture groups, then you can refer to the matching text by name rather than by number: - -`let quote = /"(?<quotedText>[^"]*)"/g;` - -`'He said "stop"'.replace(quote, '«$<quotedText>»')` - -'He said «stop»' - -Instead of passing a replacement string as the second argument to replace(), you can also pass a function that will be invoked to compute the replacement value. - -Example to convert decimal integers in a string to hexadecimal: - -`let s = "15 times 15 is 225";` - -`s.replace(/\d+/gu, n => parseInt(n).toString(16))` - -"f times f is e1" - -### MATCH() - -`"7 plus 8 equals 15".match(/\d+/g)` - -\["7", "8", "15"\] - -If the regular expression does not have the `g` flag set, `match()` does not do a global search; it simply searches for the first match. In this nonglobal case, `match()` still returns an array, but the array elements are completely different. - -Thus, if `match()` returns an array a, a\[0\] contains the complete match, a\[1\] contains the substring that matched the first parenthesized expression, and so on. - - let url = /(\w+):\/\/([\w.]+)\/(\S*)/; - - let text = "Visit my blog at http://www.example.com/~david"; - - let match = text.match(url); - - let fullurl, protocol, host, path; - - if (match !== null) { - - fullurl = match[0]; - -<a href="http://www.example.com/~david" class="markup--anchor markup--p-anchor">"http://www.example.com/~david</a>" - - protocol = match[1]; - -"http" - - host = match[2]; - -<a href="http://www.example.com/" class="markup--anchor markup--p-anchor">"www.example.com</a>" - - path = match[3]; - -"~david" - -In this non-global case, the array returned by match() also has some object properties in addition to the numbered array elements. - -input property refers to the string on which match() was called - -The index property is the position within that string at which the match starts. - -if the regular expression contains named capture groups, then the returned array also has a groups property whose value is an object. - -`let url = /(?<protocol>\w+):\/\/(?<host>[\w.]+)\/(?<path>\S*)/;` - -`let text = "Visit my blog at http://www.example.com/~david";` - -`let match = text.match(url);` - -`match[0]` - -<a href="http://www.example.com/~david" class="markup--anchor markup--p-anchor">"http://www.example.com/~david</a>" - -`match.input` - -text - -`match.index` - -17 - -`match.groups.protocol` - -"http" - -`match.groups.host` - -<a href="http://www.example.com/" class="markup--anchor markup--p-anchor">"www.example.com</a>" - -`match.groups.path` - -"~david" - -There are also important but less dramatic differences in behavior when the y flag is set. Refer to book for examples. - -### MATCHALL() - -Instead of returning an array of matching substrings like `match()` does, however, it returns an iterator that yields the kind of match objects that match() returns when used with a non-global RegExp. - -### SPLIT() - -`"123,456,789".split(",")` - -\["123", "456","789"\] - -`"1, 2, 3,\n4, 5".split(/\s*,\s*/)` - -\["1", "2", "3", "4","5"\] - -Surprisingly, if you call `split()` with a RegExp delimiter and the regular expression includes capturing groups, then the text that matches the capturing groups will be included in the returned array. - -`const htmlTag = /<([^>]+)>/;` - -`"Testing<br/>1,2,3".split(htmlTag)` - -\["Testing", "br/","1,2,3"\] - -### The RegExp Class - -The `RegExp()` constructor is useful when a regular expression is being dynamically created and thus cannot be represented with the regular expression literal syntax. - - let zipcode = new RegExp("\\d{5}", "g"); - -`let exactMatch = /JavaScript/;` - `let caseInsensitive = new RegExp(exactMatch, "i");` - -### TEST() - -Returns true or false by calling `exec()`. - -### EXEC() - - let pattern = /Java/g; - - let text = "JavaScript > Java"; - - let match; - - while((match = pattern.exec(text)) !== null) { - - console.log(`Matched ${match[0]} at ${match.index}`); - - console.log(`Next search begins at ${pattern.lastIndex}`); - - } - -### THE LASTINDEX PROPERTY AND REGEXP REUSE - -The use of the `lastIndex` property with the g and y flags is a particularly awkward part of this API. When you use these flags, you need to be particularly careful when calling the `match(), exec()`, or `test()` methods because the behavior of these methods depends on `lastIndex`, and the value of `lastIndex` depends on what you have previously done with the RegExp object. - -To find the index of all <p> tags within a string of HTML text: - - let match, positions = []; - - while((match = /<p>/g.exec(html)) !== null) { - - positions.push(match.index); - - } - -If the html string contains at least one <p> tag, then it will loop forever. For each iteration of the loop, we're creating a new RegExp object with `lastIndex` set to 0, so `exec()` always begins at the start of the string, and if there is a match, it will keep matching over and over. The solution, of course, is to define the RegExp once, and save it to a variable so that we're using the same RegExp object for each iteration of the loop. - -On the other hand, sometimes reusing a RegExp object is the wrong thing to do. Suppose, for example, that we want to loop through all of the words in a dictionary to find words that contain pairs of double letters. - - let dictionary = [ "apple", "book", "coffee" ]; - - let doubleLetterWords = []; - - let doubleLetter = /(\w)\1/g; - - for(let word of dictionary) { - - if (doubleLetter.test(word)) { - - doubleLetterWords.push(word); - - } - - } - -`doubleLetterWords` - -\["apple", "coffee"\]: "book" is missing! - -Because we set the g flag on the RegExp, the `lastIndex` property is changed after successful matches, and the `test()` method (which is based on `exec()`) starts searching for a match at the position specified by `lastIndex`. After matching the "pp" in "apple", `lastIndex` is 3, and so we start searching the word "book" at position 3 and do not see the "oo" that it contains. - -### Dates and Times - - let now = new Date(); - -The current time - - let epoch = new Date(0); - -Midnight, January 1st, 1970, GMT - - let century = new Date(2100, - - 0, - - 1, - - 2, 3, 4, 5); - -Year 2100 - -January - -1st - -02:03:04.005, local - - let century = new Date(Date.UTC(2100, 0, 1)); - -Midnight in GMT, January 1, 2100 - -If you print a date (with console.log(century), for example), it will, by default, be printed in your local time zone. If you want to display a date in UTC, you should explicitly convert it to a string with `toUTCString()` or` toISOString()`. - -if you pass a string to the Date() constructor, it will attempt to parse that string as a date and time specification - -`let century = new Date("2100-01-01T00:00:00Z");` - -Once you have a Date object, various get and set methods allow you to query and modify the year, month, day-of-month, hour, minute, second, and millisecond fields of the Date. Each of these methods hastwo forms: one that gets or sets using local time and one that gets or sets using UTC time. - -Note that the methods for querying the day-of-month are `getDate()` and `getUTCDate()`. The more natural-sounding functions `getDay()` and `getUTCDay()` return the day-of-week (0 for Sunday through 6 for Saturday). The day-of-week is read-only, so there is not a corresponding `setDay()` method. - -### Timestamps - -JavaScript represents dates internally as integers that specify the number of milliseconds since (or before) midnight on January 1, 1970, UTC time. - -For any Date object, the `getTime()` method returns this internal value, and the `setTime()` method sets it. - - d.setTime(d.getTime() + 30000); - -add 30 secs - -The static Date.now() method returns the current time as a timestamp and is helpful when you want to measure how long your code takes to run - - let startTime = Date.now(); - - reticulateSplines(); // Do some time-consuming operation - - let endTime = Date.now(); - - console.log(`Spline reticulation took ${endTime -startTime}ms.`); - -adds three months and two weeks to the current date: - -`let d = new Date();` - `d.setMonth(d.getMonth() + 3, d.getDate() + 14);` - -### Formatting and Parsing Date Strings - - let d = new Date(2020, 0, 1, 17, 10, 30); - - d.toString() - -"Wed Jan 01 2020 17:10:30 GMT-0800 (Pacific Standard Time)" - - d.toUTCString() - -"Thu, 02 Jan 2020 01:10:30 GMT" - - d.toLocaleDateString() - -"1/1/2020": 'en-US' locale - - d.toLocaleTimeString() - -"5:10:30 PM": 'en-US' locale - - d.toISOString() - -"2020-01-02T01:10:30.000Z" - -there is also a static Date.parse() method that takes a string as its argument, attempts to parse it as a date and time, and returns a timestamp representing that date. `Date.parse()` is able to parse the same strings that the `Date()` constructor can and is guaranteed to be able to parse the output of` toISOString(), toUTCString()`, and` toString()`. - -### Error Classes - -One good reason to use an Error object is that, when you create an Error, it captures the state of the JavaScript stack, and if the exception is uncaught, the stack trace will be displayed with the error message, which will help you debug the issue. - -Error objects have two properties: `message` and `name`, and a` toString()` method. Node and all modern browsers also define a `stack` property on Error objects. - -Subclasses are `EvalError, RangeError, ReferenceError, SyntaxError, TypeError,` and `URIError`. - -You should feel free to define your own Error subclasses that best encapsulate the error conditions of your own program. - - class HTTPError extends Error { - - constructor(status, statusText, url) { - - super(`${status} ${statusText}: ${url}`); - - this.status = status; - - this.statusText = statusText; - - this.url = url; - - } - - get name() { return "HTTPError"; } - - } - - let error = new HTTPError(404, "Not Found", "http://example.com/"); - - error.status - -404 - - error.message - -"404 Not Found:<a href="http://example.com/" class="markup--anchor markup--p-anchor">http://example.com/</a>" - - error.name - -HTTPError - -### JSON Serialization and Parsing - -JavaScript supports JSON serialization and deserialization with the two functions `JSON.stringify()` and `JSON.parse().` - - let o = {s: "", n: 0, a: [true, false, null]}; - - let s = JSON.stringify(o); - -s == '{"s":"","n":0,"a":\[true,false,null\]}' - - let copy = JSON.parse(s); - -copy == {s: "", n: 0, a:\[true, false, null\]} - -Inefficient way of creating a deep copy of an object - - function deepcopy(o) { - - return JSON.parse(JSON.stringify(o)); - - } - -Typically, you pass only a single argument to `JSON.stringify()` and `JSON.parse()`. Both functions accept an optional second argument that allows us to extend the JSON format. - -`JSON.stringify()` also takes an optional third argument. If you would like your JSONformatted string to be human-readable (if it is being used as a configuration file, for example), then you should pass null as the second argument and pass a number or string as the third argument. If the third argument is a number, then it will use that number of spaces for each indentation level. If the third argument is a string of whitespace (such as '\\t'), it will use that string for each level of indent. - -### JSON Customizations - -If `JSON.stringify()` is asked to serialize a value that is not natively supported by the JSON format, it looks to see if that value has a `toJSON()` method, and if so, it calls that method and then stringifies the return value in place of the original value. Date objects implement `toJSON()`: it returns the same string that `toISOString()` method does. - -If you need to re-create Date objects (or modify the parsed object inany other way), you can pass a "reviver" function as the second argument to `JSON.parse()`. - - let data = JSON.parse(text, function(key, value) { - - if (key[0] === "_") return undefined; - - if (typeof value === "string" && /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ$/.test(value)) { - - return new Date(value); - - } - - return value; - - }); - -### The Console API - -Console functions that print their arguments like console.log() have a little-known feature: if the first argument is a string that includes `%s, %i, %d, %f, %o, %O, or %c`, then this first argument is treated as format string, and the values of subsequent arguments are substituted into the string in place of the two-character % sequences. - -### URL API - - let url = new URL("https://example.com:8000/path/name?q=term#fragment"); - - url.href - -<a href="https://example.com:8000/path/name" class="markup--anchor markup--p-anchor">"https://example.com:8000/path/name</a>?q=term\#fragment" - - url.origin - -<a href="https://example.com:8000/" class="markup--anchor markup--p-anchor">"https://example.com:8000</a>" - - url.protocol - -"https:" - - url.host - -<a href="http://example.com/" class="markup--anchor markup--p-anchor">"example.com</a>:8000" - - url.hostname - -<a href="http://example.com/" class="markup--anchor markup--p-anchor">"example.com</a>" - - url.port - -"8000" - - url.pathname - -"/path/name" - - url.search - -"?q=term" - - url.hash - -"\#fragment" - - let url = new URL("https://example.com"); - - url.pathname = "api/search"; - -Add a path to an API endpoint - - url.search = "q=test"; - -Add a query parameter - - url.toString() - -<a href="https://example.com/api/search?q=test" class="markup--anchor markup--p-anchor">"https://example.com/api/search?q=test</a>" - -One of the important features of the URL class is that it correctly adds punctuation and escapes special characters in URLs when that is needed - - let url = new URL("https://example.com"); - - url.pathname = "path with spaces"; - - url.pathname - -"/path%20with%20spaces" - - url.search = "q=foo#bar"; - - url.search - -"?q=foo%23bar" - - url.href - -<a href="https://example.com/path%20with%20spaces?q=foo%23bar" class="markup--anchor markup--p-anchor">"https://example.com/path%20with%20spaces?q=foo%23bar</a>" - -Often, however, HTTP requests encode the values of multiple form fields or multiple API parameters into the query portion of a URL. In this format, the query portion of the URL is a question mark followed by one or more name/value pairs, which are separated from one another by ampersands. - -If you want to encode these kinds of name/value pairs into the query portion of a URL, then the searchParams property will be more useful than the search property. - -`let url = new URL("https://example.com/search");` - -`url.search` - -"" - -`url.searchParams.append("q", "term");` - -`url.search` - -"?q=term" - -`url.searchParams.set("q", "x");` - -`url.search` - -"?q=x" - -`url.searchParams.append("opts", "1");` - -`url.search` - -"?q=x&opts=1" - -The value of the searchParams property is a URLSearchParams object. - -`let url = new URL("http://example.com");` - -`let params = new URLSearchParams();` - -`params.append("q", "term");` - -`params.append("opts", "exact");` - -`params.toString()` - -"q=term&opts=exact" - -`url.search = params;` - -`url.href` - -<a href="http://example.com/" class="markup--anchor markup--p-anchor">"http://example.com/</a>?q=term&opts=exact" - -### Timers - -`setTimeout()` and` setInterval()`—that allow programs to ask the browser to invoke a function after a specified amount of time has elapsed or to invoke the function repeatedly at a specified interval. - - setTimeout(() => { console.log("Ready..."); }, 1000); - - setTimeout(() => { console.log("set..."); }, 2000); - - setTimeout(() => { console.log("go!"); }, 3000); - -If you want to invoke a function repeatedly, use `setInterval()` - -Both `setTimeout()` and `setInterval()` return a value. If you save this value in a variable, you can then use it later to cancel the execution of the function by passing it to `clearTimeout()` or `clearInterval()`. - - let clock = setInterval(() => { - - console.clear(); - - console.log(new Date().toLocaleTimeString()); - - }, 1000); - - setTimeout(() => { clearInterval(clock); }, 10000); - -After 10 seconds: stop the repeating code above - -### Iterators and Generators - -The iterator method of an iterable object does not have a conventional name but uses the Symbol, Symbol.iterator as its name. So a simple for/of loop over an iterable object iterable could also be written the hard way, like this: - - let iterable = [99]; - - let iterator = iterable[Symbol.iterator](); - - for(let result = iterator.next(); !result.done; result =iterator.next()) { - - console.log(result.value) // result.value == 99 - - } - -When you want to iterate though a "partially used" iterator: - -`let list = [1,2,3,4,5];` - `let iter = list[Symbol.iterator]();` - -`let head = iter.next().value;` - -head == 1 - -`let tail = [...iter];` - -tail == \[2,3,4,5\] - -### Implementing Iterable Objects - -we will implement the Range class one more time, making it iterable without relying on a generator. - -In order to make a class iterable, you must implement a method whose name is the Symbol `Symbol.iterator` - - class Range { - - constructor (from, to) { - - this.from = from; - - this.to = to; - - } - - has(x) { return typeof x === "number" && this.from <= x && x <= this.to; } - - toString() { return `{ x | ${this.from} ≤ x ≤ ${this.to}}`; } - - [Symbol.iterator]() { - - let next = Math.ceil(this.from); - - let last = this.to; - - return { - - next() { - - return (next <= last) ? { value: next++ } : { done: true }; - - }, - - [Symbol.iterator]() { return this; } - - }; - - } - - } - - for(let x of new Range(1,10)) console.log(x); - -Logs numbers 1 to 10 - - [...new Range(-2,2)] - -\[-2, -1, 0,1, 2\] - -In addition to making your classes iterable, it can be quite useful to define functions that return iterable values. - -Return an iterable object that iterates the result of applying `f()` to each value from the source iterable - - function map(iterable, f) { - - let iterator = iterable[Symbol.iterator](); - - return { - - [Symbol.iterator]() { return this; }, - - next() { - - let v = iterator.next(); - - if (v.done) { - - return v; - - } - - else { - - return { value: f(v.value) }; - - } - - } - - }; - - } - -`[...map(new Range(1,4), x => x*x)]` - -\[1, 4, 9, 16\] - -Return an iterable object that filters the specified iterable, iterating only those elements for which the predicate returns true - - function filter(iterable, predicate) { - - let iterator = iterable[Symbol.iterator](); - - return { - - [Symbol.iterator]() { return this; }, - - next() { - - for(;;) { - - let v = iterator.next(); - - if (v.done || predicate(v.value)) { - - return v; - - } - - } - - } - - }; - - } - -`[...filter(new Range(1,10), x => x % 2 === 0)]` - -\[2,4,6,8,10\] - -### Generators - -Particularly useful when the values to be iterated are not the elements of a data structure, but the result of a computation. - -To create a generator, you must first define a generator function — defined with the keyword `function*` rather than `function` - -When you invoke a generator function, it does not actually execute the function body, but instead returns a generator object. This generator object is an iterator. - -Calling its `next()` method causes the body of the generator function to run from the start (or whatever its current position is) until it reaches a `yield` statement. - -The value of the `yield` statement becomes the value returned by the `next()` call on the iterator. - - function* oneDigitPrimes() { - - yield 2; - - yield 3; - - yield 5; - - yield 7; - - } - - let primes = oneDigitPrimes(); - -we get a generator - - primes.next().value - -2 - - primes.next().value - -3 - - primes.next().value - -5 - - primes.next().value - -7 - - primes.next().done - -true - -Generators have a `Symbol.iterator` method to make them iterable - -`primes[Symbol.iterator]()` - -`[...oneDigitPrimes()]` - -\[2,3,5,7\] - - let sum = 0; - - for(let prime of oneDigitPrimes()) sum += prime; - - sum - -17 - -Like regular functions, however, we can also define generators in expression form. - - const seq = function*(from,to) { - - for(let i = from; i <= to; i++) yield i; - - }; - - [...seq(3,5)] - -\[3, 4, 5\] - -In classes and object literals, we can use shorthand notation to omit the function keyword entirely when we define methods. - - let o = { - - x: 1, y: 2, z: 3, - - *g() { - - for(let key of Object.keys(this)) { - - yield key; - - } - - } - - }; - -`[...o.g()]` - -\["x", "y", "z", "g"\] - -Generators often make it particularly easy to define iterable classes. - - *[Symbol.iterator]() { - - for(let x = Math.ceil(this.from); x <= this.to; x++) - - yield x; - - } - -### Generator Examples - -Generators are more interesting if they actually generate the values they yield by doing some kind of computation. - -generator function that yields Fibonacci numbers - - function* fibonacciSequence() { - - let x = 0, y = 1; - - for(;;) { - - yield y; - - [x, y] = [y, x+y]; - - } - - } - -If this generator is used with the … spread operator, it will loop until memory is exhausted and the program crashes. - -Use it in a `for/of` loop, however - - function fibonacci(n) { - - for(let f of fibonacciSequence()) { - - if (n-- <= 0) return f; - - } - - } - - fibonacci(20) - -10946 - -This kind of infinite generator becomes more useful with a `take()` generator like this - - function* take(n, iterable) { - - let it = iterable[Symbol.iterator](); - - while(n-- > 0) { - - let next = it.next(); - - if (next.done) return; - - else yield next.value; - - } - - } - - [...take(5, fibonacciSequence())] - -\[1, 1, 2, 3, 5\] - -### Asynchronous Javascript - -`Promises`, new in ES6, are objects that represent the not-yet-available result of an asynchronous operation. - -The keywords `async` and `await` were introduced in ES2017 and provide new syntax that simplifies asynchronous programming by allowing you to structure your Promise based code as if it was synchronous. - -Asynchronous iterators and the` for/await` loop were introduced in ES2018 and allow you to work with streams of asynchronous events using simple loops that appear synchronous. - -### Asynchronous Programming with Callbacks - -### Timers - -`setTimeout(checkForUpdates, 60000);` - - let updateIntervalId = setInterval(checkForUpdates, 60000); - - function stopCheckingForUpdates() { - - clearInterval(updateIntervalId); - - } - -### Events - -Event-driven JavaScript programs register callback functions for specified types of events in specified contexts, and the web browser invokes those functions whenever the specified events occur. - -These callback functions are called event handlers or event listeners, and they are registered with `addEventListener()` - -Ask the web browser to return an object representing the HTML <button> element that matches this CSS selector: - -`let okay = document.querySelector('#confirmUpdateDialogbutton.okay');` - -Now register a callback function to be invoked when the user clicks on that button - -`okay.addEventListener('click', applyUpdate);` - -### Network Events - -JavaScript running in the browser can fetch data from a web server with code like this: - - function getCurrentVersionNumber(versionCallback) { - - let request = new XMLHttpRequest(); - - request.open("GET", "http://www.example.com/api/version"); - - request.send(); - - request.onload = function() { - - if (request.status === 200) { - - let currentVersion = parseFloat(request.responseText); - - versionCallback(null, currentVersion); - - } - - else { - - versionCallback(response.statusText, null); - - } - - }; - - request.onerror = request.ontimeout = function(e) { - - versionCallback(e.type, null); - - }; - - } - -### Promises - -Promises, a core language feature designed to simplify asynchronous programming. - -A Promise is an object that represents the result of an asynchronous computation. That result may or may not be ready yet, and the Promise API is intentionally vague about this: there is no way to synchronously get the value of a Promise; you can only ask the Promise to call a callback function when the value is ready. - -One real problem with callback-based asynchronous programming is that it is common to end up with callbacks inside callbacks inside callbacks, with lines of code so highly indented that it is difficult to read. - -Promises allow this kind of nested callback to be re-expressed as a more linear Promise chain that tends to be easier to read and easier to reason about. - -Another problem with callbacks is that they can make handling errors difficult. If an asynchronous function (or an asynchronously invoked callback) throws an exception, there is no way for that exception to propagate back to the initiator of the asynchronous operation. This is a fundamental fact about asynchronous programming: it breaks exception handling. Promises help here by standardizing a way to handle errors and providing a way for errors to propagate correctly through a chain of promises. - -Note that Promises represent the future results of single asynchronous computations. They cannot be used to represent repeated asynchronous computations, however. - -We can't use Promises to replace `setInterval()` because that function invokes a callback function repeatedly, which is something that Promises are just not designed to do. - -### Using Promises - -How we would use this Promise returning utility function - - getJSON(url).then(jsonData => { - - // callback function that will be asynchronously invoked with the parsed JSON value when it becomes available. - - }); - -The Promise object defines a then() instance method. Instead of passing our callback function directly to `getJSON()`, we instead pass it to the then() method. When the HTTP response arrives, the body of that response is parsed as JSON, and the resulting parsed value is passed to the function that we passed to `then()`. - -If you call the `then()` method of a Promise object multiple times, each of the functions you specify will be called when the promised computation is complete. - -Unlike many event listeners, though, a Promise represents a single computation, and each function registered with then() will be invoked only once. - - function displayUserProfile(profile) { ...} - - getJSON("/api/user/profile").then(displayUserProfile); - -### HANDLING ERRORS WITH PROMISES - -Asynchronous operations, particularly those that involve networking, can typically fail in a number of ways, and robust code has to be written to handle the errors that will inevitably occur. - -`getJSON("/api/user/profile").then(displayUserProfile, handleProfileError);` - -if `getJSON()` runs normally, it passes its result to `displayUserProfile()`. If there is an error (the user is not logged in, the server is down, the user's internet connection dropped, the request timed out, etc.), then `getJSON()` passes an Error object to `handleProfileError()`. - -In practice, it is rare to see two functions passed to then(). There is a better and more idiomatic way of handling errors when working with Promises. - -To understand it, first consider what happens if `getJSON()` completes normally but an error occurs in `displayUserProfile()`. That callback function is invoked asynchronously when `getJSON()` returns, so it is also asynchronous and cannot meaningfully throw an exception (because there is no code on the call stack to handle it). - - getJSON("/api/user/profile").then(displayUserProfile).catch(handleProfileError); - -With this code, a normal result from` getJSON()` is still passed to `displayUserProfile()`, but any error in `getJSON()` or in `displayUserProfile()` (including any exceptions thrown by `displayUserProfile`) get passed to `handleProfileError()`. - -### Chaining Promises - -One of the most important benefits of Promises is that they provide a natural way to express a sequence of asynchronous operations as a linear chain of `then()` method invocations, without having to nest each operation within the callback of the previous one. - - fetch(documentURL) - - .then(response => response.json()) - - .then(document => {return render(document); }) - - .then(rendered => {cacheInDatabase(rendered); }) - - .catch(error => handle(error)); - -has largely been replaced by the newer, Promise-based Fetch API. In its simplest form, this new HTTP API is just the function fetch(). That promise is fulfilled when the HTTP response begins to arrive and the HTTP status and headers are available. - - fetch("/api/user/profile") - - .then(response => { - - if (response.ok && response.headers.get("Content-Type") === "application/json") { - - // What can we do here? We don't actually have the response body yet. - - } - - }); - -But although the initial Promise is fulfilled, the body of the response may not yet have arrived. So these `text()` and` json()` methods for accessing the body of the response themselves return Promises. - - fetch("/api/user/profile") - - .then(response => { - - return response.json(); - - }) - - .then(profile => { - - displayUserProfile(profile); - - }); - -There is a second `then()` in the chain, which means that the first invocation of the `then()` method must itself return a Promise. That is not how Promises work, however. - -When we write a chain of `.then()` invocations, we are not registering multiple callbacks on a single Promise object. Instead, each invocation of the `then()` method returns a new Promise object. That new Promise object is not fulfilled until the function passed to `then()` is complete. - - fetch(theURL) // task 1; returns promise 1 - - .then(callback1) // task 2; returns promise 2 - - .then(callback2); // task 3; returns promise 3 - -### Resolving Promises - -There is actually a fourth Promise object involved as which brings up the point of what it means for a Promise to be "resolved." - -fetch() returns a Promise object which, when fulfilled, passes a Response object to the callback function we register. This Response object has `.text(), .json(),` and other methods to request the body of the HTTP response in various forms. But since the body may not yet have arrived, these methods must return Promise objects. - -"task 2" calls the `.json()` method and returns its value. This is the fourth Promise object, and it is the return value of the `callback1()` function. - -Let's consider: - - function c1(response) { - - let p4 = response.json(); - - return p4; - - } - - // callback 1 - - // returns promise 4 - - function c2(profile) { - - displayUserProfile(profile); - - } - - // callback 2 - - let p1 = fetch("/api/user/profile"); - - promise 1, task 1 - - let p2 = p1.then(c1); - - promise 2, task 2 - - let p3 = p2.then(c2); - - promise 3, task 3 - -In order for Promise chains to work usefully, the output of task 2 must become the input to task 3. The input to task 3 is the body of the URL that was fetched, parsed as a JSON object. But the return value of callback c1 is not a JSON object, but Promise p4 for that JSON object. - -When p1 is fulfilled, c1 is invoked, and task 2 begins. And when p2 is fulfilled, c2 is invoked, and task 3 begins. - -And when p2 is fulfilled, c2 is invoked, and task 3 begins. But just because task 2 begins when c1 is invoked,it does not mean that task 2 must end when c1 returns. - -Promises are about managing asynchronous tasks, and if task 2 is asynchronous, then that task will not be complete by the time the callback returns. - -When you pass a callback c to the `then()` method, `then()` returns a Promise p and arranges to asynchronously invoke c at some later time. The callback performs some computation and returns a value v. When the callback returns, p is resolved with the value v. When a Promise is resolved with a value that is not itself a Promise, it is immediately fulfilled with that value. - -So if c returns a non-Promise, that return value becomes the value of p, p is fulfilled and we are done. But if the return value v is itself a Promise, then p is resolved but not yet fulfilled. - -At this stage, p cannot settle until the Promise v settles. If v is fulfilled, then p will be fulfilled to the same value. If v is rejected, then p will be rejected for the same reason. This is what the "resolved" state of a Promise means - -the Promise has become associated with, or "locked onto," another Promise. We don't know yet whether p will be fulfilled or rejected, but our callback c no longer has any control over that. p is "resolved" in the sense that its fate now depends entirely on what happens to Promise v. - -Let's bring this back to our URL-fetching example. When c1 returns p4, p2 is resolved. But being resolved is not the same as being fulfilled, so task 3 does not begin yet. When the full body of the HTTP response becomes available, then the .`json()` method can parse it and use that parsed value to fulfill p4. When p4 is fulfilled, p2 is automatically fulfilled as well, with the same parsed JSON value. At this point, the parsed JSON object is passed to c2, and task 3 begins. - -### More on Promises and Errors - -With synchronous code, if you leave out error-handling code, you'll at least get an exception and a stack trace that you can use to figure out what is going wrong. With asynchronous code, unhandled exceptions will often go unreported, and errors can occur silently, making them much harder to debug. The good news is that the `.catch()` method makes it easy to handle errors when working with Promises. - -THE CATCH AND FINALLY METHODS - -The `.catch()` method of a Promise is simply a shorthand way to call `.then()` with null as the first argument and an error-handling callback as the second argument. - -Normal exceptions don't work with asynchronous code. The `.catch()` method of Promises is an alternative that does work for asynchronous code. - - fetch("/api/user/profile") - - .then(response => { - - if (!response.ok) { - - return null; - - } - - let type = response.headers.get("content-type"); - - if (type !== "application/json") { - - throw new TypeError(`Expected JSON, got ${type}`); - - } - - return response.json(); - - }) - - .then(profile => { - - if (profile) { - - displayUserProfile(profile); - - } - - else { - - displayLoggedOutProfilePage(); - - } - - }) - - .catch(e => { - - if (e instanceof NetworkError) { - - displayErrorMessage("Check your internet connection."); - - } - - else if (e instanceof TypeError) { - - displayErrorMessage("Something is wrong with our server!"); - - } - - else { - - console.error(e); - - } - - }); - -p1 is the Promise returned by the `fetch()` call - -p2 is the Promise returned by the first `.then()` call - -c1 is the callback that we pass to that .`then()` call - -p3 is the Promise returned by the second `.then()` call - -c2 is the callback we pass to that call - -c3 is the callback that we pass to the `.catch()` call - -The first thing that could fail is the fetch() request itself. Let's say p1 was rejected with a NetworkError object. - -We didn't pass an error-handling callback function as the second argument to the `.then()` call, so p2 rejects as well with the same NetworkError object. - -Without a handler, though, p2 is rejected, and then p3 is rejected for the same reason. - -At this point, the c3 error-handling callback is called, and the NetworkError-specific code within it runs. - -There are a couple of things worth noting about this code. First, notice that the error object thrown with a regular, synchronous throw statement ends up being handled asynchronously with a `.catch()` method invocation in a Promise chain. This should make it clear why this shorthand method is preferred over passing a second argument to .`then()`, and also why it is so idiomatic to end Promise chains with a `.catch()` call. - -it is also perfectly valid to use `.catch()` elsewhere in a Promise chain. If one of the stages in your Promise chain can fail with an error, and if the error is some kind of recoverable error that should not stop the rest of the chain from running, then you can insert a `.catch()` call in the chain, resulting in code that might look like this: - - startAsyncOperation() - - .then(doStageTwo) - - .catch(recoverFromStageTwoError) - - .then(doStageThree) - - .then(doStageFour) - - .catch(logStageThreeAndFourErrors); - -If the callback returns normally, then the `.catch()` callback will be skipped, and the return value of the previous callback will become the input to the next .`then()` callback. - -Once an error has been passed to a `.catch()` callback, it stops propagating down the Promise chain. A `.catch()` callback can throw a new error, but if it returns normally, than that return value is used to resolve and/or fulfill the associated Promise, and - the error stops propagating. - -Sometimes, in complex network environments, errors can occur more or less at random, and it can be appropriate to handle those errors by simply retrying the asynchronous request. - - queryDatabase() - - .catch(e => wait(500).then(queryDatabase)) - - .then(displayTable) - - .catch(displayDatabaseError); - -### Promises in Parallel - -Sometimes,we want to execute a number of asynchronous operations in parallel. The function `Promise.all()` can do this. `Promise.all()` takes an array of Promise objects as its input and returns a Promise. - -The returned Promise will be rejected if any of the input Promises are rejected. Otherwise, it will be fulfilled with an array of the fulfillment values of each of the input Promises. - - const urls = [ /* zero or more URLs here */ ]; - - promises = urls.map(url => fetch(url).then(r => r.text())); - - Promise.all(promises) - - .then(bodies => { /* do something with the array of strings */ }) - - .catch(e => console.error(e)); - -The Promise returned by `Promise.all()` rejects when any of the input Promises is rejected. This happens immediately upon the first rejection and can happen while other input Promises are still pending. In ES2020, `Promise.allSettled()` takes an array of input - Promises and returns a Promise, just like Promise.all() does. But `Promise.allSettled()` never rejects the returned Promise, and it does not fulfill that Promise until all of the input Promises have settled. The Promise resolves to an array of objects, with one object for each input Promise. Each of these returned objects has a status property set to "fulfilled" or "rejected." If the status is "fulfilled", then the object will also have a value property that gives the fulfillment value. And if the status is "rejected", then the object will also have a reason property that gives the error or rejection value of the corresponding Promise. - - Promise.allSettled([Promise.resolve(1), Promise.reject(2),3]).then(results => { - - results[0] // => { status: "fulfilled", value: 1 } - - results[1] // => { status: "rejected", reason: 2 } - - results[2] // => { status: "fulfilled", value: 3 } - - }); - -Occasionally, you may want to run a number of Promises at once but may only care about the value of the first one to fulfill. In that case, you can use `Promise.race()` instead of `Promise.all()`. It returns a Promise that is fulfilled or rejected when the first of the Promises in the input array is fulfilled or rejected. - -### Making Promises - -### Promises in Sequence - -### async and await - -These new keywords dramatically simplify the use of Promises and allow us to write Promise-based, asynchronous code that looks like synchronous code that blocks while waiting for network responses or other asynchronous events. - -Asynchronous code can't return a value or throw an exception the way that regular synchronous code can. And this is why Promises are designed the way the are. The value of a fulfilled Promise is like the return value of a synchronous function. And the value of a rejected Promise is like a value thrown by a synchronous function. - -`async` and `await` take efficient, Promise-based code and hide the Promises so that your asynchronous code can be as easy to read and as easy to reason about as inefficient, blocking, synchronous code. - -Given a Promise object p, the expression await p waits until p settles. If p fulfills, then the value of await p is the fulfillment value of p. On the other hand, if p is rejected, then the await p expression throws the rejection value of p. - - let response = await fetch("/api/user/profile"); - - let profile = await response.json(); - -It is critical to understand right away that the `await` keyword does not cause your program to block and literally do nothing until the specified Promise settles. The code remains asynchronous, and the `await` simply disguises this fact. This means that any code that uses await is itself asynchronous. - -### async Functions - -Because any code that uses await is asynchronous, there is one critical rule: you can only use the await keyword within functions that have been declared with the `async` keyword. - - async function getHighScore() { - - let response = await fetch("/api/user/profile"); - - let profile = await response.json(); - - return profile.highScore; - - } - -Declaring a function `async` means that the return value of the function will be a Promise even if no Promise-related code appears in the body of the function. - -The `getHighScore()` function is declared `async`, so it returns a Promise. And because it returns a Promise, we can use the `await` keyword with it: - - displayHighScore(await getHighScore()); - -### Awaiting Multiple Promises - -Suppose that we've written our `getJSON()` function using async: - - async function getJSON(url) { - - let response = await fetch(url); - - let body = await response.json(); - - return body; - - } - -And now suppose that we want to fetch two JSON values with this function - - let value1 = await getJSON(url1); - - let value2 = await getJSON(url2); - -The problem with this code is that it is unnecessarily sequential: the fetch of the second URL will not begin until the first fetch is complete. If the second URL does not depend on the value obtained from the firstURL, then we should probably try to fetch the two values at the same time. - - let [value1, value2] = await Promise.all([getJSON(url1), getJSON(url2)]); - -### The for/await Loop - -Suppose you have an array of URLs: - - const urls = [url1, url2, url3]; - -You can call fetch() on each URL to get an array of Promises: - - const promises = urls.map(url => fetch(url)); - -We could now use` Promise.all()` to wait for all the Promises in the array to be fulfilled. But suppose we want the results of the first fetch as soon as they become available and don't want to wait for all the URLs to be fetched. - - for(const promise of promises) { - - response = await promise; - - handle(response); - - } - -←> - - for await (const response of promises) { - - handle(response); - - } - -both examples will only work if they are within functions declared async; a `for/await` loop is no different than a regular await expression in that way - -#### If you found this guide helpful feel free to checkout my GitHub/gist's where I host similar content: - -<a href="https://gist.github.com/bgoonz" class="markup--anchor markup--p-anchor"><strong>bgoonz's</strong> gists · GitHub</a> - -<a href="https://github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://github.com/bgoonz"><strong>bgoonz — Overview</strong> -<br/> - -<em>Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…</em>github.com</a><a href="https://github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -Or checkout my personal resource site: - -<a href="https://goofy-euclid-1cd736.netlify.app/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://goofy-euclid-1cd736.netlify.app/"><strong>a/A-Student-Resources</strong> -<br/> - -<em>Edit description</em>goofy-euclid-1cd736.netlify.app</a><a href="https://goofy-euclid-1cd736.netlify.app/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [March 8, 2021](https://medium.com/p/64306cd6b0db). - -<a href="https://medium.com/@bryanguner/complete-javascript-reference-guide-64306cd6b0db" class="p-canonical">Canonical link</a> - -August 31, 2021. diff --git a/notes/articles/medium/markdown/The-Complete-JavaScript-Reference.md b/notes/articles/medium/markdown/The-Complete-JavaScript-Reference.md deleted file mode 100644 index 0fc1892fcf..0000000000 --- a/notes/articles/medium/markdown/The-Complete-JavaScript-Reference.md +++ /dev/null @@ -1,5683 +0,0 @@ -# The Complete JavaScript Reference Guide - -You will want to bookmark this - ---- - -### The Complete JavaScript Reference Guide - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*In5wB-29T0Ud_zs3.jpg" class="graf-image" /></figure>### How to learn effectively - -**Learning**: The acquisition of skills and the ability to apply them in the future. - -**What makes an Effective learner?** - -- <span id="7504">They are active listeners.</span> -- <span id="179b">They are engaged with the material.</span> -- <span id="3193">They are receptive of feedback.</span> -- <span id="17d8">They are open to difficulty.</span> - -**Why do active learning techniques feel difficult?** - -- <span id="7848">It feels difficult because you are constantly receiving feedback, and so you are constantly adapting and perfecting the material.</span> - -**Desirable Difficulty** - -- <span id="67c9">The skills we wish to obtain is often a difficult one.</span> -- <span id="c939">We want challenging but possible lessons based on current level of skill.</span> - -**Effective learners space their practice** - -- <span id="59a4">Consistent effort > cramming => for **durable knowledge**</span> - ---- - -### Getting visual feedback in your programs - -The first command we'll learn in JavaScript is `console.log`. This command is used to _print_ something onto the screen. As we write our first lines of code, we'll be using `console.log` frequently as a way to visually see the output of our programs. Let's write our first program: - - console.log("hello world"); - console.log("how are you?"); - -Executing the program above would print out the following: - - hello world - how are you? - -Nothing too ground breaking here, but pay close attention to the exact way we wrote the program. In particular, notice how we lay out the periods, parentheses, and quotation marks. We'll also terminate lines with semicolons (;). - -> _Depending on how you structure your code, sometimes you'll be able to omit semicolons at the end of lines. For now, you'll want to include them just as we do._ - -### Syntax - -We refer to the exact arrangement of the symbols, characters, and keywords as **syntax**. These details matter — your computer will only be able to "understand" proper JavaScript syntax. A programming language is similar to a spoken language. A spoken language like English has grammar rules that we should follow in order to be understood by fellow speakers. In the same way, a programming language like JavaScript has syntax rules that we ought to follow! - -As you write your first lines of code in this new language, you may make many syntax errors. Don't get frustrated! This is normal — all new programmers go through this phase. Every time we recognize an error in our code, we have an opportunity to reinforce your understanding of correct syntax. Adopt a growth mindset and learn from your mistakes. - -Additionally, one of the best things about programming is that we can get such immediate feedback from our creations. There is no penalty for making a mistake when programming. Write some code, run the code, read the errors, fix the errors, rinse and repeat! - -### Code comments - -Occasionally we'll want to leave **comments** or notes in our code. Commented lines will be ignored by our computer. This means that we can use comments to write plain english or temporarily avoid execution of some JavaScript lines. The proper _syntax_ for writing a comment is to begin the line with double forward slashes (`//`): - - // let's write another program!!! - console.log("hello world"); - - // console.log("how are you?"); - - console.log("goodbye moon"); - -The program above would only print: - - hello world - goodbye moon - -Comments are useful when annotating pieces of code to offer an explanation of how the code works. We'll want to strive to write straightforward code that is self-explanatory when possible, but we can also use comments to add additional clarity. The real art of programming is to write code so elegantly that it is easy to follow. - -**The Number Data Type** - -The **number** data type in JS is used to represent any numerical values, including integers and decimal numbers. - -**Basic Arithmetic Operators** - -Operators are the symbols that perform particular operations. - -- <span id="f533">**+** (addition)</span> -- <span id="5b9f">**-** (subtraction)</span> -- <span id="b98b">**asterisk** (multiplication)</span> -- <span id="9a15">**/** (division)</span> -- <span id="c752">**%** (modulo)</span> - -JS evaluates more complex expressions using the general math order of operations aka PEMDAS. - -- <span id="b6e3">**PEMDAS** : Parentheses, Exponents, Multiplication, Division, Modulo, Addition, Subtraction.</span> -- <span id="9c25">_To force a specific order of operation, use the group operator ( ) around a part of the expression._</span> - -**Modulo** : Very useful operation to check divisibility of numbers, check for even & odd, whether a number is prime, and much more! _(Discrete Math concept, circular problems can be solved with modulo)_ - -- <span id="cf5b">Whenever you have a smaller number % a larger number, the answer will just be the initial small number. - console.log(7 % 10) // => 7;</span> - -**The String Data Type** - -The **string** data type is a primitive data type that used to represent textual data. - -- <span id="e1b0">can be wrapped by either **single** or **double** quotation marks, _best to choose one and stick with it for consistency_.</span> -- <span id="f8ad">If your string contains quotation marks inside, can layer single or double quotation marks to allow it to work. - "That's a great string"; (valid) - 'Shakespeare wrote, "To be or not to be"'; (valid) - 'That's a bad string'; (invalid)</span> -- <span id="b2cb">Alt. way to add other quotes within strings is to use template literals. - \`This is a temp'l'ate literal ${function}\` // use ${} to invoke functions within.</span> -- <span id="7b1a">**.length** : property that can be appended to data to return the length.</span> -- <span id="f633">empty strings have a length of zero.</span> -- <span id="0a07">**indices** : indexes of data that begin at 0, can call upon index by using the bracket notation \[ \]. - console.log("bootcamp"\[0\]); // => "b" - console.log("bootcamp"\[10\]); // => "undefined" - console.log("boots"\[1 \* 2\]); // => "o" - console.log("boots"\["boot".length-1\]); // => "t"</span> -- <span id="6482">we can pass expressions through the brackets as well since JS always evaluates expressions first.</span> -- <span id="e2f5">The index of the last character of a string is always one less than it's length.</span> -- <span id="2271">**indexOf()** : method used to find the first index of a given character within a string. - console.log("bagel".indexOf("b")); // => 0 - console.log("bagel".indexOf("z")); // => -1</span> -- <span id="8d68">if the character inside the indexOf() search does not exist in the string, the output will be -1.</span> -- <span id="d15e">the indexOf() search will return the first instanced index of the the char in the string.</span> -- <span id="a275">**concatenate** : word to describe joining strings together into a single string.</span> - -**The Boolean Data Type** - -The **Boolean** data type is the simplest data type since there are only two values: **true** and **false**. - -- <span id="60da">**Logical Operators** (B*oolean Operators*) are used to establish logic in our code.</span> -- <span id="139b">**!** (not) : reverses a Boolean value. - console.log(!true); // => false - console.log(!!false); // => false</span> -- <span id="e412">**Logical Order of Operations** : JS will evaluate !, then &&, then ||.</span> -- <span id="99ad">**Short-Circuit Evaluation** : Because JS evalutes from left to right, expressions can "short-circuit". For example if we have true on the left of an || logical comparison, it will stop evaluating and yield true instead of wasting resources on processing the rest of the statement. - console.log(true || !false) // => stops after it sees "true ||"</span> - -**Comparison Operators** - -All comparison operators will result in a boolean output. - -**The relative comparators** - -- <span id="6fee">**>** (greater than)</span> -- <span id="0437">**<** (less than)</span> -- <span id="17ff">**>=** (greater than or equal to)</span> -- <span id="b2b4">**<=** (less than or equal to)</span> -- <span id="0c13">**===** (equal to)</span> -- <span id="b73a">**!==** (not equal to)</span> - -Fun Fact: "a" < "b" is considered valid JS Code because string comparisons are compared lexicographically (meaning dictionary order), so "a" is less than "b" because it appears earlier! - -If there is ever a standstill comparison of two string lexicographically (i.e. app vs apple) the comparison will deem the shorter string lesser. - -**Difference between == and ===** - -#### === - -Strict Equality, will only return true if the two comparisons are entirely the same. - -#### == - -Loose Equality, will return true even if the values are of a different type, due to coercion. (Avoid using this) - -**Variables** - -Variables are used to store information to be referenced and manipulated in a program. - -- <span id="c73d">We initialize a variable by using the **let** keyword and a **=** single equals sign (assignment operator). - let bootcamp = "App Academy"; - console.log(bootcamp); // "App Academy"</span> -- <span id="7849">JS variable names can contain any alphanumeric characters, underscores, or dollar signs (cannot being with a number).</span> -- <span id="ad76">If you do not declare a value for a variable, undefined is automatically set. - let bootcamp; - console.log(bootcamp); // undefined</span> -- <span id="2188">We can change the value of a previously declared variable (let, not const) by re-assigning it another value.</span> -- <span id="47ca">**let** is the updated version of **var**; there are some differences in terms of hoisting and global/block scope</span> - -**Assignment Shorthand** - -let num = 0; - num += 10; // same as num = num + 10 - num -= 2; // same as num = num — 2 - num /= 4; // same as num = num / 4 - num \*= 7; // same as num = num \* 7 - -- <span id="9c05">In general, any nonsensical arithmetic will result in **NaN** ; usually operations that include undefined.</span> - -**Functions** - -A function is a procedure of code that will run when called. Functions are used so that we do not have to rewrite code to do the same thing over and over. (Think of them as 'subprograms') - -- <span id="366f">**Function Declaration** : Process when we first initially write our function.</span> -- <span id="676f">Includes three things:</span> -- <span id="80c2">Name of the function.</span> -- <span id="f3a4">A list of _parameters_ ()</span> -- <span id="2b0e">The code to execute {}</span> -- <span id="6879">**Function Calls** : We can call upon our function whenever and wherever\* we want. (\*wherever is only after the initial declaration)</span> -- <span id="8374">JS evaluates code top down, left to right.</span> -- <span id="2687">When we execute a declared function later on in our program we refer to this as **invoking** our function.</span> -- <span id="0c3a">Every function in JS returns undefined unless otherwise specified.</span> -- <span id="4207">When we hit a **return** statement in a function we immediately exit the function and return to where we called the function.</span> -- <span id="e39f">When naming functions in JS always use camelCase and name it something appropriate.</span> - -Greate code reads like English and almost explains itself. Think: Elegant, readable, and maintainable! - -**Parameters and Arguments** - -- <span id="e94e">**Parameters** : Comma seperated variables specified as part of a function's declaration.</span> -- <span id="6740">**Arguments** : Values passed to the function when it is invoked.</span> -- <span id="004c">_If the number of arguments passed during a function invocation is different than the number of paramters listed, it will still work._</span> -- <span id="7da5">However, is there are not enough arguments provided for parameters our function will likely yield **Nan**.</span> - -### Including Comments - -Comments are important because they help other people understand what is going on in your code or remind you if you forgot something yourself. Keep in mind that they have to be marked properly so the browser won't try to execute them. - -In JavaScript you have two different options: - -- <span id="356d">Single-line comments — To include a comment that is limited to a single line, precede it with `//`</span> -- <span id="ee3a">Multi-line comments — In case you want to write longer comments between several lines, wrap it in `/*` and `*/` to avoid it from being executed</span> - -### Variables in JavaScript - -Variables are stand-in values that you can use to perform operations. You should be familiar with them from math class. - -### var, const, let - -You have three different possibilities for declaring a variable in JavaScript, each with their own specialties: - -- <span id="4b29">`var` — The most common variable. It can be reassigned but only accessed within a function. Variables defined with `var` move to the top when the code is executed.</span> -- <span id="d234">`const` — Can not be reassigned and not accessible before they appear within the code.</span> -- <span id="0e3b">`let` — Similar to `const`, the `let` variable can be reassigned but not re-declared.</span> - -### Data Types - -Variables can contain different types of values and data types. You use `=` to assign them: - -- <span id="b276">Numbers — `var age = 23`</span> -- <span id="5571">Variables — `var x`</span> -- <span id="e26c">Text (strings) — `var a = "init"`</span> -- <span id="1312">Operations — `var b = 1 + 2 + 3`</span> -- <span id="9880">True or false statements — `var c = true`</span> -- <span id="335a">Constant numbers — `const PI = 3.14`</span> -- <span id="7221">Objects — `var name = {firstName:"John", lastName:"Doe"}`</span> - -There are more possibilities. Note that variables are case sensitive. That means `lastname` and `lastName` will be handled as two different variables. - -### Objects - -Objects are certain kinds of variables. They are variables that can have their own values and methods. The latter are actions that you can perform on objects. - -var person = { - -firstName:"John", - -lastName:"Doe", - -age:20, - -nationality:"German" - -}; - -### The Next Level: Arrays - -Next up in our JavaScript cheat sheet are arrays. Arrays are part of many different programming languages. They are a way of organizing variables and properties into groups. Here's how to create one in JavaScript: - -var fruit = \["Banana", "Apple", "Pear"\]; - -Now you have an array called `fruit` which contains three items that you can use for future operations. - -### Array Methods - -Once you have created arrays, there are a few things you can do with them: - -- <span id="4e4b">`concat()` — Join several arrays into one</span> -- <span id="5c02">`indexOf()` — Returns the first position at which a given element appears in an array</span> -- <span id="45cd">`join()` — Combine elements of an array into a single string and return the string</span> -- <span id="3a4e">`lastIndexOf()` — Gives the last position at which a given element appears in an array</span> -- <span id="8fbb">`pop()` — Removes the last element of an array</span> -- <span id="28e4">`push()` — Add a new element at the end</span> -- <span id="0be2">`reverse()` — Sort elements in a descending order</span> -- <span id="775e">`shift()` — Remove the first element of an array</span> -- <span id="1063">`slice()` — Pulls a copy of a portion of an array into a new array</span> -- <span id="53fd">`sort()` — Sorts elements alphabetically</span> -- <span id="f551">`splice()` — Adds elements in a specified way and position</span> -- <span id="c46b">`toString()` — Converts elements to strings</span> -- <span id="ef66">`unshift()` —Adds a new element to the beginning</span> -- <span id="4598">`valueOf()` — Returns the primitive value of the specified object</span> - -### Operators - -If you have variables, you can use them to perform different kinds of operations. To do so, you need operators. - -### Basic Operators - -- <span id="5d34">`+` — Addition</span> -- <span id="5fd9">`-` — Subtraction</span> -- <span id="3b13">`*` — Multiplication</span> -- <span id="521a">`/` — Division</span> -- <span id="cf0f">`(...)` — Grouping operator, operations within brackets are executed earlier than those outside</span> -- <span id="bb2a">`%` — Modulus (remainder )</span> -- <span id="e837">`++` — Increment numbers</span> -- <span id="71ea">`--` — Decrement numbers</span> - -### Comparison Operators - -- <span id="a2b0">`==` — Equal to</span> -- <span id="5105">`===` — Equal value and equal type</span> -- <span id="c79c">`!=` — Not equal</span> -- <span id="1f7f">`!==` — Not equal value or not equal type</span> -- <span id="78c3">`>` — Greater than</span> -- <span id="d40b">`<` — Less than</span> -- <span id="081b">`>=` — Greater than or equal to</span> -- <span id="d065">`<=` — Less than or equal to</span> -- <span id="174d">`?` — Ternary operator</span> - -### Logical Operators - -- <span id="cb7b">`&&` — Logical and</span> -- <span id="b1ee">`||` — Logical or</span> -- <span id="96d4">`!` — Logical not</span> - -### Bitwise Operators - -- <span id="8cf7">`&` — AND statement</span> -- <span id="02d5">`|` — OR statement</span> -- <span id="e576">`~` — NOT</span> -- <span id="9c66">`^` — XOR</span> -- <span id="b343">`<<` — Left shift</span> -- <span id="52b1">`>>` — Right shift</span> -- <span id="1b5c">`>>>` — Zero fill right shift</span> - -### Functions - -JavaScript functions are blocks of code that perform a certain task. A basic function looks like this: - -function name(parameter1, parameter2, parameter3) { - -// what the function does - -} - -As you can see, it consists of the `function` keyword plus a name. The function's parameters are in the brackets and you have curly brackets around what the function performs. You can create your own, but to make your life easier - there are also a number of default functions. - -### Outputting Data - -A common application for functions is the output of data. For the output, you have the following options: - -- <span id="a7a7">`alert()` — Output data in an alert box in the browser window</span> -- <span id="0c44">`confirm()` — Opens up a yes/no dialog and returns true/false depending on user click</span> -- <span id="9690">`console.log()` — Writes information to the browser console, good for debugging purposes</span> -- <span id="0d4d">`document.write()` — Write directly to the HTML document</span> -- <span id="16aa">`prompt()` — Creates a dialogue for user input</span> - -### Global Functions - -Global functions are functions built into every browser capable of running JavaScript. - -- <span id="f4f1">`decodeURI()` — Decodes a <a href="https://en.wikipedia.org/wiki/Uniform_Resource_Identifier" class="markup--anchor markup--li-anchor">Uniform Resource Identifier (URI)</a> created by `encodeURI` or similar</span> -- <span id="c203">`decodeURIComponent()` — Decodes a URI component</span> -- <span id="176a">`encodeURI()` — Encodes a URI into UTF-8</span> -- <span id="6720">`encodeURIComponent()` — Same but for URI components</span> -- <span id="e97b">`eval()` — Evaluates JavaScript code represented as a string</span> -- <span id="390b">`isFinite()` — Determines whether a passed value is a finite number</span> -- <span id="5d46">`isNaN()` — Determines whether a value is NaN or not</span> -- <span id="f668">`Number()` —- Returns a number converted from its argument</span> -- <span id="a5ff">`parseFloat()` — Parses an argument and returns a floating-point number</span> -- <span id="a666">`parseInt()` — Parses its argument and returns an integer</span> - -### JavaScript Loops - -Loops are part of most programming languages. They allow you to execute blocks of code desired number of times with different values: - -for (before loop; condition **for** loop; execute after loop) { - -// what to do during the loop - -} - -You have several parameters to create loops: - -- <span id="ff62">`for` — The most common way to create a loop in JavaScript</span> -- <span id="7ad1">`while` — Sets up conditions under which a loop executes</span> -- <span id="c2f4">`do while` — Similar to the `while` loop but it executes at least once and performs a check at the end to see if the condition is met to execute again</span> -- <span id="7157">`break` —Used to stop and exit the cycle at certain conditions</span> -- <span id="f5c0">`continue` — Skip parts of the cycle if certain conditions are met</span> - -### If — Else Statements - -These types of statements are easy to understand. Using them, you can set conditions for when your code is executed. If certain conditions apply, something is done, if not — something else is executed. - -if (condition) { - -// what to do if condition is met - -} **else** { - -// what to do if condition is not met - -} - -A similar concept to `if else` is the `switch` statement. However, using the switch you select one of several code blocks to execute. - -### Strings - -Strings are what JavaScript calls to text that does not perform a function but can appear on the screen. - -var person = "John Doe"; - -In this case, `John Doe` is the string. - -### Escape Characters - -In JavaScript, strings are marked with single or double-quotes. If you want to use quotation marks in a string, you need to use special characters: - -- <span id="b4b1">`\'` — Single quote</span> -- <span id="3b22">`\"` — Double quote</span> - -Aside from that you also have additional escape characters: - -- <span id="b412">`\\` — Backslash</span> -- <span id="1592">`\b` — Backspace</span> -- <span id="3a72">`\f` — Form feed</span> -- <span id="145a">`\n` — New line</span> -- <span id="1416">`\r` — Carriage return</span> -- <span id="95d4">`\t` — Horizontal tabulator</span> -- <span id="d962">`\v` — Vertical tabulator</span> - -### String Methods - -There are many different ways to work with strings: - -- <span id="2021">`charAt()` — Returns a character at a specified position inside a string</span> -- <span id="d3e5">`charCodeAt()` — Gives you the Unicode of a character at that position</span> -- <span id="fdd1">`concat()` — Concatenates (joins) two or more strings into one</span> -- <span id="009c">`fromCharCode()` — Returns a string created from the specified sequence of UTF-16 code units</span> -- <span id="7ed3">`indexOf()` — Provides the position of the first occurrence of a specified text within a string</span> -- <span id="2937">`lastIndexOf()` — Same as `indexOf()` but with the last occurrence, searching backward</span> -- <span id="142d">`match()` — Retrieves the matches of a string against a search pattern</span> -- <span id="6c18">`replace()` — Find and replace specified text in a string</span> -- <span id="e279">`search()` — Executes a search for a matching text and returns its position</span> -- <span id="6bcd">`slice()` — Extracts a section of a string and returns it as a new string</span> -- <span id="e4ee">`split()` — Splits a string object into an array of strings at a specified position</span> -- <span id="3a27">`substr()` — Similar to `slice()` but extracts a substring depending on a specified number of characters</span> -- <span id="3d14">`substring()` — Also similar to `slice()` but can't accept negative indices</span> -- <span id="fa33">`toLowerCase()` — Convert strings to lower case</span> -- <span id="3485">`toUpperCase()` — Convert strings to upper case</span> -- <span id="4f96">`valueOf()` — Returns the primitive value (that has no properties or methods) of a string object</span> - -### Regular Expression Syntax - -Regular expressions are search patterns used to match character combinations in strings. The search pattern can be used for text search and text to replace operations. - -### Pattern Modifiers - -- <span id="bb29">`e` — Evaluate replacement</span> -- <span id="b6b8">`i` — Perform case-insensitive matching</span> -- <span id="4f50">`g` — Perform global matching</span> -- <span id="4add">`m` — Perform multiple line matching</span> -- <span id="a073">`s` — Treat strings as a single line</span> -- <span id="482b">`x` — Allow comments and whitespace in the pattern</span> -- <span id="f6ad">`U` — Ungreedy pattern</span> - -### Brackets - -- <span id="aae1">`[abc]` — Find any of the characters between the brackets</span> -- <span id="e048">`[^abc]` — Find any character which is not in the brackets</span> -- <span id="f9b5">`[0-9]` — Used to find any digit from 0 to 9</span> -- <span id="ac71">`[A-z]` — Find any character from uppercase A to lowercase z</span> -- <span id="6fce">`(a|b|c)` — Find any of the alternatives separated with `|`</span> - -### Metacharacters - -- <span id="dcd6">`.` — Find a single character, except newline or line terminator</span> -- <span id="e944">`\w` — Word character</span> -- <span id="c4bf">`\W` — Non-word character</span> -- <span id="7b81">`\d` — A digit</span> -- <span id="a533">`\D` — A non-digit character</span> -- <span id="1fcc">`\s` — Whitespace character</span> -- <span id="374c">`\S` — Non-whitespace character</span> -- <span id="72d0">`\b` — Find a match at the beginning/end of a word</span> -- <span id="2d38">`\B` — A match not at the beginning/end of a word</span> -- <span id="859b">`\0` — NUL character</span> -- <span id="df4d">`\n` — A new line character</span> -- <span id="5acd">`\f` — Form feed character</span> -- <span id="833f">`\r` — Carriage return character</span> -- <span id="4f31">`\t` — Tab character</span> -- <span id="e618">`\v` — Vertical tab character</span> -- <span id="dcfc">`\xxx` — The character specified by an octal number xxx</span> -- <span id="cf5e">`\xdd` — Character specified by a hexadecimal number dd</span> -- <span id="978f">`\uxxxx` — The Unicode character specified by a hexadecimal number XXXX</span> - -### Quantifiers - -- <span id="e4cf">`n+` — Matches any string that contains at least one n</span> -- <span id="be07">`n*` — Any string that contains zero or more occurrences of n</span> -- <span id="4a93">`n?` — A string that contains zero or one occurrence of n</span> -- <span id="91f0">`n{X}` — String that contains a sequence of X n's</span> -- <span id="097b">`n{X,Y}` — Strings that contain a sequence of X to Y n's</span> -- <span id="e9f2">`n{X,}` — Matches any string that contains a sequence of at least X n's</span> -- <span id="15b3">`n$` — Any string with n at the end of it</span> -- <span id="5fc9">`^n` — String with n at the beginning of it</span> -- <span id="2b42">`?=n` — Any string that is followed by a specific string n</span> -- <span id="6ffa">`?!n` — String that is not followed by a specific string ni</span> - -### Numbers and Math - -In JavaScript, you can also work with numbers, constants and perform mathematical functions. - -### Number Properties - -- <span id="3554">`MAX_VALUE` — The maximum numeric value representable in JavaScript</span> -- <span id="c55d">`MIN_VALUE` — Smallest positive numeric value representable in JavaScript</span> -- <span id="49e0">`NaN` — The "Not-a-Number" value</span> -- <span id="3024">`NEGATIVE_INFINITY` — The negative Infinity value</span> -- <span id="0bf4">`POSITIVE_INFINITY` — Positive Infinity value</span> - -### Number Methods - -- <span id="9478">`toExponential()` — Returns the string with a rounded number written as exponential notation</span> -- <span id="2ad0">`toFixed()` — Returns the string of a number with a specified number of decimals</span> -- <span id="d464">`toPrecision()` — String of a number written with a specified length</span> -- <span id="2244">`toString()` — Returns a number as a string</span> -- <span id="bc1e">`valueOf()` — Returns a number as a number</span> - -### Math Properties - -- <span id="9f68">`E` — Euler's number</span> -- <span id="a4df">`LN2` — The natural logarithm of 2</span> -- <span id="0f06">`LN10` — Natural logarithm of 10</span> -- <span id="1a92">`LOG2E` — Base 2 logarithm of E</span> -- <span id="42e7">`LOG10E` — Base 10 logarithm of E</span> -- <span id="1fbe">`PI` — The number PI</span> -- <span id="2a56">`SQRT1_2` — Square root of 1/2</span> -- <span id="aab4">`SQRT2` — The square root of 2</span> - -### Math Methods - -- <span id="8836">`abs(x)` — Returns the absolute (positive) value of x</span> -- <span id="ddb9">`acos(x)` — The arccosine of x, in radians</span> -- <span id="a0c3">`asin(x)` — Arcsine of x, in radians</span> -- <span id="c2ca">`atan(x)` — The arctangent of x as a numeric value</span> -- <span id="8b93">`atan2(y,x)` — Arctangent of the quotient of its arguments</span> -- <span id="b103">`ceil(x)` — Value of x rounded up to its nearest integer</span> -- <span id="c68a">`cos(x)` — The cosine of x (x is in radians)</span> -- <span id="d480">`exp(x)` — Value of Ex</span> -- <span id="2954">`floor(x)` — The value of x rounded down to its nearest integer</span> -- <span id="ff4d">`log(x)` — The natural logarithm (base E) of x</span> -- <span id="b6a9">`max(x,y,z,...,n)` — Returns the number with the highest value</span> -- <span id="dfb0">`min(x,y,z,...,n)` — Same for the number with the lowest value</span> -- <span id="a6f1">`pow(x,y)` — X to the power of y</span> -- <span id="8851">`random()` — Returns a random number between 0 and 1</span> -- <span id="d32e">`round(x)` — The value of x rounded to its nearest integer</span> -- <span id="fe9a">`sin(x)` — The sine of x (x is in radians)</span> -- <span id="c244">`sqrt(x)` — Square root of x</span> -- <span id="b5ef">`tan(x)` — The tangent of an angle</span> - -### Dealing with Dates in JavaScript - -You can also work with and modify dates and time with JavaScript. This is the next chapter in the JavaScript cheat sheet. - -### Setting Dates - -- <span id="b187">`Date()` — Creates a new date object with the current date and time</span> -- <span id="42f8">`Date(2017, 5, 21, 3, 23, 10, 0)` — Create a custom date object. The numbers represent a year, month, day, hour, minutes, seconds, milliseconds. You can omit anything you want except for a year and month.</span> -- <span id="4e80">`Date("2017-06-23")` — Date declaration as a string</span> - -### Pulling Date and Time Values - -- <span id="465e">`getDate()` — Get the day of the month as a number (1-31)</span> -- <span id="1b08">`getDay()` — The weekday as a number (0-6)</span> -- <span id="6d9e">`getFullYear()` — Year as a four-digit number (yyyy)</span> -- <span id="a216">`getHours()` — Get the hour (0-23)</span> -- <span id="388a">`getMilliseconds()` — The millisecond (0-999)</span> -- <span id="a97f">`getMinutes()` — Get the minute (0-59)</span> -- <span id="2427">`getMonth()` — Month as a number (0-11)</span> -- <span id="b964">`getSeconds()` — Get the second (0-59)</span> -- <span id="505d">`getTime()` — Get the milliseconds since January 1, 1970</span> -- <span id="7c14">`getUTCDate()` — The day (date) of the month in the specified date according to universal time (also available for day, month, full year, hours, minutes etc.)</span> -- <span id="d6b6">`parse` — Parses a string representation of a date and returns the number of milliseconds since January 1, 1970</span> - -### Set Part of a Date - -- <span id="9a97">`setDate()` — Set the day as a number (1-31)</span> -- <span id="d4f0">`setFullYear()` — Sets the year (optionally month and day)</span> -- <span id="1a45">`setHours()` — Set the hour (0-23)</span> -- <span id="8020">`setMilliseconds()` — Set milliseconds (0-999)</span> -- <span id="7feb">`setMinutes()` — Sets the minutes (0-59)</span> -- <span id="d7ca">`setMonth()` — Set the month (0-11)</span> -- <span id="795d">`setSeconds()` — Sets the seconds (0-59)</span> -- <span id="1d7f">`setTime()` — Set the time (milliseconds since January 1, 1970)</span> -- <span id="78e1">`setUTCDate()` — Sets the day of the month for a specified date according to universal time (also available for day, month, full year, hours, minutes etc.)</span> - -### DOM Mode - -The DOM is the <a href="https://en.wikipedia.org/wiki/Document_Object_Model" class="markup--anchor markup--p-anchor">Document Object Model</a> of a page. It is the code of the structure of a webpage. JavaScript comes with a lot of different ways to create and manipulate HTML elements (called nodes). - -### Node Properties - -- <span id="cfb7">`attributes` — Returns a live collection of all attributes registered to an element</span> -- <span id="6138">`baseURI` — Provides the absolute base URL of an HTML element</span> -- <span id="34da">`childNodes` — Gives a collection of an element's child nodes</span> -- <span id="58ec">`firstChild` — Returns the first child node of an element</span> -- <span id="2f34">`lastChild` — The last child node of an element</span> -- <span id="fdea">`nextSibling` — Gives you the next node at the same node tree level</span> -- <span id="1ca4">`nodeName` —Returns the name of a node</span> -- <span id="d4ee">`nodeType` — Returns the type of a node</span> -- <span id="cd22">`nodeValue` — Sets or returns the value of a node</span> -- <span id="a9a3">`ownerDocument` — The top-level document object for this node</span> -- <span id="51b4">`parentNode` — Returns the parent node of an element</span> -- <span id="31ef">`previousSibling` — Returns the node immediately preceding the current one</span> -- <span id="ec40">`textContent` — Sets or returns the textual content of a node and its descendants</span> - -### Node Methods - -- <span id="7f05">`appendChild()` — Adds a new child node to an element as the last child node</span> -- <span id="3b3a">`cloneNode()` — Clones an HTML element</span> -- <span id="661c">`compareDocumentPosition()` — Compares the document position of two elements</span> -- <span id="86d2">`getFeature()` — Returns an object which implements the APIs of a specified feature</span> -- <span id="059c">`hasAttributes()` — Returns true if an element has any attributes, otherwise false</span> -- <span id="5d0d">`hasChildNodes()` — Returns true if an element has any child nodes, otherwise false</span> -- <span id="4c86">`insertBefore()` — Inserts a new child node before a specified, existing child node</span> -- <span id="4b38">`isDefaultNamespace()` — Returns true if a specified namespaceURI is the default, otherwise false</span> -- <span id="8c4e">`isEqualNode()` — Checks if two elements are equal</span> -- <span id="2f6a">`isSameNode()` — Checks if two elements are the same node</span> -- <span id="944e">`isSupported()` — Returns true if a specified feature is supported on the element</span> -- <span id="b7ef">`lookupNamespaceURI()` — Returns the namespace URI associated with a given node</span> -- <span id="5f59">`lookupPrefix()` — Returns a DOMString containing the prefix for a given namespace URI if present</span> -- <span id="6670">`normalize()` — Joins adjacent text nodes and removes empty text nodes in an element</span> -- <span id="c80a">`removeChild()` — Removes a child node from an element</span> -- <span id="8108">`replaceChild()` — Replaces a child node in an element</span> - -### Element Methods - -- <span id="9530">`getAttribute()` — Returns the specified attribute value of an element node</span> -- <span id="0dd1">`getAttributeNS()` — Returns string value of the attribute with the specified namespace and name</span> -- <span id="8a0d">`getAttributeNode()` — Gets the specified attribute node</span> -- <span id="fc41">`getAttributeNodeNS()` — Returns the attribute node for the attribute with the given namespace and name</span> -- <span id="2a3e">`getElementsByTagName()` — Provides a collection of all child elements with the specified tag name</span> -- <span id="11a4">`getElementsByTagNameNS()` — Returns a live HTMLCollection of elements with a certain tag name belonging to the given namespace</span> -- <span id="e2ae">`hasAttribute()` — Returns true if an element has any attributes, otherwise false</span> -- <span id="17dd">`hasAttributeNS()` — Provides a true/false value indicating whether the current element in a given namespace has the specified attribute</span> -- <span id="f28c">`removeAttribute()` — Removes a specified attribute from an element</span> -- <span id="8cd0">`removeAttributeNS()` — Removes the specified attribute from an element within a certain namespace</span> -- <span id="e6c3">`removeAttributeNode()` — Takes away a specified attribute node and returns the removed node</span> -- <span id="a7b9">`setAttribute()` — Sets or changes the specified attribute to a specified value</span> -- <span id="bf42">`setAttributeNS()` — Adds a new attribute or changes the value of an attribute with the given namespace and name</span> -- <span id="2322">`setAttributeNode()` — Sets or changes the specified attribute node</span> -- <span id="0540">`setAttributeNodeNS()` — Adds a new namespaced attribute node to an element</span> - -### Working with the User Browser - -Besides HTML elements, JavaScript is also able to take into account the user browser and incorporate its properties into the code. - -### Window Properties - -- <span id="1b1f">`closed` — Checks whether a window has been closed or not and returns true or false</span> -- <span id="805f">`defaultStatus` — Sets or returns the default text in the status bar of a window</span> -- <span id="458e">`document` — Returns the document object for the window</span> -- <span id="93ee">`frames` — Returns all `<iframe>` elements in the current window</span> -- <span id="c42a">`history` — Provides the History object for the window</span> -- <span id="3a5d">`innerHeight` — The inner height of a window's content area</span> -- <span id="c609">`innerWidth` — The inner width of the content area</span> -- <span id="5167">`length` — Find out the number of `<iframe>` elements in the window</span> -- <span id="4f05">`location` — Returns the location object for the window</span> -- <span id="4125">`name` — Sets or returns the name of a window</span> -- <span id="3d7f">`navigator` — Returns the Navigator object for the window</span> -- <span id="c601">`opener` — Returns a reference to the window that created the window</span> -- <span id="734e">`outerHeight` — The outer height of a window, including toolbars/scrollbars</span> -- <span id="9b0a">`outerWidth` — The outer width of a window, including toolbars/scrollbars</span> -- <span id="3140">`pageXOffset` — Number of pixels the current document has been scrolled horizontally</span> -- <span id="0bcc">`pageYOffset` — Number of pixels the document has been scrolled vertically</span> -- <span id="a2af">`parent` — The parent window of the current window</span> -- <span id="3634">`screen` — Returns the Screen object for the window</span> -- <span id="9566">`screenLeft` — The horizontal coordinate of the window (relative to the screen)</span> -- <span id="1245">`screenTop` — The vertical coordinate of the window</span> -- <span id="5656">`screenX` — Same as `screenLeft` but needed for some browsers</span> -- <span id="21e7">`screenY` — Same as `screenTop` but needed for some browsers</span> -- <span id="d000">`self` — Returns the current window</span> -- <span id="99af">`status` — Sets or returns the text in the status bar of a window</span> -- <span id="0a0f">`top` — Returns the topmost browser window</span> - -### Window Methods - -- <span id="5715">`alert()` — Displays an alert box with a message and an OK button</span> -- <span id="4afc">`blur()` — Removes focus from the current window</span> -- <span id="ef9a">`clearInterval()` — Clears a timer set with `setInterval()`</span> -- <span id="fa72">`clearTimeout()` — Clears a timer set with `setTimeout()`</span> -- <span id="7bce">`close()` — Closes the current window</span> -- <span id="ccbf">`confirm()` — Displays a dialogue box with a message and an _OK_ and _Cancel_ button</span> -- <span id="e6f2">`focus()` — Sets focus to the current window</span> -- <span id="5eb7">`moveBy()` — Moves a window relative to its current position</span> -- <span id="16b6">`moveTo()` — Moves a window to a specified position</span> -- <span id="32d8">`open()` — Opens a new browser window</span> -- <span id="4198">`print()` — Prints the content of the current window</span> -- <span id="3bec">`prompt()` — Displays a dialogue box that prompts the visitor for input</span> -- <span id="e16a">`resizeBy()` — Resizes the window by the specified number of pixels</span> -- <span id="31c8">`resizeTo()` — Resizes the window to a specified width and height</span> -- <span id="6c44">`scrollBy()` — Scrolls the document by a specified number of pixels</span> -- <span id="959f">`scrollTo()` — Scrolls the document to specified coordinates</span> -- <span id="704a">`setInterval()` — Calls a function or evaluates an expression at specified intervals</span> -- <span id="87c3">`setTimeout()` — Calls a function or evaluates an expression after a specified interval</span> -- <span id="1cde">`stop()` — Stops the window from loading</span> - -### Screen Properties - -- <span id="7e50">`availHeight` — Returns the height of the screen (excluding the Windows Taskbar)</span> -- <span id="d7ea">`availWidth` — Returns the width of the screen (excluding the Windows Taskbar)</span> -- <span id="4feb">`colorDepth` — Returns the bit depth of the color palette for displaying images</span> -- <span id="f2f7">`height` — The total height of the screen</span> -- <span id="8e22">`pixelDepth` — The color resolution of the screen in bits per pixel</span> -- <span id="bc5a">`width` — The total width of the screen</span> - -### JavaScript Events - -Events are things that can happen to HTML elements and are performed by the user. The programming language can listen for these events and trigger actions in the code. No JavaScript cheat sheet would be complete without them. - -### Mouse - -- <span id="9546">`onclick` — The event occurs when the user clicks on an element</span> -- <span id="9b50">`oncontextmenu` — User right-clicks on an element to open a context menu</span> -- <span id="147a">`ondblclick` — The user double-clicks on an element</span> -- <span id="3720">`onmousedown` — User presses a mouse button over an element</span> -- <span id="a40a">`onmouseenter` — The pointer moves onto an element</span> -- <span id="345e">`onmouseleave` — Pointer moves out of an element</span> -- <span id="79b1">`onmousemove` — The pointer is moving while it is over an element</span> -- <span id="fa70">`onmouseover` — When the pointer is moved onto an element or one of its children</span> -- <span id="94f8">`onmouseout` — User moves the mouse pointer out of an element or one of its children</span> -- <span id="486e">`onmouseup` — The user releases a mouse button while over an element</span> - -### Keyboard - -- <span id="6a8f">`onkeydown` — When the user is pressing a key down</span> -- <span id="0647">`onkeypress` — The moment the user starts pressing a key</span> -- <span id="ff0f">`onkeyup` — The user releases a key</span> - -### Frame - -- <span id="9d29">`onabort` — The loading of a media is aborted</span> -- <span id="baa4">`onbeforeunload` — Event occurs before the document is about to be unloaded</span> -- <span id="740e">`onerror` — An error occurs while loading an external file</span> -- <span id="be95">`onhashchange` — There have been changes to the anchor part of a URL</span> -- <span id="d0fd">`onload` — When an object has loaded</span> -- <span id="65e5">`onpagehide` — The user navigates away from a webpage</span> -- <span id="aae6">`onpageshow` — When the user navigates to a webpage</span> -- <span id="e3dc">`onresize` — The document view is resized</span> -- <span id="96c8">`onscroll` — An element's scrollbar is being scrolled</span> -- <span id="f2fa">`onunload` — Event occurs when a page has unloaded</span> - -### Form - -- <span id="731a">`onblur` — When an element loses focus</span> -- <span id="facf">`onchange` — The content of a form element changes (for `<input>`, `<select>` and `<textarea>`)</span> -- <span id="7a0a">`onfocus` — An element gets focus</span> -- <span id="5188">`onfocusin` — When an element is about to get focus</span> -- <span id="594a">`onfocusout` — The element is about to lose focus</span> -- <span id="700e">`oninput` — User input on an element</span> -- <span id="dd0f">`oninvalid` — An element is invalid</span> -- <span id="6cad">`onreset` — A form is reset</span> -- <span id="f4f2">`onsearch` — The user writes something in a search field (for `<input="search">`)</span> -- <span id="32a9">`onselect` — The user selects some text (for `<input>` and `<textarea>`)</span> -- <span id="3e1d">`onsubmit` — A form is submitted</span> - -### Drag - -- <span id="912c">`ondrag` — An element is dragged</span> -- <span id="6897">`ondragend` — The user has finished dragging the element</span> -- <span id="8225">`ondragenter` — The dragged element enters a drop target</span> -- <span id="cf37">`ondragleave` — A dragged element leaves the drop target</span> -- <span id="5bc3">`ondragover` — The dragged element is on top of the drop target</span> -- <span id="2b0c">`ondragstart` — User starts to drag an element</span> -- <span id="8e24">`ondrop` — Dragged element is dropped on the drop target</span> - -### Clipboard - -- <span id="c299">`oncopy` — User copies the content of an element</span> -- <span id="267c">`oncut` — The user cuts an element's content</span> -- <span id="e33c">`onpaste` — A user pastes the content in an element</span> - -### Media - -- <span id="e0ab">`onabort` — Media loading is aborted</span> -- <span id="0758">`oncanplay` — The browser can start playing media (e.g. a file has buffered enough)</span> -- <span id="0bc2">`oncanplaythrough` — The browser can play through media without stopping</span> -- <span id="4c27">`ondurationchange` — The duration of the media changes</span> -- <span id="aa9a">`onended` — The media has reached its end</span> -- <span id="25b8">`onerror` — Happens when an error occurs while loading an external file</span> -- <span id="cdf4">`onloadeddata` — Media data is loaded</span> -- <span id="edce">`onloadedmetadata` — Metadata (like dimensions and duration) are loaded</span> -- <span id="7928">`onloadstart` — The browser starts looking for specified media</span> -- <span id="159c">`onpause` — Media is paused either by the user or automatically</span> -- <span id="057f">`onplay` — The media has been started or is no longer paused</span> -- <span id="ce2a">`onplaying` — Media is playing after having been paused or stopped for buffering</span> -- <span id="2655">`onprogress` — The browser is in the process of downloading the media</span> -- <span id="a11c">`onratechange` — The playing speed of the media changes</span> -- <span id="f8bb">`onseeked` — User is finished moving/skipping to a new position in the media</span> -- <span id="9895">`onseeking` — The user starts moving/skipping</span> -- <span id="c636">`onstalled` — The browser is trying to load the media but it is not available</span> -- <span id="6480">`onsuspend` — The browser is intentionally not loading media</span> -- <span id="f94b">`ontimeupdate` — The playing position has changed (e.g. because of fast forward)</span> -- <span id="e96b">`onvolumechange` — Media volume has changed (including mute)</span> -- <span id="9fe8">`onwaiting` — Media paused but expected to resume (for example, buffering)</span> - -### Animation - -- <span id="4497">`animationend` — A CSS animation is complete</span> -- <span id="fc16">`animationiteration` — CSS animation is repeated</span> -- <span id="0f40">`animationstart` — CSS animation has started</span> - -### Other - -- <span id="614b">`transitionend` — Fired when a CSS transition has completed</span> -- <span id="5a40">`onmessage` — A message is received through the event source</span> -- <span id="0dad">`onoffline` — The browser starts to work offline</span> -- <span id="058e">`ononline` — The browser starts to work online</span> -- <span id="090a">`onpopstate` — When the window's history changes</span> -- <span id="d940">`onshow` — A `<menu>` element is shown as a context menu</span> -- <span id="3062">`onstorage` — A Web Storage area is updated</span> -- <span id="2681">`ontoggle` — The user opens or closes the `<details>` element</span> -- <span id="6a40">`onwheel` — Mouse wheel rolls up or down over an element</span> -- <span id="7178">`ontouchcancel` — Screen-touch is interrupted</span> -- <span id="bec5">`ontouchend` — User's finger is removed from a touch-screen</span> -- <span id="3b60">`ontouchmove` — A finger is dragged across the screen</span> -- <span id="3c0e">`ontouchstart` — A finger is placed on the touch-screen</span> - -### Errors - -When working with JavaScript, different errors can occur. There are several ways of handling them: - -- <span id="54c9">`try` — Lets you define a block of code to test for errors</span> -- <span id="cb14">`catch` — Set up a block of code to execute in case of an error</span> -- <span id="6a5b">`throw` — Create custom error messages instead of the standard JavaScript errors</span> -- <span id="6aea">`finally` — Lets you execute code, after try and catch, regardless of the result</span> - -### Error Name Values - -JavaScript also has a built-in error object. It has two properties: - -- <span id="ca3b">`name` — Sets or returns the error name</span> -- <span id="7047">`message` — Sets or returns an error message in a string from</span> - -The error property can return six different values as its name: - -- <span id="b389">`EvalError` — An error has occurred in the `eval()` function</span> -- <span id="570c">`RangeError` — A number is "out of range"</span> -- <span id="2352">`ReferenceError` — An illegal reference has occurred</span> -- <span id="5019">`SyntaxError` — A syntax error has occurred</span> -- <span id="0527">`TypeError` — A type error has occurred</span> -- <span id="02a3">`URIError` — An `encodeURI()` error has occurred</span> - -### Explicit Conversions - -The simplest way to perform an explicit type conversion is to use the `Boolean(), Number()`, and `String()` functions. - -Any value other than `null `or `undefined `has a` toString()` method. - -`n.toString(2);` - -binary - -`n.toString(8);` - -octal - -`n.toString(16);` - -hex - -`let n = 123456.789;` - -`n.toFixed(0)` - -"123457" - -`n.toFixed(5)` - -"123456.78900" - -`n.toExponential(3)` - -"1.235e+5" - -`n.toPrecision(7)` - -"123456.8" - -`n.toPrecision(10)` - -"123456.7890" - -`parseInt("3 blind mice")` - -3 - -`parseFloat(" 3.14 meters")` - -3.14 - -`parseInt("-12.34")` - --12 - -`parseInt("0xFF")` - -255 - -### Types, Values, and Variables - -### Links - -**Resource** - -**URL** - -MDN - -<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript" class="markup--anchor markup--p-anchor">https://developer.mozilla.org/en-US/docs/Web/JavaScript</a> - -Run Snippets - -<a href="https://developers.google.com/web/tools/chrome-devtools/javascript/snippets" class="markup--anchor markup--p-anchor">https://developers.google.com/web/tools/chrome-devtools/javascript/snippets</a> - -### Explicit Conversions - -The simplest way to perform an explicit type conversion is to use the `Boolean(), Number()`, and `String()` functions. - -Any value other than `null `or `undefined `has a` toString()` method. - -`n.toString(2);` - -binary - -`n.toString(8);` - -octal - -`n.toString(16);` - -hex - -`let n = 123456.789;` - -`n.toFixed(0)` - -"123457" - -`n.toFixed(5)` - -"123456.78900" - -`n.toExponential(3)` - -"1.235e+5" - -`n.toPrecision(7)` - -"123456.8" - -`n.toPrecision(10)` - -"123456.7890" - -`parseInt("3 blind mice")` - -3 - -`parseFloat(" 3.14 meters")` - -3.14 - -`parseInt("-12.34")` - --12 - -`parseInt("0xFF")` - -255 - -`parseInt("0xff")` - -255 - -`parseInt("-0XFF")` - --255 - -`parseInt("0.1")` - -0 - -`parseInt(".1")` - -NaN: integers can't start with "." - -`parseFloat("$72.47")` - -NaN: numbers can't start with "$" - -Supply Radix - -`parseInt("11", 2)` - -3 - -`parseInt("ff", 16)` - -255 - -`parseInt("077", 8)` - -63 - -### Conversion Idioms - -`x + ""` - -`String(x)` - -`+x` - -`Number(x)` - -`x-0` - -`Number(x)` - -`!!x` - -`Boolean(x)` - -### Destructuring Assignment - -`let [x,y] = [1,2];` - -let x=1, y=2 - -`[x,y] = [x + 1,y + 1];` - -x = x + 1, y = y + 1 - -`[x,y] = [y,x];` - -Swap the value of the two variables - -Destructuring assignment makes it easy to work with functions that return arrays of values: - -`let [r,theta] = toPolar(1.0, 1.0);` - - function toPolar(x, y) { - - return [Math.sqrt(x*x+y*y), Math.atan2(y,x)]; - - } - -Variable destructuring in loops: - -`let o = { x: 1, y: 2 };` - - for(const [name, value] of Object.entries(o)) { - - console.log(name, value); // Prints "x 1" and "y 2" - - } - -**Note**: The `Object.entries()` method returns an array of a given object's own enumerable string-keyed property `[key, value]` pairs, in the same order as that provided by a `for...in` loop. (The only important difference is that a `for...in` loop enumerates properties in the prototype chain as well). - -The list of variables on the left can include extra commas to skip certain values on the right - -`[,x,,y] = [1,2,3,4];` - -x == 2; y == 4 - -**Note**: the last comma does not stand for a value. - -To collect all unused or remaining values into a single variable when destructuring an array, use three dots `(...) `before the last variable name on the left-hand side - -`let [x, ...y] = [1,2,3,4];` - -y == \[2,3,4\] - -`let [first, ...rest] = "Hello";` - -first == "H"; rest ==\["e","l","l","o"\] - -Destructuring assignment can also be performed when the righthand side is an object value. - -`let transparent = {r: 0.0, g: 0.0, b: 0.0, a: 1.0};` - -`let {r, g, b} = transparent;` - -r == 0.0; g == 0.0; b == 0.0 - -`const {sin, cos, tan} = Math;` - -sin=Math.sin, cos=Math.cos, tan=Math.tan - -### Expressions and Operators - -In JavaScript, the values `null `and `undefined `are the only two values that do not have properties. In a regular property access expression using . or \[\], you get a `TypeError` if the expression on the left evaluates to `null `or `undefined`. You can use `?.` and `?.[]` syntax to guard against errors of this type. - -You can also invoke a function using `?.()` instead of `()`. - -With the `new ?.()` invocation syntax, if the expression to the left of the `?.` evaluates to `null` or `undefined`, then the entire invocation expression evaluates to `undefined `and no exception is thrown. - -Write the function invocation using `?.(),` knowing that invocation will only happen if there is actually a value to be invoked - - function square(x, log) { - - log?.(x); // Call the function if there is one - - return x * x; - - } - -Note that expression `x++` is not always the same as `x = x + 1`.The `++` operator never performs string concatenation: it always converts its operand to a number and increments it. If x is the string "1", `++x` is the number 2, but` x + 1` is the string "11". - -JavaScript objects are compared by reference, not by value. An object is equal to itself, but not to any other object. If two distinct objects have the same number of properties, with the same names and values, they are still not equal. Similarly, two arrays that have the same elements in the same order are not equal to each other. - -`NaN `value is never equal to any other value, including itself! To check whether a value `x` is `NaN`, use `x !== `, or the global `isNaN()` function. - -If both values refer to the same object, array, or function, they are equal. If they refer to different objects, they are not equal, even if both objects have identical properties. - -### Evaluating Expressions - -JavaScript has the ability to interpret strings of JavaScript source code, evaluating them to produce a value. - -`eval("3+2")` - -Because of security issues, some web servers use the HTTP "Content-Security-Policy" header to disable` eval()` for an entire website. - -### First-Defined (??) - -The first-defined operator `??` evaluates to its first defined operand: if its left operand is not `null` and not `undefined`, it returns that value. - -`a ?? b` is equivalent to `(a !== null && a !== undefined) ? a : b` - -`??` is a useful alternative to `||.` The problem with this idiomatic use is that zero, the empty string, and false are all `falsy `values that may be perfectly valid in some circumstances. In this code example, if `maxWidth `is zero, that value will be ignored. But if we change the `||` operator to `??`, we end up with an expression where zero is a valid value. - -`let max = maxWidth || preferences.maxWidth || 500;` - -`let max = maxWidth ?? preferences.maxWidth ?? 500;` - -### delete Operator - -Deleting an array element leaves a "hole" in the array and does not change the array's length. The resulting array is sparse. - -### void Operator - -Using the `void` operator makes sense only if the operand has side effects. - -`let counter = 0;` - -`const increment = () => void counter++;` - -`increment()` - -undefined - -`counter` - -1 - -### Statements - -Expressions are evaluated to produce a value, but statements are executed to make something happen. - -Expressions with side effects, such as assignments and function invocations, can stand alone as statements, and when used this way are known as expression statements. - -A similar category of statements are the declaration statements that declare new variables and define new functions. - -If a function does not have any side effects, there is no sense in calling it, unless it is part of a larger expression or an assignment statement. - -### for/of - -The `for/of` loop works with iterable objects. Arrays, strings, sets, and maps are iterable. - -Array - - let data = [1, 2, 3, 4, 5, 6, 7, 8, 9], sum = 0; - - for(let element of data) { - - sum += element; - - } - - let text = "Na na na na na na na na"; - - let wordSet = new Set(text.split(" ")); - - let unique = []; - - for(let word of wordSet) { - - unique.push(word); - - } - -String - - let frequency = {}; - - for(let letter of "mississippi") { - - if (frequency[letter]) { - - frequency[letter]++; - - } - - else { - - frequency[letter] = 1; - - } - - } - -Map - - let m = new Map([[1, "one"]]); - - for(let [key, value] of m) { - - key // => 1 - - value // => "one" - - } - -Objects are not (by default) iterable. Attempting to use `for/of` on a regular object throws a `TypeError` at runtime. - -If you want to iterate through the properties of an object, you can use the `for/in` loop. - -Note: `for/of` can be used on objects with `Object.entries` property, but it will not pick properties from object's prototype. - -### for/in - -`for/in` loop works with any object after the `in`. - - for(let p in o) { - - console.log(o[p]); - - } - -Note: this will enumerate array indexes, not values. - - for(let i in a) console.log(i); - -The `for/in` loop does not actually enumerate all properties of an object. It does not enumerate properties whose names are symbols. And of the properties whose names are strings, it only loops over the `enumerable`properties. - -### with - -The with statement runs a block of code as if the properties of a specified object were variables in scope for that code. - -The `with `statement is forbidden in strict mode and should be considered deprecated in non-strict mode: avoid using it whenever possible. - - document.forms[0].address.value - - with(document.forms[0]) { - - name.value = ""; - - address.value = ""; - - email.value = ""; - - } - -### debugger - -If a debugger program is available and is running, then an implementation may (but is not required to) perform some kind of debugging action. - -In practice, this statement acts like a breakpoint: execution of JavaScript code stops, and you can use the debugger to print variables' values, examine the call stack, and so on. - -Note that it is not enough to have a debugger available: the debugger statement won't start the debugger for you. If you're using a web browser and have the developer tools console open, however, this statement will cause a breakpoint. - -### use strict - -Strict mode is a restricted subset of the language that fixes important language deficiencies and provides stronger error checking and increased security. - -The differences between strict mode and non-strict mode are the following: - -· The `with `statement is not allowed in strict mode. - -· In strict mode, all variables must be declared: a `ReferenceError `is thrown if you assign a value to an identifier that is not a declared variable, function, function parameter, catch clause parameter, or property of the global object. - -· In non-strict mode, this implicitly declares a global variable by adding a new property to the global object. - -· In strict mode, functions invoked as functions (rather than as methods) have a `this `value of undefined. (In non-strict mode, functions invoked as functions are always passed the global object as their `this `value.) - -· A function is invoked with `call() `or `apply()` , the `this `value is exactly the value passed as the first argument to `call()` or `apply()`. (In non-strict mode, `null `and `undefined `values are replaced with the global object and non-object values are converted to objects.) - -· In strict mode, assignments to non-writable properties and attempts to create new properties on non-extensible objects throw a `TypeError`. (In non-strict mode, these attempts fail silently.) - -· In strict mode, code passed to `eval() `cannot declare variables or define functions in the caller's scope as it can in non-strict mode. Instead, variable and function definitions live in a new scope created for the `eval()`. This scope is discarded when the `eval()` returns. - -· In strict mode, the Arguments object in a function holds a static copy of the values passed to the function. In non-strict mode, the Arguments object has "magical" behavior in which elements of the array and named function parameters both refer to the same value. - -· In strict mode, a `SyntaxError `is thrown if the `delete `operator is followed by an unqualified identifier such as a variable, function, or function parameter. (In non-strict mode, such a `delete `expression does nothing and evaluates to false.) - -· In strict mode, an attempt to delete a non-configurable property throws a `TypeError`. (In non-strict mode, the attempt fails and the delete expression evaluates to false.) - -· In strict mode, it is a syntax error for an object literal to define two or more properties by the same name. (In non-strict mode, no error occurs.) - -### Objects - -In addition to its name and value, each property has three property attributes: - -· The `writable `attribute specifies whether the value of the property can be set. - -· The `enumerable `attribute specifies whether the property name is returned by a `for/in` loop. - -· The `configurable `attribute specifies whether the property can be deleted and whether its attributes can be altered. - -### Prototypes - -All objects created by object literals have the same prototype object, `Object.prototype.` - -Objects created using the `new `keyword and a constructor invocation use the value of the prototype property of the constructor function as their prototype. - -Object created by `new Object()` inherits from `Object.prototype`, just as the object created by `{}` does. Similarly, the object created by `new Array()` uses `Array.prototype` as its prototype, and the object created by` new Date()` uses `Date.prototype` as its prototype. - -Almost all objects have a prototype, but only a relatively small number of objects have a `prototype `property. It is these objects with prototype properties that define the prototypes for all the other objects. - -Most built-in constructors (and most user-defined constructors) have a prototype that inherits from `Object.prototype`. - -`Date.prototype` inherits properties from `Object.prototype`, so a Date object created by `new Date()` inherits properties from both `Date.prototype` and `Object.prototype`. This linked series of prototype objects is known as a prototype chain. - -### Creating Objects - -Objects can be created with object literals, with the `new` keyword, and with the `Object.create()` function. - -Literal - -`let empty = {};` - -`let point = { x: 0, y: 0 };` - - let book = { - - "main title": "JavaScript", - - "sub-title": "The Definitive Guide", - - for: "all audiences", - - author: { - - firstname: "David", . - - surname: "Flanagan" - - } - - }; - -`new` - -`let o = new Object(); ` - `let a = new Array(); ` - `let d = new Date(); ` - `let r = new Map();` - -`Object.create` - -`let o3 = Object.create(Object.prototype);` - -Use `Object.create` to guard against accidental modifications: - - let o = { x: "don't change this value" }; - - library.function(Object.create(o)); - -Note: the library function can modify the passed in object, but not the original `o` object - -### Access Object Properties with an array (\[\]) notation - - let addr = ""; - - for(let i = 0; i < 4; i++) { - - addr += customer[`address${i}`] + "\n"; - - } - -### Inheritance - -`let o = {};` - -`o.x = 1;` - -`let p = Object.create(o);` - -`p.y = 2;` - -`let q = Object.create(p);` - -`q.z = 3;` - -Property `x` and `y` available on object `q` - -`q.x + q.y` - -### How to query for property which may be undefined - -`surname = book && book.author && book.author.surname;` - -`let surname = book?.author?.surname;` - -### Deleting properties - -The `delete` operator only deletes own properties, not inherited ones. (To delete an inherited property, you must delete it from the prototype object in which it is defined. Doing this affects every object that inherits from that prototype.) - -`delete` does not remove properties that have a `configurable `attribute of false. - -Certain properties of built-in objects are non-configurable, as are properties of the global object created by variable declaration and function declaration. - -`delete Object.prototype` - -false: property is non-configurable - -`var x = 1;` - -`delete globalThis.x` - -false: can't delete `this `property - -`function f() {}` - -`delete globalThis.f` - -false - -`globalThis.x = 1;` - -`delete globalThis.x` - -true - -### Testing properties - -To check whether an object has a property with a given name. You can do this with the `in` operator, with the `hasOwnProperty()` and `propertyIsEnumerable()` methods, or simply by querying the property - -( `!= undefined`). - -### in & query - -`let o = { x: 1 };` - -`"x" in o` - -true - -`o.x !== undefined` - -`"y" in o` - -false - -`o.y !== undefined` - -`"toString" in o` - -true: o inherits a `toString `property - -`o.toString !== undefined` - -Advantage of using in: `in` can distinguish between properties that do not exist and properties that exist but have been set to `undefined`. - -### hasOwnProperty - -`let o = { x: 1 };` - -`o.hasOwnProperty("x")` - -true - -`o.hasOwnProperty("y")` - -false - -`o.hasOwnProperty("toString")` - -false: toString is an inherited property - -The `propertyIsEnumerable()` returns true only if the named property is an own property and its `enumerable` attribute is true. - -`let o = { x: 1 };` - -`o.propertyIsEnumerable("x")` - -true - -`o.propertyIsEnumerable("toString")` - -false: not an own property - -`Object.prototype.propertyIsEnumerable("toString")` - -false: not enumerable - -### Enumerating properties - -To guard against enumerating inherited properties with `for/in`, you can add an explicit check inside the loop body: - - for(let p in o) { - - if (!o.hasOwnProperty(p)) continue; - - } - - for(let p in o) { - - if (typeof o[p] === "function") continue; - - } - -Functions you can use to get an array of property names - -· `Object.keys()` returns an array of the names of the enumerable own properties of an object. It does not include non-enumerable properties, inherited properties, or properties whose name is a Symbol. - -· `Object.getOwnPropertyNames()` works like `Object.keys() `but returns an array of the names of nonenumerable own properties as well. - -· `Object.getOwnPropertySymbols()` returns own properties whose names are Symbols, whether or not they are enumerable. - -· `Reflect.ownKeys()` returns all own property names, both enumerable and non-enumerable, and both string and Symbol. - -### Extending Objects - -To copy the properties of one object to another object - - let target = {x: 1}, source = {y: 2, z: 3}; - - for(let key of Object.keys(source)) { - - target[key] = source[key]; - - } - -One reason to assign properties from one object into another is when you have an object that defines default values for many properties and you want to copy those default properties into another object if a property by that name does not already exist in that object. Using `Object.assign()` naively will not do what you want: - - Object.assign(o, defaults); - -overwrites everything in o with defaults - -Instead, use one of the following:, - -`o = Object.assign({}, defaults, o);` - -`o = {...defaults, ...o};` - -### Serializing Objects - -The functions `JSON.stringify()` and` JSON.parse()` serialize and restore JavaScript objects. - -`let o = {x: 1, y: {z: [false, null, ""]}};` - -`let s = JSON.stringify(o);` - -s == '{"x":1,"y":{"z":\[false,null,""\]}}' - -`let p = JSON.parse(s);` - -p == {x: 1, y: {z: \[false,null, ""\]}} - -### Object methods - -`toString(), valueOf(), loLocaleString(), toJSON()` - -`let s = { x: 1, y: 1 }.toString();` - -s == "\[object Object\]" - -### Extended Object Literal Syntax - -### Shorthand Properties - - let x = 1, y = 2; - - let o = { - - x: x, - - y: y - - }; - -←> - -`let x = 1, y = 2;` - `let o = { x, y };` - -### Computer Property Names - -`const PROPERTY_NAME = "p1";` - `function computePropertyName() { return "p" + 2; }` - - let o = {}; - - o[PROPERTY_NAME] = 1; - - o[computePropertyName()] = 2; - -←> - - let p = { - - [PROPERTY_NAME]: 1, - - [computePropertyName()]: 2 - - }; - -### Symbols as Property Names - - const extension = Symbol("my extension symbol"); - - let o = { - - [extension]: {} - - }; - - o[extension].x = 0; - -Two Symbols created with the same string argument are still different from one another. - -The point of Symbols is not security, but to define a safe extension mechanism for JavaScript objects. If you get an object from third-party code that you do not control and need to add some of your own properties to that object but want to be sure that your properties will not conflict with any properties that may already exist on the object, you can safely use Symbols as your property names. - -### Spread Operator - -You can copy the properties of an existing object into a new object using the "spread operator" … inside an object literal: - -`let position = { x: 0, y: 0 };` - `let dimensions = { width: 100, height: 75 };` - `let rect = { ...position, ...dimensions };` - `rect.x + rect.y + rect.width + rect.height` - -### Shorthand Methods - - let square = { - - area: function() { - - return this.side * this.side; }, - - side: 10 - - }; - -←> - - let square = { - - area() { - - return this.side * this.side; }, - - side: 10 - - }; - -When you write a method using this shorthand syntax, the property name can take any of the forms that are legal in an object literal: in addition to a regular JavaScript identifier like the name area above, you can also use string literals and computed property names, which can include Symbol property names: - - const METHOD_NAME = "m"; - - const symbol = Symbol(); - - let weirdMethods = { - - "method With Spaces"(x) { return x + 1; }, - - [METHOD_NAME](x) { return x + 2; }, - - [symbol](x) { return x + 3; } - - }; - -`weirdMethods["method With Spaces"](1)` - -2 - -`weirdMethods[METHOD_NAME](1)` - -3 - -`weirdMethods[symbol](1)` - -4 - -### Property Getters and Setters - - let o = { - - dataProp: value, - - get accessorProp() { return this.dataProp; }, - - set accessorProp(value) { this.dataProp = value; } - - }; - -### Arrays - -### Creating Arrays - -· Array literals - -· The … spread operator on an iterable object - -· The `Array()` constructor - -· The `Array.of()` and `Array.from()` factory methods - -### Array literals - -`let empty = [];` - -`let primes = [2, 3, 5, 7, 11];` - -`let misc = [ 1.1, true, "a", ];` - -`let b = [[1, {x: 1, y: 2}], [2, {x: 3, y: 4}]];` - -If an array literal contains multiple commas in a row, with no value between, the array is sparse - -`let count = [1,,3];` - -`let undefs = [,,];` - -Array literal syntax allows an optional trailing comma, so `[,,]` has a length of 2, not 3. - -### The Spread Operator - -`let a = [1, 2, 3];` - -`let b = [0, ...a, 4];` - -\[0, 1, 2, 3, 4\] - -create a copy of an array — modifying the copy does not change the original - -`let original = [1,2,3];` - `let copy = [...original];` - -`let digits = [..."0123456789ABCDEF"];` - -\["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"\] - -`let letters = [..."hello world"];` - -\["h","e","l","l""o","","w","o""r","l","d"\] - -`[...new Set(letters)]` - -\["h","e","l","o","","w","r","d"\] - -### Array.of() - -When the `Array()` constructor function is invoked with one numeric argument, it uses that argument as an array length. But when invoked with more than one numeric argument, it treats those arguments as elements for the array to be created. This means that the `Array()` constructor cannot be used to create an array with a single numeric element. - -`Array.of()` - -\[\] - -`Array.of(10)` - -\[10\] - -`Array.of(1,2,3)` - -\[1, 2, 3\] - -### Array.from() - -It is also a simple way to make a copy of an array: - -`let copy = Array.from(original);` - -`Array.from()` is also important because it defines a way to make a true-array copy of an array-like object. Array-like objects are non-array objects that have a numeric length property and have values stored with properties whose names happen to be integers. - -`let truearray = Array.from(arraylike);` - -`Array.from()` also accepts an optional second argument. If you pass a function as the second argument, then as the new array is being built, each element from the source object will be passed to the function you specify, and the return value of the function will be stored in the array instead of the original value. - -### Reading and Writing Array Elements - -What is special about arrays is that when you use property names that are non-negative integers , the array automatically maintains the value of the `length` property for you. - -JavaScript converts the numeric array index you specify to a string — the index 1 becomes the string "1", then uses that string as a property name. - -It is helpful to clearly distinguish an array index from an object property name. All indexes are property names, but only property names that are integers between 0 and 231 are indexes. All arrays are objects, and you can create properties of any name on them. If you use properties that are array indexes, however, arrays have the special behavior of updating their `length` property as needed. - -Note that you can index an array using numbers that are negative or that are not integers. When you do this, the number is converted to a string, and that string is used as the property name. Since the name is not a non-negative integer, it is treated as a regular object property, not an array index. - -`a[-1.23] = true;` - -This creates a property named "-1.23" - -`a["1000"] = 0;` - -This the 1001st element of the array - -`a[1.000] = 1;` - -Array index 1. Same as a\[1\] = 1; - -The fact that array indexes are simply a special type of object property name means that JavaScript arrays have no notion of an "out of bounds" error. When you try to query a nonexistent property of any object, you don't get an error; you simply get `undefined`. - -### Sparse Arrays - -Sparse arrays can be created with the `Array()` constructor or simply by assigning to an array index larger than the current array length. - -`a[1000] = 0;` - -Assignment adds one element but sets length to 1001. - -you can also make an array sparse with the `delete` operator. - -Note that when you omit a value in an array literal (using repeated commas as in `[1,,3]`), the resulting array is sparse, and the omitted elements simply do not exist - -### Array Length - -if you set the length property to a nonnegative integer `n` smaller than its current value, any array elements whose index is greater than or equal to n are deleted from the array. - -`a = [1,2,3,4,5];` - -`a.length = 3;` - -a is now \[1,2,3\]. - -`a.length = 0;` - -Delete all elements. a is \[\]. - -`a.length = 5;` - -Length is 5, but no elements, like `new Array(5)` - -You can also set the length property of an array to a value larger than its current value. Doing this does not actually add any new elements to the array; it simply creates a sparse area at the end of the array. - -### Adding and Deleting Array Elements - -`let a = [];` - -`a[0] = "zero";` - -`a[1] = "one";` - -add elements to it. - -You can also use the `push()` method to add one or more values to the end of an array. - -You can use the` unshift()` method to insert a value at the beginning of an array, shifting the existing array elements to higher indexes. - -The `pop()` method is the opposite of `push()`: it removes the last element of the array and returns it, reducing the length of an array by 1. - -Similarly, the `shift()` method removes and returns the first element of the array, reducing the length by 1 and shifting all elements down to an index one lower than their current index. - -You can delete array elements with the delete operator - -`let a = [1,2,3];` - -`delete a[2];` - -a now has no element at index 2 - -`2 in a` - -false - -`a.length` - -3: delete does not affect array length - -### Iterating Arrays - -The easiest way to loop through each of the elements of an array (or any iterable object) is with the `for/of`loop - - let letters = [..."Hello world"]; - - let string = ""; - - for(let letter of letters) { - - string += letter; - - } - -It has no special behavior for sparse arrays and simply returns `undefined` for any array elements that do not exist. - -If you want to use a `for/of` loop for an array and need to know the index of each array element, use the `entries()` method of the array - - let letters = [..."Hello world"]; - - let everyother = ""; - - for(let [index, letter] of letters.entries()) { - - if (index % 2 === 0) everyother += letter; - - } - -Another good way to iterate arrays is with `forEach()`. This is not a new form of the for loop, but an array method that offers a functional approach to array iteration. - - let letters = [..."Hello world"]; - - let uppercase = ""; - - letters.forEach(letter => { - - uppercase += letter.toUpperCase(); - - }); - -You can also loop through the elements of an array with a `for` loop. - - for(let i = 0, len = letters.length; i < len; i++) { - - // loop body - - } - -### Multidimensional Arrays - -### Create a multidimensional array - -`let table = new Array(10);` - - for(let i = 0; i < table.length; i++) { - - table[i] = new Array(10); - - } - - for(let row = 0; row < table.length; row++) { - - for(let col = 0; col < table[row].length; col++) { - - table[row][col] = row * col; - - } - - } - -### Array Methods - -### Array Iterator Methods - -First, all of these methods accept a function as their first argument and invoke that function once for each element (or some elements) of the array. If the array is sparse, the function you pass is not invoked for nonexistent elements. In most cases, the function you supply is invoked with three arguments: the value of the array element, the index of the array element, and the array itself. - -FOREACH() - -`let data = [1,2,3,4,5], sum = 0;` - - data.forEach(value => { sum += value; }); - - data.forEach(function(v, i, a) { - - a[i] = v + 1; - - }); - -15 - -\[2,3,4,5,6\] - -MAP() - -`let a = [1, 2, 3];` - `a.map(x => x*x)` - -\[1, 4, 9\] - -FILTER() - -`let a = [5, 4, 3, 2, 1];` - `a.filter(x => x < 3) ` - `a.filter((x,i) => i % 2 === 0)` - -\[2, 1\]; - -\[5, 3, 1\]; - -FIND() - -FINDINDEX() - -`let a = [1,2,3,4,5];` - -`a.findIndex(x => x === 3)` - -`a.find(x => x % 5 === 0)` - -`a.find(x => x % 7 === 0)` - -2 - -5 - -undefined - -EVERY() - -SOME() - -`let a = [1,2,3,4,5];` - -`a.every(x => x < 10)` - -`a.some(x => x % 2 === 0)` - -`a.some(isNaN)` - -true - -true - -false - -REDUCE() - -ReduceRight() - -l`et a = [1,2,3,4,5];` - -`a.reduce((x,y) => x+y, 0)` - -`a.reduce((x,y) => x*y, 1)` - -`a.reduce((x,y) => (x > y) ? x : y)` - -15 - -120 - -5 - -Note that `map()` returns a new array: it does not modify the array it is invoked on. If that array is sparse, your function will not be called for the missing elements, but the returned array will be sparse in the same way as the original array: it will have the same length and the same missing elements. - -To close the gaps in a sparse array, you can do this: - -`let dense = sparse.filter(() => true);` - -And to close gaps and remove undefined and null elements, you can use filter, like this: - -`a = a.filter(x => x !== undefined && x !== null);` - -Unlike `filter()`, however,` find()` and `findIndex()` stop iterating the first time the predicate finds an element. When that happens, `find()` returns the matching element, and `findIndex()` returns the index of the matching element. If no matching element is found,` find()` returns `undefined` and` findIndex()`returns -1. - -When you invoke `reduce()` with no initial value, it uses the first element of the array as the initial value. - -`reduceRight()` works just like `reduce()`, except that it processes the array from highest index to lowest (right-to-left), rather than from lowest to highest. You might want to do this if the reduction operation has right-to-left associativity - -### Flattening arrays with `flat()` and `flatMap()` - -`[1, [2, 3]].flat()` - -\[1, 2, 3\] - -`[1, [2, [3]]].flat()` - -\[1, 2, \[3\]\] - -`let a = [1, [2, [3, [4]]]];` - -`a.flat(1)` - -`a.flat(2)` - -`a.flat(3)` - -`a.flat(4)` - -\[1, 2, \[3, \[4\]\]\] - -\[1, 2, 3, \[4\]\] - -\[1, 2, 3, 4\] - -\[1, 2, 3, 4\] - -`let phrases = ["hello world", "the definitive guide"];` - `let words = phrases.flatMap(phrase => phrase.split(" "));` - -\["hello", "world", "the", "definitive", "guide"\]; - -Calling `a.flatMap(f)` is the same as (but more efficient than) `a.map(f).flat()`: - -### Adding arrays with concat() - -`let a = [1,2,3];` - -`a.concat(4, 5)` - -\[1,2,3,4,5\] - -`a.concat([4,5],[6,7])` - -\[1,2,3,4,5,6,7\] - -### Stacks and Queues with push(), pop(), shift(), and unshift() - -The `push()` and` pop()` methods allow you to work with arrays as if they were stacks. The `push()` method appends one or more new elements to the end of an array and returns the new length of the array. - -The `unshift()` and `shift()` methods behave much like `push()` and` pop()`, except that they insert and remove elements from the beginning of an array rather than from the end. - -You can implement a queue data structure by using `push()` to add elements at the end of an array and `shift()` to remove them from the start of the array. Note differences in `unshift `with single and multiple values. - -`let a = [];` - -`a.unshift(1)` - -\[1\] - -`a.unshift(2)` - -\[2, 1\] - -`a = [];` - -`a.unshift(1,2)` - -\[1, 2\] - -### Subarrays with `slice(), splice(), fill()`, and `copyWithin()` - -SLICE() - -`let a = [1,2,3,4,5];` - -`a.slice(0,3);` - -`a.slice(3);` - -`a.slice(1,-1);` - -`a.slice(-3,-2);` - -\[1,2,3\] - -\[4,5\] - -\[2,3,4\] - -\[3\] - -SPLICE - -`let a = [1,2,3,4,5,6,7,8];` - -`a.splice(4)` - -`a.splice(1,2)` - -`a.splice(1,1)` - -`let a = [1,2,3,4,5];` - -`a.splice(2,0,"a","b")` - -`a.splice(2,2,[1,2],3)` - -\[5,6,7,8\]; `a` is now \[1,2,3,4\] - -\[2,3\]; a is now \[1,4\] - -\[4\]; a is now \[1\] - -\[\]; a is now \[1,2,"a","b",3,4,5\] - -\["a","b"\]; a is now \[1,2,\[1,2\],3,3,4,5\] - -FILL() - -`let a = new Array(5);` - -`a.fill(0)` - -`a.fill(9, 1)` - -`a.fill(8, 2, -1)` - -\[0,0,0,0,0\] - -\[0,9,9,9,9\] - -\[0,9,8,8,9\] - -COPYWITHIN() - -`let a = [1,2,3,4,5];` - -`a.copyWithin(1)` - -`a.copyWithin(2, 3, 5)` - -`a.copyWithin(0, -2)` - -\[1,1,2,3,4\] - -\[1,1,3,4,4\] - -\[4,4,3,4,4\] - -`splice()` is a general-purpose method for inserting or removing elements from an array.` splice()` can delete elements from an array, insert new elements into an array, or perform both operations at the same time. - -The first argument to `splice()` specifies the array position at which the insertion and/or deletion is to begin. The second argument specifies the number of elements that should be deleted from (spliced out of) the array. - -Unlike `concat(), splice()` inserts arrays themselves, not the elements of those arrays. - -`copyWithin()` copies a slice of an array to a new position within the array. It modifies the array in place and returns the modified array, but it will not change the length of the array. - -### Array Searching and Sorting Methods - -INDEXOF() - LASTINDEXOF() - -`let a = [0,1,2,1,0];` - -`a.indexOf(1)` - -`a.lastIndexOf(1)` - -`a.indexOf(3)` - -1 - -3 - --1 - -SORT() - -`let a = [33, 4, 1111, 222];` - -`a.sort();` - -`a.sort((a,b) => a - b);` - -Case-insensitive sort - - let a = ["ant", "Bug", "cat", "Dog"]; - - a.sort(); // a == ["Bug","Dog","ant","cat"]; - - a.sort(function(s,t) { - - let a = s.toLowerCase(); - - let b = t.toLowerCase(); - - if (a < b) return -1; - - if (a > b) return 1; - - return 0; - - }); - -`[1111, 222, 33, 4];` - -`[4, 33, 222, 1111]` - -REVERSE() - -`let a = [1,2,3];` - `a.reverse();` - -\[3,2,1\] - -`indexOf()` and `lastIndexOf()` compare their argument to the array elements using the equivalent of the === operator. If your array contains objects instead of primitive values, these methods check to see if two references both refer to exactly the same object. If you want to actually look at the content of an object, try using the `find()` method with your own custom predicate function instead. - -`indexOf()` and `lastIndexOf()` take an optional second argument that specifies the array index at which to begin the search. Negative values are allowed for the second argument and are treated as an offset from the end of the array. - -`indexOf()` will not detect the NaN value in an array, but `includes()` will - -When `sort()` is called with no arguments, it sorts the array elements in alphabetical order. To sort an array into some order other than alphabetical, you must pass a comparison function as an argument to `sort()`. - -### Array to String Conversions - -The `join()` method converts all the elements of an array to strings and concatenates them, returning the resulting string. - -`let a = [1, 2, 3];` - -`a.join()` - -`a.join(" ")` - -`a.join("")` - -"1,2,3" - -"1 2 3" - -"123" - -`let b = new Array(10);` - -`b.join("-")` - -" — — — — -" - -Arrays, like all JavaScript objects, have a `toString()` method. For an array, this method works just like the `join()` method with no arguments: - -`[1,2,3].toString()` - -"1,2,3" - -`["a", "b", "c"].toString()` - -"a,b,c" - -`[1, [2,"c"]].toString()` - -"1,2,c" - -### Static Array Functions - -`Array.isArray([])` - -true - -`Array.isArray({})` - -false - -### Array-Like Objects - -It is often perfectly reasonable to treat any object with a numeric `length` property and corresponding non-negative integer properties as a kind of array. - - let a = {}; - - let i = 0; - - while(i < 10) { - - a[i] = i * i; - - i++; - - } - - a.length = i; - - // Now iterate through it as if it were a real array - - let total = 0; - - for(let j = 0; j < a.length; j++) { - - total += a[j]; - - } - -Since array-like objects do not inherit from `Array.prototype`, you cannot invoke array methods on them directly. You can invoke them indirectly using the `Function.call` method. - -`let a = {"0": "a", "1": "b", "2": "c", length: 3};` - -// An array-like object - -`Array.prototype.join.call(a, "+")` - -"a+b+c" - -`Array.prototype.join.call("JavaScript", " ")` - -"J a v a S c r i p t" - -`Array.prototype.map.call(a, x => x.toUpperCase())` - -\["A","B","C"\] - -`Array.from(a)` - -\["a","b","c"\] - -### Strings as Arrays - -`let s = "test";` - -`s.charAt(0)` - -t - -`s[1]` - -e - -### Functions - -In addition to the arguments, each invocation has another value — the invocation context — that is the value of the `this` keyword. - -### Function Declarations - - function printprops(o) { - - for(let p in o) { - - console.log(`${p}: ${o[p]}\n`); - - } - - } - -Function declaration statements are "hoisted" to the top of the enclosing script, function, or block so that functions defined in this way may be invoked from code that appears before the definition. - -### Function Expressions - -`const square = function(x) { return x*x; };` - - const f = function fact(x) { - - if (x <= 1) return 1; - - return x * fact(x-1); - - } - -Function expressions can include names, which is useful for recursion - -`[3,2,1].sort(function(a,b) { return a - b; });` - -Function expressions can also be used as arguments to other functions - -`let tensquared = (function(x) {return x*x;}(10));` - -Function expressions are sometimes defined and immediately invoked - -### Arrow Functions - -`const sum = (x, y) => { return x + y; };` - -`const sum = (x, y) => x + y;` - -no need for `return` - -`const polynomial = x => x*x + 2*x + 3;` - -omit parens with single parameter - -`const constantFunc = () => 42;` - -usage for no params - -If the body of your arrow function is a single return statement but the expression to be returned is an object literal, then you have to put the object literal inside parentheses to avoid syntactic ambiguity between the curly braces of a function body and the curly braces of an object literal - -`const f = x => { return { value: x }; };` - -good - -`const g = x => ({ value: x });` - -good - -`const h = x => { value: x };` - -returns nothing - -`const i = x => { v: x, w: x };` - -syntax error - -Arrow functions differ from functions defined in other ways in one critical way: they inherit the value of the `this` keyword from the environment in which they are defined rather than defining their own invocation context as functions defined in other ways do. - -### Nested Functions - - function hypotenuse(a, b) { - - function square(x) { return x*x; } - - return Math.sqrt(square(a) + square(b)); - - } - -### Invoking Functions - -For function invocation in non-strict mode, the invocation context (the `this` value) is the global object. In strict mode, however, the invocation context is `undefined`. - -`const strict = (function() { return !this; }())` - -Determine if we're in strict mode - -### Constructor Invocation - -A constructor invocation creates a new, empty object that inherits from the object specified by the `prototype`property of the constructor. - -### Indirect invocation - -JavaScript functions are objects, and like all JavaScript objects, they have methods. Two of these methods, `call()` and `apply()`, invoke the function indirectly. Both methods allow you to explicitly specify the `this `value for the invocation, which means you can invoke any function as a method of any object, even if it is not actually a method of that object. - -### Function Arguments and Parameters - -### Optional Parameters and Defaults - -When a function is invoked with fewer arguments than declared parameters, the additional parameters are set to their default value, which is normally `undefined`. - - function getPropertyNames(o, a) { - - a = a || []; - - for(let property in o) a.push(property); - - return a; - - } - - function getPropertyNames(o, a = []) { - - for(let property in o) a.push(property); - - return a; - - } - -One interesting case is that, for functions with multiple parameters, you can use the value of a previous parameter to define the default value of the parameters that follow it - - const rectangle = (width, height = width*2) => ({width, height}); - -### Rest Parameters and Variable-Length Argument Lists - -Rest parameters enable us to write functions that can be invoked with arbitrarily more arguments than parameters. - - function max(first=-Infinity, ...rest) { - - let maxValue = first; - - for(let n of rest) { - - if (n > maxValue) { - - maxValue = n; - - } - - } - - return maxValue; - - } - - max(1, 10, 100, 2, 3, 1000, 4, 5, 6) - -1000 - -within the body of a function, the value of a rest parameter will always be an array. The array may be empty, but a rest parameter will never be `undefined`. - -This type of function is called variadic functions, variable arity functions, or vararg functions. - -### The Arguments Object - -Within the body of any function, the identifier `arguments` refers to the Arguments object for that invocation. - - function max(x) { - - let maxValue = -Infinity; - - for(let i = 0; i < arguments.length; i++) { - - if (arguments[i] > maxValue) - - maxValue = arguments[i]; - - } - - return maxValue; - - } - - max(1, 10, 100, 2, 3, 1000, 4, 5, 6) - -1000 - -you should avoid using it in any new code you write. - -### The Spread Operator for Function Calls - - let numbers = [5, 2, 10, -1, 9, 100, 1]; - - Math.min(...numbers) - --1 - - function timed(f) { - - return function(...args) { - - console.log(`Entering function ${f.name}`); - - let startTime = Date.now(); - - try { - - return f(...args); - - } - - finally { - - console.log(`Exiting ${f.name} after ${Date.now() - startTime}ms`); - - } - - }; - - } - - // Compute the sum of the numbers between 1 and n by brute force - - function benchmark(n) { - - let sum = 0; - - for(let i = 1; i <= n; i++) sum += i; - - return sum; - - } - - // Now invoke the timed version of that test function - - timed(benchmark)(1000000) - -### Destructuring Function Arguments into Parameters - - function vectorAdd(v1, v2) { - - return [v1[0] + v2[0], v1[1] + v2[1]]; - - } - - vectorAdd([1,2], [3,4]) - -←> - - function vectorAdd([x1,y1], [x2,y2]) { - - return [x1 + x2, y1 + y2]; - - } - - vectorAdd([1,2], [3,4]) - - function vectorMultiply({x, y}, scalar) { - - return { x: x*scalar, y: y*scalar }; - - } - - vectorMultiply({x: 1, y: 2}, 2) - -←> - - function vectorMultiply({x,y}, scalar) { - - return { x: x*scalar, y: y*scalar}; - - } - - vectorMultiply({x: 1, y: 2}, 2) - -### Argument Types - -Adding code to check the types of arguments - - function sum(a) { - - let total = 0; - - for(let element of a) { - - if (typeof element !== "number") { - - throw new TypeError("sum(): elements must be numbers"); - - } - - total += element; - - } - - return total; - - } - -`sum([1,2,3])` - -6 - -`sum(1, 2, 3);` - -`TypeError`: 1 is not iterable - -`sum([1,2,"3"]);` - -`TypeError`: element 2 is not a number - -### Functions as Values - - function square(x) { return x * x; } - -`let s = square;` - -`square(4)` - -16 - -`s(4)` - -16 - -Functions can also be assigned to object properties rather than variables. - -`let o = {square: function(x) { return x*x; }};` - -`let y = o.square(16);` - -256 - -Functions don't even require names at all, as when they're assigned to array elements: - -`let a = [x => x*x, 20];` - -`a[0](a[1])` - -400 - -`a[0]` accesses first element of the array, which is "`x => x*x`", `(a[1])` passes parameter, which is 20. - -### Examples of using functions as data - - function add(x,y) { return x + y; } - - function subtract(x,y) { return x - y; } - - function multiply(x,y) { return x * y; } - - function divide(x,y) { return x / y; } - - function operate(operator, operand1, operand2) { - - return operator(operand1, operand2); - - } - -`let i = operate(add, operate(add, 2, 3), operate(multiply, 4,5));` - -`(2+3) + (4*5):` - -or: - - const operators = { - - add: (x,y) => x+y, - - subtract: (x,y) => x-y, - - multiply: (x,y) => x*y, - - divide: (x,y) => x/y, - - pow: Math.pow - - }; - - function operate2(operation, operand1, operand2) { - - if (typeof operators[operation] === "function") { - - return operators[operation](operand1, operand2); - - } - - else throw "unknown operator"; - - } - -`operate2("add", "hello", operate2("add", " ", "world"))` - -// "hello world" - -`operate2("pow", 10, 2)` - -100 - -### Defining Your Own Function Properties - -When a function needs a "static" variable whose value persists across invocations, it is often convenient to use a property of the function itself. - -For example, suppose you want to write a function that returns a unique integer whenever it is invoked. The function must never return the same value twice. In order to manage this, the function needs to keep track of the values it has already returned, and this information must persist across function invocations. - - uniqueInteger.counter = 0; - - function uniqueInteger() { - - return uniqueInteger.counter++; - - } - - uniqueInteger() - -0 - - uniqueInteger() - -1 - -Compute factorials and cache results as properties of the function itself. - - function factorial(n) { - - if (Number.isInteger(n) && n > 0) { - - if (!(n in factorial)) { - - factorial[n] = n * factorial(n-1); - - } - - return factorial[n]; - - } - - else { - - return NaN; - - } - - } - - factorial[1] = 1; - -Initialize the cache to hold this base case. - - factorial(6) - -720 - - factorial[5] - -120; the call above caches this value - -### Functions as Namespaces - -Variables declared within a function are not visible outside of the function. For this reason, it is sometimes useful to define a function simply to act as a temporary namespace in which you can define variables without cluttering the global namespace. - -Variables that would have been global become local to the function. Following code defines only a single global variable: the function name `chunkNamespace`. - - function chunkNamespace() { - - // Chunk of code goes here - - // Any variables defined in the chunk are local to this function - - // instead of cluttering up the global namespace. - - } - - chunkNamespace(); - -If defining even a single property is too much, you can define and invoke an anonymous function in a single expression — IIEF (immediately invoked function expression) - - (function() { - - // chunkNamespace() function rewritten as an unnamed expression. - - // Chunk of code goes here - - }()); - -### Closures - -JavaScript uses lexical scoping. This means that functions are executed using the variable scope that was in effect when they were defined, not the variable scope that is in effect when they are invoked. - -In order to implement lexical scoping, the internal state of a JavaScript function object must include not only the code of the function but also a reference to the scope in which the function definition appears. - -This combination of a function object and a scope (a set of variable bindings) in which the function's variables are resolved is called a closure. - -Closures become interesting when they are invoked from a different scope than the one they were defined in. This happens most commonly when a nested function object is returned from the function within which it was defined. - - let scope = "global scope"; - - function checkscope() { - - let scope = "local scope"; - - function f() { return scope; } - - return f(); - - } - -`checkscope()` - -"local scope" - - let scope = "global scope"; - - function checkscope() { - - let scope = "local scope"; - - function f() { return scope; } - - return f; - - } - -`let s = checkscope()();` - -"local scope" - -Closures capture the local variables of a single function invocation and can use those variables as private state. - - let uniqueInteger = (function() { - - let counter = 0; - - return function() { return counter++; }; - - }()); - -`uniqueInteger()` - -0 - -`uniqueInteger()` - -1 - -it is the return value of the function that is being assigned to `uniqueInteger`. - -Private variables like counter need not be exclusive to a single closure: it is perfectly possible for two or more nested functions to be defined within the same outer function and share the same scope. - - function counter() { - - let n = 0; - - return { - - count: function() { return n++; }, - - reset: function() { n = 0; } - - }; - - } - -`let c = counter(), d = counter();` - -`c.count()` - -0 - -`d.count()` - -0 - -`c.reset();` - -`c.count()` - -0 - -`d.count()` - -1 - -You can combine this closure technique with property getters and setters - - function counter(n) { - - return { - - get count() { return n++; }, - - set count(m) { - - if (m > n) n = m; - - else throw Error("count can only be set to a larger value") - - } - - }; - - } - -`let c = counter(1000);` - -`c.count` - -1000 - -`c.count` - -1001 - -`c.count = 2000;` - -`c.count` - -2000 - -`c.count = 2000;` - -Error: count can only be set to a larger value - -Define a private variable and two nested functions to get and set the value of that variable. - - function addPrivateProperty(o, name, predicate) { - - let value; - - o[`get${name}`] = function() { return value; }; - - o[`set${name}`] = function(v) { - - if (predicate && !predicate(v)) { - - throw new TypeError(`set${name}: invalid value ${v}`); - - } - - else { - - value = v; - - } - - }; - - } - -`let o = {};` - -`addPrivateProperty(o, "Name", x => typeof x === "string");` - -`o.setName("Frank");` - -`o.getName()` - -"Frank" - -`o.setName(0);` - -TypeError: try to set a value ofthe wrong type - -### Function Properties, Methods, and Constructor - -Since functions are objects, they can have properties and methods, just like any other object. - -### The length Property - -The read-only length property of a function specifies the arity of the function — the number of parameters it declares in its parameter list, which is usually the number of arguments that the function expects. - -### The name Property - -This property is primarily useful when writing debugging or error messages. - -### The prototype Property - -When a function is used as a constructor, the newly created object inherits properties from the prototype object. - -### The call() and apply() Methods - -`call()` and `apply()` allow you to indirectly invoke a function as if it were a method of some other object. The first argument to both `call()` and `apply()` is the object on which the function is to be invoked; this argument is the invocation context and becomes the value of the `this` keyword within the body of the function. - -To invoke the function` f()` as a method of the object o (passing no arguments), - -`f.call(o);` - -`f.apply(o);` - -To pass two numbers to the function `f()` and invoke it as if it were a method of the object o, - - f.call(o, 1, 2); - -The `apply()` method is like the `call()` method, except that the arguments to be passed to the function are specified as an array: - - f.apply(o, [1,2]); - -The `trace() `function defined uses the `apply() `method instead of a spread operator, and by doing that, it is able to invoke the wrapped method with the same arguments and the same this value as the wrapper method - - function trace(o, m) { - - let original = o[m]; - - o[m] = function(...args) { - - console.log(new Date(), "Entering:", m); - - let result = original.apply(this, args); - - console.log(new Date(), "Exiting:", m); - - return result; - - }; - - } - -### The bind() Method - -The primary purpose of `bind()` is to bind a function to an object. - -`function f(y) { return this.x + y; }` - -`let o = { x: 1 };` - -`let g = f.bind(o);` - -`g(2)` - -3 - -`let p = { x: 10, g };` - -`p.g(2)` - -3 // g is still bound to o, not p. - -The most common use case for calling `bind()` is to make non-arrow functions behave like arrow functions. - -Partial application is a common technique in functional programming and is sometimes called `currying`. - -`let sum = (x,y) => x + y;` - -`let succ = sum.bind(null, 1);` - -`succ(2)` - -3 - -### The toString() Method - -Most (but not all) implementations of this `toString()` method return the complete source code for the function - -### The Function() Constructor - -The Function() constructor is best thought of as a globally scoped version of `eval()` that defines new variables and functions in its own private scope. You will probably never need to use this constructor in your code. - -### Higher-Order Functions - -A higher-order function is a function that operates on functions, taking one or more functions as arguments and returning a new function. - - function not(f) { - - return function(...args) { - - let result = f.apply(this, args); - - return !result; - - }; - - } - -`const even = x => x % 2 === 0;` - -A function to determine if a number is even - -`const odd = not(even);` - -`[1,1,3,5,5].every(odd)` - -true - -Returns a new function that maps one array to another - - const map = function(a, ...args) { return a.map(...args); }; - - function mapper(f) { - - return a => map(a, f); - - } - - const increment = x => x + 1; - - const incrementAll = mapper(increment); - - incrementAll([1,2,3] - -\[2,3,4\] - -Example that takes two functions, f and g, and returns a new function that computes f(g()): - - function compose(f, g) { - - return function(...args) { - - return f.call(this, g.apply(this, args)); - - }; - - } - -`const sum = (x,y) => x+y;` - -`const square = x => x*x;` - -`compose(square, sum)(2,3)` - -25 - -### Memoization - -We defined a factorial function that cached its previously computed results. In functional programming, this kind of caching is called memoization. - -### Classes - -JavaScript's classes and prototype-based inheritance mechanism are substantially different from the classes and class-based inheritance mechanism of Java. - -### Classes and Prototypes - -If we define a prototype object and then use `Object.create()` to create objects that inherit from it, we have defined a JavaScript class. - -Factory function that returns a new range object: - - function range(from, to) { - - let r = Object.create(range.methods); - - r.from = from; - - r.to = to; - - return r; - - } - - range.methods = { - - includes(x) { return this.from <= x && x <= this.to; }, - - *[Symbol.iterator]() { - - for(let x = Math.ceil(this.from); x <= this.to; x++) - - yield x; - - }, - - toString() { return "(" + this.from + "..." + this.to +")"; } - - }; - -`let r = range(1,3);` - -`r.includes(2)` - -true - -`r.toString()` - -"(1…3)" - -`[...r]` - -\[1, 2, 3\] - -### Classes and Constructors - -A constructor is a function designed for the initialization of newly created objects. - -The critical feature of constructor invocations is that the `prototype` property of the constructor is used as the prototype of the new object. - -While almost all objects have a prototype, only a few objects have a `prototype` property. It is function objects that have a `prototype` property. - -This means that all objects created with the same constructor function inherit from the same object and are therefore members of the same class. - -A Range class using a constructor - - function Range(from, to) { - - this.from = from; - - this.to = to; - - } - - Range.prototype = { - - includes: function(x) { return this.from <= x && x <= this.to; }, - - [Symbol.iterator]: function*() { - - for(let x = Math.ceil(this.from); x <= this.to; x++) - - yield x; - - }, - - toString: function() { return "(" + this.from + "..." + this.to + ")"; } - - }; - -`let r = new Range(1,3);` - -`r.includes(2)` - -true - -`r.toString()` - -"(1…3)" - -`[...r]` - -\[1, 2, 3\] - -Because the `Range() `constructor is invoked with `new`, it does not have to call `Object.create()` or take any action to create a new object. - -In the first example, the prototype was `range.methods`. This was a convenient and descriptive name, but arbitrary. In the second example, the prototype is `Range.prototype`, and this name is mandatory. - -An invocation of the `Range()` constructor automatically uses `Range.prototype` as the prototype of the `new Range` object. - -### Constructors, Class Identity, and instanceof - -Two objects are instances of the same class if and only if they inherit from the same prototype object. - -The `instanceof` operator is not checking whether `r` was actually initialized by the Range constructor. Instead, it is checking whether `r` inherits from `Range.prototype`. - - function Strange() {} - - Strange.prototype = Range.prototype; - - new Strange() instanceof Range - -true - -If you want to test the prototype chain of an object for a specific prototype and do not want to use the constructor function as an intermediary, you can use the `isPrototypeOf()` method - - range.methods.isPrototypeOf(r); - -### The constructor Property - -Every regular JavaScript function automatically has a `prototype` property. The value of this property is an object that has a single, non-enumerable `constructor` property. - -The value of the `constructor` property is the function object - - let F = function() {}; - - let p = F.prototype; - - let c = p.constructor; - - c === F - -true - -`let o = new F();` - -`o.constructor === F` - -true - -Instances of the Range class, as defined, do not have a constructor property. We can remedy this problem by explicitly adding a constructor to the prototype: - - Range.prototype = { - - constructor: Range - - }; - -Another common technique that you are likely to see in older JavaScript code is to use the predefined prototype object with its constructor property and add methods to it one at a time with code like this: - - Range.prototype.includes = function(x) { - - return this.from <= x && x <= this.to; - - }; - - Range.prototype.toString = function() { - - return "(" + this.from + "..." + this.to + ")"; - - }; - -### Classes with the class Keyword - - class Range { - - constructor(from, to) { - - this.from = from; - - this.to = to; - - } - - includes(x) { return this.from <= x && x <= this.to; } - - *[Symbol.iterator]() { - - for(let x = Math.ceil(this.from); x <= this.to; x++) - - yield x; - - } - - toString() { return `(${this.from}...${this.to})`; } - - } - -`let r = new Range(1,3);` - -`r.includes(2)` - -true - -`r.toString()` - -(1…3) - -`[...r]` - -\[1, 2, 3\] - -Although class bodies are superficially similar to object literals, they are not the same thing. In particular, they do not support the definition of properties with name/value pairs. - -If your class does not need to do any initialization, you can omit the constructor keyword and its body, and an empty constructor function will be implicitly created for you. - -If you want to define a class that subclasses — or inherits from — another class, you can use the `extends` keyword with the class keyword: - - class Span extends Range { - - constructor(start, length) { - - if (length >= 0) { - - super(start, start + length); - - } - - else { - - super(start + length, start); - - } - - } - - } - -class declarations have both statement and expression forms - -`let Square = class { constructor(x) { this.area = x * x; } };` - -`new Square(3).area` - -9 - -### Static methods - -You can define a `static` method within a class body by prefixing the method declaration with the `static` keyword. Static methods are defined as properties of the constructor function rather than properties of the prototype object. - - static parse(s) { - - let matches = s.match(/^\((\d+)\.\.\.(\d+)\)$/); - - if (!matches) { - - throw new TypeError(`Cannot parse Range from "${s}".`) - - } - - return new Range(parseInt(matches[1]), - - parseInt(matches[2])); - - } - -The method defined by this code is `Range.parse()`, not `Range.prototype.parse()`, and you must invoke it through the constructor, not through an instance: - - let r = Range.parse('(1...10)'); - -### Getters, Setters, and other Method Forms - -Within a class body, you can define getter and setter methods just as you can in object literals. The only difference is that in class bodies, you don't put a comma after the getter or setter. - -### Public, Private, and Static Fields - -The ES6 standard only allows the creation of methods (including getters, setters, and generators) and static methods; it does not include syntax for defining fields. - -If you want to define a field on a class instance, you must do that in the constructor function or in one of the methods. And if you want to define a static field for a class, you must do that outside the class body, after the class has been defined. - -Standardization is underway, however, for extended class syntax that allows the definition of instance and static fields, in both public and private forms. - - class Buffer { - - constructor() { - - this.size = 0; - - this.capacity = 4096; - - this.buffer = new Uint8Array(this.capacity); - - } - - } - -←> - - class Buffer { - - size = 0; - - capacity = 4096; - - buffer = new Uint8Array(this.capacity); - - } - -The same proposal that seeks to standardize these instance fields also defines private (with the \# prefix) instance fields. - - class Buffer { - - #size = 0; - - get size() { return this.#size; } - - } - -A related proposal seeks to standardize the use of the `static` keyword for fields. - - static integerRangePattern = /^\((\d+)\.\.\.(\d+)\)$/; - - static parse(s) { - - let matches = s.match(Range.integerRangePattern); - - if (!matches) { - - throw new TypeError(`Cannot parse Range from "${s}".`) - - } - - return new Range(parseInt(matches[1]), matches[2]); - - } - -### Adding Methods to Existing Classes - -We can augment JavaScript classes simply by adding new methods to their prototype objects. - - if (!String.prototype.startsWith) { - - String.prototype.startsWith = function(s) { - - return this.indexOf(s) === 0; - - }; - - } - - Number.prototype.times = function(f, context) { - - let n = this.valueOf(); - - for(let i = 0; i < n; i++) f.call(context, i); - - }; - -### Subclasses - -### Subclasses and Prototypes - -Span subclass of the Range class. This subclass will work just like a Range, but instead of initializing it with a start and an end, we'll instead specify a start and a distance, or span. - - function Span(start, span) { - - if (span >= 0) { - - this.from = start; - - this.to = start + span; - - } - - else { - - this.to = start; - - this.from = start + span; - - } - - } - -Ensure that the `Span` prototype inherits from the `Range` - - Span.prototype = Object.create(Range.prototype); - -We don't want to inherit `Range.prototype.constructor`, so we define our own constructor property: - - Span.prototype.constructor = Span; - -`Span` overrides the `toString()` method - -`Span.prototype.toString = function() {` - `` return `(${this.from}... +${this.to - this.from})`; `` - `};` - -A robust subclassing mechanism needs to allow classes to invoke the methods and constructor of their superclass, but prior to ES6, JavaScript did not have a simple way to do these things. - -### Subclasses with extends and super - - class EZArray extends Array { - - get first() { return this[0]; } - - get last() { return this[this.length-1]; } - - } - -`let a = new EZArray();` - -`a instanceof EZArray` - -true - -`a instanceof Array` - -true - -`a.push(1,2,3,4);` - -`a.pop()` - -4 - -`a.first` - -1 - -`a.last` - -3 - -`Array.isArray(a)` - -true - -`EZArray.isArray(a)` - -true - -`Array.prototype.isPrototypeOf(EZArray.prototype` - -true - -`Array.isPrototypeOf(EZArray)` - -true - -Example demonstrates the use of the `super` keyword to invoke the constructor and methods of the superclass - - class TypedMap extends Map { - - constructor(keyType, valueType, entries) { - - if (entries) { - - for(let [k, v] of entries) { - - if (typeof k !== keyType || typeof v !== valueType) { - - throw new TypeError(`Wrong type for entry [${k}, ${v}]`); - - } - - } - - } - - super(entries); - - this.keyType = keyType; - - this.valueType = valueType; - - } - - set(key, value) { - - if (this.keyType && typeof key !== this.keyType) { - - throw new TypeError(`${key} is not of type${this.keyType}`); - - } - - if (this.valueType && typeof value !== this.valueType) - - { - - throw new TypeError(`${value} is not of type ${this.valueType}`); - - } - - return super.set(key, value); - - } - - } - -You may not use the `this` keyword in your constructor until after you have invoked the superclass constructor with `super()`. This enforces a rule that superclasses get to initialize themselves before subclasses do. - -Once private fields are supported, we could change these properties to `#keyType` and `#valueType` so that they could not be altered from the outside. - -### Class Hierarchies and Abstract Classes - -Define abstract classes — classes that do not include a complete implementation — to serve as a common superclass for a group of related subclasses. - -### Modules - -### Automating Closure-Based Modularity - -Imagine a tool that takes a set of files, wraps the content of each of those files within an immediately invoked function expression, keeps track of the return value of each function, and concatenates everything into one big file. - - const modules = {}; - - function require(moduleName) { return modules[moduleName]; } - - modules["sets.js"] = (function() { - - const exports = {}; - - exports.BitSet = class BitSet { ... }; - - return exports; - - }()); - - modules["stats.js"] = (function() { - - const exports = {}; - - const sum = (x, y) => x + y; - - const square = x = > x * x; - - exports.mean = function(data) { ... }; - - exports.stddev = function(data) { ... }; - - return exports; - - }()); - -writing code like the following to make use of those modules - - const stats = require("stats.js"); - - const BitSet = require("sets.js").BitSet; - - // Now write code using those modules - - let s = new BitSet(100); - - s.insert(10); - - s.insert(20); - - s.insert(30); - - let average = stats.mean([...s]); - -### Modules in ES6 - -ES6 adds import and export keywords to JavaScript and finally supports real modularity as a core language feature. - -ES6 modularity is conceptually the same as Node modularity: each file is its own module, and constants, variables, functions, and classes defined within a file are private to that module unless they are explicitly exported. - -### ES6 Exports - -To export a constant, variable, function, or class from an ES6 module, simply add the keyword export before the declaration - - export const PI = Math.PI; - - export function degreesToRadians(d) { return d * PI / 180; } - - export class Circle { - - constructor(r) { this.r = r; } - - area() { return PI * this.r * this.r; } - - } - -or: - - export { Circle, degreesToRadians, PI }; - -It is common to write modules that export only one value (typically a function or class), and in this case, we usually use export `default` instead of `export` - - export default class BitSet { - - // implementation omitted - - } - -### ES6 Imports - - import BitSet from './bitset.js'; - - import { mean, stddev } from "./stats.js"; - -When importing from a module that defines many exports, however, you can easily import everything with an import statement like this: - - import * as stats from "./stats.js"; - -With the wildcard import shown in the previous example, the importing module would use the imported `mean()` and` stddev()` functions through the stats object, invoking them as `stats.mean()` and `stats.stddev()`. - -Note: not finished. - -### The JavaScript Standard Library - -### The Set Class - -Sets are not ordered or indexed, and they do not allow duplicates. - - let s = new Set(); - - let t = new Set([1, s]); - - let t = new Set(s); - - let unique = new Set("Mississippi"); - -The argument to the `Set()` constructor need not be an array: any iterable object (including other Set objects) is allowed. - -The `add()` method takes a single argument; if you pass an array, it adds the array itself to the set, not the individual array elements. `add()` always returns the set it is invoked on, however, so if you want to add multiple values to a set, you can used chained method calls like. - -it is very important to understand that set membership is based on strict equality checks, like the === operator performs. - -The most important thing we do with sets is not to add and remove elements from them, but to check to see whether a specified value is a member of the set: - -`let oneDigitPrimes = new Set([2,3,5,7]);` - -`oneDigitPrimes.has(2)` - -The Set class is iterable, which means that you can use a `for/of` loop to enumerate all of the elements of a set: - - let sum = 0; - - for(let p of oneDigitPrimes) { - - sum += p; // and add them up - - } - -Because Set objects are iterable, you can convert them to arrays and argument lists with the … spread operator - -`[...oneDigitPrimes]` - -JavaScript Set class always remembers the order that elements were inserted in, and it always uses this order when you iterate a set: the first element inserted will be the first one iterated (assuming you haven't deleted it first), and the most recently inserted element will be the last one iterated. - -Set class also implements a `forEach()` method - - let product = 1; - - oneDigitPrimes.forEach(n => { product *= n; }); - -### The Map Class - - let m = new Map(); - - let n = new Map([["one", 1],["two", 2]]); - - let copy = new Map(n); - - let o = { x: 1, y: 2}; - - let p = new Map(Object.entries(o)); - -map is a set of keys, each of which has an associated value. This is not quite the same as a set of key/value pairs. - -use `has()` to check whether a map includes the specified key; use `delete()` to remove a key (and its associated value) from the map; use `clear()` to remove all key/value pairs from the map; and use the size property to find out how many keys a map contains. - -`set()` method of Map can be chained. - -Any JavaScript value can be used as a key or a value in a Map. This includes` null, undefined`, and `NaN`, as well as reference types like objects and arrays. - -Map compares keys by identity, not by equality. - -`let m = new Map();` - -`m.set({}, 1);` - -`m.set({}, 2);` - -Map a different empty object to the number 2. - -`m.get({})` - -undefined: - -`m.set(m, undefined);` - -`m.has(m)` - -true - -`m.get(m)` - -undefined - -Iterate over map: - -`let m = new Map([["x", 1], ["y", 2]]);` - -`[...m]` - -\[\["x", 1\], \["y", 2\]\] - -`for(let [key, value] of m) {...}` - -Map class iterates in insertion order - -If you want to iterate just the keys or just the associated values of a map, use the `keys()` and `values()` methods: these return iterable objects that iterate keys and values, in insertion order. (The - `entries()` method returns an iterable object that iterates key/value pairs, but this is exactly the same as iterating the map directly.) - - [...m.keys()] - - [...m.values()] - - [...m.entries()] - -Map objects can also be iterated using the `forEach()` - - m.forEach((value, key) => {...} - -Note that the value parameter comes before the key parameter. - -### WeakMap and WeakSet - -The `WeakMap `class is a variant (but not an actual subclass) of the Map class that does not prevent its key values from being garbage collected. - -`WeakMap `keys must be objects or arrays; primitive values are not subject to garbage collection and cannot be used as keys. - -WeakMap implements only the` get(), set(), has(),` and `delete()` methods. In particular, `WeakMap` is not iterable and does not define `keys(), values(),` or `forEach()`. If WeakMap was iterable, then its keys would be reachable and it wouldn't be weak. - -Similarly, WeakMap does not implement the size property because the `size` of a WeakMap could change at any time as objects are garbage collected - -### Typed Arrays and Binary Data - -They differ from regular arrays in some very important ways - -· The elements of a typed array are all numbers. Unlike regular JavaScript numbers, however, typed arrays allow you to specify the type (signed and unsigned integers and IEEE-754 floating point) and size (8 bits to 64 bits) of the numbers to be stored in the array. - -· You must specify the length of a typed array when you create it, and that length can never change. - -· The elements of a typed array are always initialized to 0 when the array is created. - - Int8Array() - - Uint8Array() - - Uint8ClampedArray() - - Int16Array() - - Uint32Array() - - Uint16Array() - - Int32Array() - - BigInt64Array() - - BigUint64Array() - - Float32Array() - - let bytes = new Uint8Array(1024); - - let matrix = new Float64Array(9); - - let sudoku = new Int8Array(81); - -Initialize with values - - let white = Uint8ClampedArray.of(255, 255, 255, 0); - - let ints = Uint32Array.from(white); - -one more way to create typed arrays that involves the `ArrayBuffer` type - - let buffer = new ArrayBuffer(1024*1024); - - buffer.byteLength - -1024\*1024 - -Typed arrays are not true arrays, but they re-implement most array methods, so you can use them pretty much just like you'd use regular arrays: - -`let ints = new Int16Array(10);` - -10 short integers - -`ints.fill(3).map(x=>x*x).join("")` - -"9999999999" - -Remember that typed arrays have fixed lengths, so the length property is read-only, and methods that change the length of the array (such as` push(), pop(), unshift(), shift(),` and `splice()`) are not implemented for typed arrays. Methods that alter the contents of an array without changing the length (such as `sort(), reverse()`, and `fill()`) are implemented. - -### Determine Endianess and DataView - - let littleEndian = new Int8Array(new Int32Array([1]).buffer) - - [0] === 1; - -You can use the `DataView` class, which defines methods for reading and writing values from an `ArrayBuffer` with explicitly specified byte ordering. Refer to book for more examples. - -### Pattern Matching with Regular Expressions - -RegExp objects may be created with the `RegExp()` constructor, of course, but they are more often created using a special literal syntax. - - let pattern = /s$/; - -←> - - let pattern = new RegExp("s$"); - -Regular expressions can also have one or more flag characters that affect how they work - - let pattern = /s$/i; - -i = case insensitive - -Punctuation characters have special meanings in regular expressions: `^ $ . * + ? = ! : | \ / ( ) [ ] { }. `Other punctuation characters, such as quotation marks and @, do not have special meaning and simply match themselves literally in a regular expression. - -If you use the `RegExp()` constructor, keep in mind that any backslashes in your regular expression need to be doubled, since strings also use backslashes as an escape character. - -**Character** - -**Matches** - -`[...]` - -Any one character between the brackets. - -`[^...]` - -Any one character not between the brackets - -`.` - -Any character except newline or another Unicode line terminator. Or, if the `RegExp` uses the s flag, then a period matches any character, including line terminators. - -`\w` - -Any ASCII word character. Equivalent to \[a-zA-Z0-9\_\]. - -`\W` - -Equivalent to \[^a-zA-Z0-9\_\] - -`\s` - -Any Unicode whitespace character. - -`\S` - -Any character that is not Unicode whitespace. - -`\d` - -Equivalent to \[0-9\]. - -`\D` - -Equivalent to \[⁰-9\]. - -`[\b]` - -A literal backspace (special case). - -`[\s\d]` - -Any one whitespace character or digit - -REPETITIONS - -**Character** - -**Meaning** - -`{n,m}` - -Match the previous item at least n times but no more than m times - -`{n,}` - -Match the previous item n or more times. - -`{n}` - -Match exactly n occurrences of the previous item. - -`?` - -Equivalent to {0,1}. - -`+` - -Equivalent to {1,} - -\* - -Equivalent to {0,}. - -**Example** - -**Description** - - let r = /\d{2,4}/; - -Match between two and four digits - - r = /\w{3}\d?/; - -Match exactly three word characters and an optional digit - - r = /\s+java\s+/; - -Match "java" with one or more spaces before and after - - r = /[^(]*/; - -Match zero or more characters that are not open parens - -If you want to match repetitions of more complicated expressions, you'll need to define a group with parentheses - -Be careful when using the \* and ? repetition characters. Since these characters may match zero instances of whatever precedes them, they are allowed to match nothing. - -### NON-GREEDY REPETITION - -It is also possible to specify that repetition should be done in a non-greedy way. Simply follow the repetition character or characters with a question mark: `??, +?, *?`, or even {1,5}?. - -**String** - -**Pattern** - -**Match** - - "aaa" - - /a+/ - - "aaa" - - "aaa" - - /a+?/ - - "a" - -Note that using non-greedy repetition may not always produce the results you expect. This is because regular expression pattern matching is done by findingthe first position in the string at which a match is possible. Since a match is possible starting at the first character of the string, shorter matches starting at subsequent characters are never even considered. - -### ALTERNATION, GROUPING, AND REFERENCES - -**Char** - -**Pattern** - -**Pattern** - -`|` - -`/ab|cd|ef/` - -"ab" or the string "cd" or the string "ef". - -`/\d{3}|[a-z]{4}/` - -either three digits or four lowercase letters. - -`/a|ab/` - -matches only the first letter "a" - -`()` - -`/java(script)?/` - -matches "java" followed by the optional "script" - -`/(ab|cd)+|ef/` - -matches "java" followed by the optional "script" - -If the left alternative matches, the right alternative is ignored, even if it would have produced a "better" match - -Another purpose of parentheses in regular expressions is to define subpatterns within the complete pattern. When a regular expression is successfully matched against a target string, it is possible to extract the portions of the target string that matched any particular parenthesized subpattern. For example, suppose you are looking for one or more lowercase letters followed by one or more digits. You might use the pattern `/[a-z]+\d+/`. But suppose you only really care about the digits at the end of each match. If you put that part of the pattern in parentheses (/\[a-z\]+(\\d+)/), you can extract the digits from any matches you find, - -A related use of parenthesized subexpressions is to allow you to refer back to a subexpression later in the same regular expression. This is done by following a \\ character by a digit or digits. The digits refer to the position of the parenthesized subexpression within the regular expression. For example, \\1 refers back to the first subexpression, and \\3 refers to the third. - -**Match** - -**Pattern** - -zero or more characters within single or double quotes. However, it does not - require the opening and closing quotes to match - - /['"][^'"]*['"]/ - -To require the quotes to match,use a reference - - /(['"])[^'"]*\1/ - -**Character** - -**Meaning** - -| - -match either the subexpression to the left or the subexpression to the right. - -(…) - -Grouping: group items into a single unit that can be used with \*, +, ?, |, and so on. Also remember the characters that match this group for use with later references - -(?:…) - -group items into a single unit, but do not remember the characters that match this group. - -Note` (?:...)` syntax: - -In pattern` "/([Jj]ava(?:[Ss]cript)?)\sis\s(fun\w*)/`" `\2` refers to the text matched by `(fun\w*)` since `(?:[Ss]cript)?)` in not remembered. - -### SPECIFYING MATCH POSITION - -_regular expression anchors_ because they anchor the pattern to a specific position in the search string. The most commonly used anchor elements are ^, which ties the pattern to the beginning of the string, and $, which anchors the pattern to the end of the string. - -**Example** - -**Pattern** - -match the word "JavaScript" on a line by itself - -`/^JavaScript$/` - -To search for "Java" as a word by itself you can try the pattern `/\sJava\s/`, which requires a space before and after the word. But there are two problems with this solution. First, it does not match "Java" at the beginning or the end of a string, but only if it appears with space on either side. Second, when this pattern does find a match, the matched string it returns has leading and trailing spaces, which is not quite what's needed. So instead of matching actual space characters with \\s, match (or anchor to) word boundaries with \\b. The resulting expression is `/\bJava\b/`. - -The element `\B` anchors the match to a location that is not a word boundary. Thus, the pattern `/\B[Ss]cript/` matches "JavaScript" and "postscript", but not "script" or "Scripting". - -You can also use arbitrary regular expressions as anchor conditions. - -If you include an expression within `(?= and )` characters, it is a lookahead assertion, and it specifies that the enclosed characters must match, without actually matching them. - -**Example** - -**Pattern** - -**Matches** - -to match the name of a common programming language, but only if it is followed by a colon - -`/[Jj]ava([Ss]cript)?(?=\:)/` - -matches the word "JavaScript" in "JavaScript: The DefinitiveGuide" - -does not match "Java" in "Java in a Nutshell" - -If you instead introduce an assertion with `(?!`, it is a negative lookahead assertion. - -### FLAGS - -Flags are specified after the second / character of a regular expression literal or as a string passed as the second argument to the RegExp() constructor. - -**Flag** - -**Meaning** - -g - -"global" — that is,that we intend to use it to find all matches within a string rather than just finding the first <a href="http://match.it/" class="markup--anchor markup--p-anchor">match.it</a> does alter the behavior of the String `match()` method and the `RegExp exec()` method in important ways. - -i - -case-insensitive - -m - -"multiline" mode - -s - -useful when working with text that includes newlines.Normally, a "." in a regular expression matches any character except a line terminator. When the s flag is used, however, "." will match any character, including line terminators. - -u - -Unicode. - -Setting the u flag on a RegExp also allows you to use the new `\u{...}` escape sequence for Unicode character and also enables the \\p{...} notation for Unicode character classes. - -y - -"sticky". should match at the beginning of a string or at the first character following the previous match - -### String Methods for Pattern Matching - -### SEARCH() - -Strings support four methods that use regular expressions. - -`"JavaScript".search(/script/ui)` - -4 - -`"Python".search(/script/ui)` - --1 - -`search()` does not support global searches; it ignores the `g` flag of its regular expression argument. - -REPLACE() - -`text.replace(/javascript/gi, "JavaScript");` - -No matter how it is capitalized, replace it with the correct capitalization - -parenthesized subexpressions of a regular expression are numbered from left to right and that the regular expression remembers the text that each subexpression matches. - -to replace quotation marks in a string with other characters: - -`let quote = /"([^"]*)"/g;` - -`'He said "stop"'.replace(quote, '«$1»')` - -'He said «stop»' - -If your RegExp uses named capture groups, then you can refer to the matching text by name rather than by number: - -`let quote = /"(?<quotedText>[^"]*)"/g;` - -`'He said "stop"'.replace(quote, '«$<quotedText>»')` - -'He said «stop»' - -Instead of passing a replacement string as the second argument to replace(), you can also pass a function that will be invoked to compute the replacement value. - -Example to convert decimal integers in a string to hexadecimal: - -`let s = "15 times 15 is 225";` - -`s.replace(/\d+/gu, n => parseInt(n).toString(16))` - -"f times f is e1" - -### MATCH() - -`"7 plus 8 equals 15".match(/\d+/g)` - -\["7", "8", "15"\] - -If the regular expression does not have the `g` flag set, `match()` does not do a global search; it simply searches for the first match. In this nonglobal case, `match()` still returns an array, but the array elements are completely different. - -Thus, if `match()` returns an array a, a\[0\] contains the complete match, a\[1\] contains the substring that matched the first parenthesized expression, and so on. - - let url = /(\w+):\/\/([\w.]+)\/(\S*)/; - - let text = "Visit my blog at http://www.example.com/~david"; - - let match = text.match(url); - - let fullurl, protocol, host, path; - - if (match !== null) { - - fullurl = match[0]; - -<a href="http://www.example.com/~david" class="markup--anchor markup--p-anchor">"http://www.example.com/~david</a>" - - protocol = match[1]; - -"http" - - host = match[2]; - -<a href="http://www.example.com/" class="markup--anchor markup--p-anchor">"www.example.com</a>" - - path = match[3]; - -"~david" - -In this non-global case, the array returned by match() also has some object properties in addition to the numbered array elements. - -input property refers to the string on which match() was called - -The index property is the position within that string at which the match starts. - -if the regular expression contains named capture groups, then the returned array also has a groups property whose value is an object. - -`let url = /(?<protocol>\w+):\/\/(?<host>[\w.]+)\/(?<path>\S*)/;` - -`let text = "Visit my blog at http://www.example.com/~david";` - -`let match = text.match(url);` - -`match[0]` - -<a href="http://www.example.com/~david" class="markup--anchor markup--p-anchor">"http://www.example.com/~david</a>" - -`match.input` - -text - -`match.index` - -17 - -`match.groups.protocol` - -"http" - -`match.groups.host` - -<a href="http://www.example.com/" class="markup--anchor markup--p-anchor">"www.example.com</a>" - -`match.groups.path` - -"~david" - -There are also important but less dramatic differences in behavior when the y flag is set. Refer to book for examples. - -### MATCHALL() - -Instead of returning an array of matching substrings like `match()` does, however, it returns an iterator that yields the kind of match objects that match() returns when used with a non-global RegExp. - -### SPLIT() - -`"123,456,789".split(",")` - -\["123", "456","789"\] - -`"1, 2, 3,\n4, 5".split(/\s*,\s*/)` - -\["1", "2", "3", "4","5"\] - -Surprisingly, if you call `split()` with a RegExp delimiter and the regular expression includes capturing groups, then the text that matches the capturing groups will be included in the returned array. - -`const htmlTag = /<([^>]+)>/;` - -`"Testing<br/>1,2,3".split(htmlTag)` - -\["Testing", "br/","1,2,3"\] - -### The RegExp Class - -The `RegExp()` constructor is useful when a regular expression is being dynamically created and thus cannot be represented with the regular expression literal syntax. - - let zipcode = new RegExp("\\d{5}", "g"); - -`let exactMatch = /JavaScript/;` - `let caseInsensitive = new RegExp(exactMatch, "i");` - -### TEST() - -Returns true or false by calling `exec()`. - -### EXEC() - - let pattern = /Java/g; - - let text = "JavaScript > Java"; - - let match; - - while((match = pattern.exec(text)) !== null) { - - console.log(`Matched ${match[0]} at ${match.index}`); - - console.log(`Next search begins at ${pattern.lastIndex}`); - - } - -### THE LASTINDEX PROPERTY AND REGEXP REUSE - -The use of the `lastIndex` property with the g and y flags is a particularly awkward part of this API. When you use these flags, you need to be particularly careful when calling the `match(), exec()`, or `test()` methods because the behavior of these methods depends on `lastIndex`, and the value of `lastIndex` depends on what you have previously done with the RegExp object. - -To find the index of all <p> tags within a string of HTML text: - - let match, positions = []; - - while((match = /<p>/g.exec(html)) !== null) { - - positions.push(match.index); - - } - -If the html string contains at least one <p> tag, then it will loop forever. For each iteration of the loop, we're creating a new RegExp object with `lastIndex` set to 0, so `exec()` always begins at the start of the string, and if there is a match, it will keep matching over and over. The solution, of course, is to define the RegExp once, and save it to a variable so that we're using the same RegExp object for each iteration of the loop. - -On the other hand, sometimes reusing a RegExp object is the wrong thing to do. Suppose, for example, that we want to loop through all of the words in a dictionary to find words that contain pairs of double letters. - - let dictionary = [ "apple", "book", "coffee" ]; - - let doubleLetterWords = []; - - let doubleLetter = /(\w)\1/g; - - for(let word of dictionary) { - - if (doubleLetter.test(word)) { - - doubleLetterWords.push(word); - - } - - } - -`doubleLetterWords` - -\["apple", "coffee"\]: "book" is missing! - -Because we set the g flag on the RegExp, the `lastIndex` property is changed after successful matches, and the `test()` method (which is based on `exec()`) starts searching for a match at the position specified by `lastIndex`. After matching the "pp" in "apple", `lastIndex` is 3, and so we start searching the word "book" at position 3 and do not see the "oo" that it contains. - -### Dates and Times - - let now = new Date(); - -The current time - - let epoch = new Date(0); - -Midnight, January 1st, 1970, GMT - - let century = new Date(2100, - - 0, - - 1, - - 2, 3, 4, 5); - -Year 2100 - -January - -1st - -02:03:04.005, local - - let century = new Date(Date.UTC(2100, 0, 1)); - -Midnight in GMT, January 1, 2100 - -If you print a date (with console.log(century), for example), it will, by default, be printed in your local time zone. If you want to display a date in UTC, you should explicitly convert it to a string with `toUTCString()` or` toISOString()`. - -if you pass a string to the Date() constructor, it will attempt to parse that string as a date and time specification - -`let century = new Date("2100-01-01T00:00:00Z");` - -Once you have a Date object, various get and set methods allow you to query and modify the year, month, day-of-month, hour, minute, second, and millisecond fields of the Date. Each of these methods hastwo forms: one that gets or sets using local time and one that gets or sets using UTC time. - -Note that the methods for querying the day-of-month are `getDate()` and `getUTCDate()`. The more natural-sounding functions `getDay()` and `getUTCDay()` return the day-of-week (0 for Sunday through 6 for Saturday). The day-of-week is read-only, so there is not a corresponding `setDay()` method. - -### Timestamps - -JavaScript represents dates internally as integers that specify the number of milliseconds since (or before) midnight on January 1, 1970, UTC time. - -For any Date object, the `getTime()` method returns this internal value, and the `setTime()` method sets it. - - d.setTime(d.getTime() + 30000); - -add 30 secs - -The static Date.now() method returns the current time as a timestamp and is helpful when you want to measure how long your code takes to run - - let startTime = Date.now(); - - reticulateSplines(); // Do some time-consuming operation - - let endTime = Date.now(); - - console.log(`Spline reticulation took ${endTime -startTime}ms.`); - -adds three months and two weeks to the current date: - -`let d = new Date();` - `d.setMonth(d.getMonth() + 3, d.getDate() + 14);` - -### Formatting and Parsing Date Strings - - let d = new Date(2020, 0, 1, 17, 10, 30); - - d.toString() - -"Wed Jan 01 2020 17:10:30 GMT-0800 (Pacific Standard Time)" - - d.toUTCString() - -"Thu, 02 Jan 2020 01:10:30 GMT" - - d.toLocaleDateString() - -"1/1/2020": 'en-US' locale - - d.toLocaleTimeString() - -"5:10:30 PM": 'en-US' locale - - d.toISOString() - -"2020-01-02T01:10:30.000Z" - -there is also a static Date.parse() method that takes a string as its argument, attempts to parse it as a date and time, and returns a timestamp representing that date. `Date.parse()` is able to parse the same strings that the `Date()` constructor can and is guaranteed to be able to parse the output of` toISOString(), toUTCString()`, and` toString()`. - -### Error Classes - -One good reason to use an Error object is that, when you create an Error, it captures the state of the JavaScript stack, and if the exception is uncaught, the stack trace will be displayed with the error message, which will help you debug the issue. - -Error objects have two properties: `message` and `name`, and a` toString()` method. Node and all modern browsers also define a `stack` property on Error objects. - -Subclasses are `EvalError, RangeError, ReferenceError, SyntaxError, TypeError,` and `URIError`. - -You should feel free to define your own Error subclasses that best encapsulate the error conditions of your own program. - - class HTTPError extends Error { - - constructor(status, statusText, url) { - - super(`${status} ${statusText}: ${url}`); - - this.status = status; - - this.statusText = statusText; - - this.url = url; - - } - - get name() { return "HTTPError"; } - - } - - let error = new HTTPError(404, "Not Found", "http://example.com/"); - - error.status - -404 - - error.message - -"404 Not Found:<a href="http://example.com/" class="markup--anchor markup--p-anchor">http://example.com/</a>" - - error.name - -HTTPError - -### JSON Serialization and Parsing - -JavaScript supports JSON serialization and deserialization with the two functions `JSON.stringify()` and `JSON.parse().` - - let o = {s: "", n: 0, a: [true, false, null]}; - - let s = JSON.stringify(o); - -s == '{"s":"","n":0,"a":\[true,false,null\]}' - - let copy = JSON.parse(s); - -copy == {s: "", n: 0, a:\[true, false, null\]} - -Inefficient way of creating a deep copy of an object - - function deepcopy(o) { - - return JSON.parse(JSON.stringify(o)); - - } - -Typically, you pass only a single argument to `JSON.stringify()` and `JSON.parse()`. Both functions accept an optional second argument that allows us to extend the JSON format. - -`JSON.stringify()` also takes an optional third argument. If you would like your JSONformatted string to be human-readable (if it is being used as a configuration file, for example), then you should pass null as the second argument and pass a number or string as the third argument. If the third argument is a number, then it will use that number of spaces for each indentation level. If the third argument is a string of whitespace (such as '\\t'), it will use that string for each level of indent. - -### JSON Customizations - -If `JSON.stringify()` is asked to serialize a value that is not natively supported by the JSON format, it looks to see if that value has a `toJSON()` method, and if so, it calls that method and then stringifies the return value in place of the original value. Date objects implement `toJSON()`: it returns the same string that `toISOString()` method does. - -If you need to re-create Date objects (or modify the parsed object inany other way), you can pass a "reviver" function as the second argument to `JSON.parse()`. - - let data = JSON.parse(text, function(key, value) { - - if (key[0] === "_") return undefined; - - if (typeof value === "string" && /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ$/.test(value)) { - - return new Date(value); - - } - - return value; - - }); - -### The Console API - -Console functions that print their arguments like console.log() have a little-known feature: if the first argument is a string that includes `%s, %i, %d, %f, %o, %O, or %c`, then this first argument is treated as format string, and the values of subsequent arguments are substituted into the string in place of the two-character % sequences. - -### URL API - - let url = new URL("https://example.com:8000/path/name?q=term#fragment"); - - url.href - -<a href="https://example.com:8000/path/name" class="markup--anchor markup--p-anchor">"https://example.com:8000/path/name</a>?q=term\#fragment" - - url.origin - -<a href="https://example.com:8000/" class="markup--anchor markup--p-anchor">"https://example.com:8000</a>" - - url.protocol - -"https:" - - url.host - -<a href="http://example.com/" class="markup--anchor markup--p-anchor">"example.com</a>:8000" - - url.hostname - -<a href="http://example.com/" class="markup--anchor markup--p-anchor">"example.com</a>" - - url.port - -"8000" - - url.pathname - -"/path/name" - - url.search - -"?q=term" - - url.hash - -"\#fragment" - - let url = new URL("https://example.com"); - - url.pathname = "api/search"; - -Add a path to an API endpoint - - url.search = "q=test"; - -Add a query parameter - - url.toString() - -<a href="https://example.com/api/search?q=test" class="markup--anchor markup--p-anchor">"https://example.com/api/search?q=test</a>" - -One of the important features of the URL class is that it correctly adds punctuation and escapes special characters in URLs when that is needed - - let url = new URL("https://example.com"); - - url.pathname = "path with spaces"; - - url.pathname - -"/path%20with%20spaces" - - url.search = "q=foo#bar"; - - url.search - -"?q=foo%23bar" - - url.href - -<a href="https://example.com/path%20with%20spaces?q=foo%23bar" class="markup--anchor markup--p-anchor">"https://example.com/path%20with%20spaces?q=foo%23bar</a>" - -Often, however, HTTP requests encode the values of multiple form fields or multiple API parameters into the query portion of a URL. In this format, the query portion of the URL is a question mark followed by one or more name/value pairs, which are separated from one another by ampersands. - -If you want to encode these kinds of name/value pairs into the query portion of a URL, then the searchParams property will be more useful than the search property. - -`let url = new URL("https://example.com/search");` - -`url.search` - -"" - -`url.searchParams.append("q", "term");` - -`url.search` - -"?q=term" - -`url.searchParams.set("q", "x");` - -`url.search` - -"?q=x" - -`url.searchParams.append("opts", "1");` - -`url.search` - -"?q=x&opts=1" - -The value of the searchParams property is a URLSearchParams object. - -`let url = new URL("http://example.com");` - -`let params = new URLSearchParams();` - -`params.append("q", "term");` - -`params.append("opts", "exact");` - -`params.toString()` - -"q=term&opts=exact" - -`url.search = params;` - -`url.href` - -<a href="http://example.com/" class="markup--anchor markup--p-anchor">"http://example.com/</a>?q=term&opts=exact" - -### Timers - -`setTimeout()` and` setInterval()`—that allow programs to ask the browser to invoke a function after a specified amount of time has elapsed or to invoke the function repeatedly at a specified interval. - - setTimeout(() => { console.log("Ready..."); }, 1000); - - setTimeout(() => { console.log("set..."); }, 2000); - - setTimeout(() => { console.log("go!"); }, 3000); - -If you want to invoke a function repeatedly, use `setInterval()` - -Both `setTimeout()` and `setInterval()` return a value. If you save this value in a variable, you can then use it later to cancel the execution of the function by passing it to `clearTimeout()` or `clearInterval()`. - - let clock = setInterval(() => { - - console.clear(); - - console.log(new Date().toLocaleTimeString()); - - }, 1000); - - setTimeout(() => { clearInterval(clock); }, 10000); - -After 10 seconds: stop the repeating code above - -### Iterators and Generators - -The iterator method of an iterable object does not have a conventional name but uses the Symbol, Symbol.iterator as its name. So a simple for/of loop over an iterable object iterable could also be written the hard way, like this: - - let iterable = [99]; - - let iterator = iterable[Symbol.iterator](); - - for(let result = iterator.next(); !result.done; result =iterator.next()) { - - console.log(result.value) // result.value == 99 - - } - -When you want to iterate though a "partially used" iterator: - -`let list = [1,2,3,4,5];` - `let iter = list[Symbol.iterator]();` - -`let head = iter.next().value;` - -head == 1 - -`let tail = [...iter];` - -tail == \[2,3,4,5\] - -### Implementing Iterable Objects - -we will implement the Range class one more time, making it iterable without relying on a generator. - -In order to make a class iterable, you must implement a method whose name is the Symbol `Symbol.iterator` - - class Range { - - constructor (from, to) { - - this.from = from; - - this.to = to; - - } - - has(x) { return typeof x === "number" && this.from <= x && x <= this.to; } - - toString() { return `{ x | ${this.from} ≤ x ≤ ${this.to}}`; } - - [Symbol.iterator]() { - - let next = Math.ceil(this.from); - - let last = this.to; - - return { - - next() { - - return (next <= last) ? { value: next++ } : { done: true }; - - }, - - [Symbol.iterator]() { return this; } - - }; - - } - - } - - for(let x of new Range(1,10)) console.log(x); - -Logs numbers 1 to 10 - - [...new Range(-2,2)] - -\[-2, -1, 0,1, 2\] - -In addition to making your classes iterable, it can be quite useful to define functions that return iterable values. - -Return an iterable object that iterates the result of applying `f()` to each value from the source iterable - - function map(iterable, f) { - - let iterator = iterable[Symbol.iterator](); - - return { - - [Symbol.iterator]() { return this; }, - - next() { - - let v = iterator.next(); - - if (v.done) { - - return v; - - } - - else { - - return { value: f(v.value) }; - - } - - } - - }; - - } - -`[...map(new Range(1,4), x => x*x)]` - -\[1, 4, 9, 16\] - -Return an iterable object that filters the specified iterable, iterating only those elements for which the predicate returns true - - function filter(iterable, predicate) { - - let iterator = iterable[Symbol.iterator](); - - return { - - [Symbol.iterator]() { return this; }, - - next() { - - for(;;) { - - let v = iterator.next(); - - if (v.done || predicate(v.value)) { - - return v; - - } - - } - - } - - }; - - } - -`[...filter(new Range(1,10), x => x % 2 === 0)]` - -\[2,4,6,8,10\] - -### Generators - -Particularly useful when the values to be iterated are not the elements of a data structure, but the result of a computation. - -To create a generator, you must first define a generator function — defined with the keyword `function*` rather than `function` - -When you invoke a generator function, it does not actually execute the function body, but instead returns a generator object. This generator object is an iterator. - -Calling its `next()` method causes the body of the generator function to run from the start (or whatever its current position is) until it reaches a `yield` statement. - -The value of the `yield` statement becomes the value returned by the `next()` call on the iterator. - - function* oneDigitPrimes() { - - yield 2; - - yield 3; - - yield 5; - - yield 7; - - } - - let primes = oneDigitPrimes(); - -we get a generator - - primes.next().value - -2 - - primes.next().value - -3 - - primes.next().value - -5 - - primes.next().value - -7 - - primes.next().done - -true - -Generators have a `Symbol.iterator` method to make them iterable - -`primes[Symbol.iterator]()` - -`[...oneDigitPrimes()]` - -\[2,3,5,7\] - - let sum = 0; - - for(let prime of oneDigitPrimes()) sum += prime; - - sum - -17 - -Like regular functions, however, we can also define generators in expression form. - - const seq = function*(from,to) { - - for(let i = from; i <= to; i++) yield i; - - }; - - [...seq(3,5)] - -\[3, 4, 5\] - -In classes and object literals, we can use shorthand notation to omit the function keyword entirely when we define methods. - - let o = { - - x: 1, y: 2, z: 3, - - *g() { - - for(let key of Object.keys(this)) { - - yield key; - - } - - } - - }; - -`[...o.g()]` - -\["x", "y", "z", "g"\] - -Generators often make it particularly easy to define iterable classes. - - *[Symbol.iterator]() { - - for(let x = Math.ceil(this.from); x <= this.to; x++) - - yield x; - - } - -### Generator Examples - -Generators are more interesting if they actually generate the values they yield by doing some kind of computation. - -generator function that yields Fibonacci numbers - - function* fibonacciSequence() { - - let x = 0, y = 1; - - for(;;) { - - yield y; - - [x, y] = [y, x+y]; - - } - - } - -If this generator is used with the … spread operator, it will loop until memory is exhausted and the program crashes. - -Use it in a `for/of` loop, however - - function fibonacci(n) { - - for(let f of fibonacciSequence()) { - - if (n-- <= 0) return f; - - } - - } - - fibonacci(20) - -10946 - -This kind of infinite generator becomes more useful with a `take()` generator like this - - function* take(n, iterable) { - - let it = iterable[Symbol.iterator](); - - while(n-- > 0) { - - let next = it.next(); - - if (next.done) return; - - else yield next.value; - - } - - } - - [...take(5, fibonacciSequence())] - -\[1, 1, 2, 3, 5\] - -### Asynchronous Javascript - -`Promises`, new in ES6, are objects that represent the not-yet-available result of an asynchronous operation. - -The keywords `async` and `await` were introduced in ES2017 and provide new syntax that simplifies asynchronous programming by allowing you to structure your Promise based code as if it was synchronous. - -Asynchronous iterators and the` for/await` loop were introduced in ES2018 and allow you to work with streams of asynchronous events using simple loops that appear synchronous. - -### Asynchronous Programming with Callbacks - -### Timers - -`setTimeout(checkForUpdates, 60000);` - - let updateIntervalId = setInterval(checkForUpdates, 60000); - - function stopCheckingForUpdates() { - - clearInterval(updateIntervalId); - - } - -### Events - -Event-driven JavaScript programs register callback functions for specified types of events in specified contexts, and the web browser invokes those functions whenever the specified events occur. - -These callback functions are called event handlers or event listeners, and they are registered with `addEventListener()` - -Ask the web browser to return an object representing the HTML <button> element that matches this CSS selector: - -`let okay = document.querySelector('#confirmUpdateDialogbutton.okay');` - -Now register a callback function to be invoked when the user clicks on that button - -`okay.addEventListener('click', applyUpdate);` - -### Network Events - -JavaScript running in the browser can fetch data from a web server with code like this: - - function getCurrentVersionNumber(versionCallback) { - - let request = new XMLHttpRequest(); - - request.open("GET", "http://www.example.com/api/version"); - - request.send(); - - request.onload = function() { - - if (request.status === 200) { - - let currentVersion = parseFloat(request.responseText); - - versionCallback(null, currentVersion); - - } - - else { - - versionCallback(response.statusText, null); - - } - - }; - - request.onerror = request.ontimeout = function(e) { - - versionCallback(e.type, null); - - }; - - } - -### Promises - -Promises, a core language feature designed to simplify asynchronous programming. - -A Promise is an object that represents the result of an asynchronous computation. That result may or may not be ready yet, and the Promise API is intentionally vague about this: there is no way to synchronously get the value of a Promise; you can only ask the Promise to call a callback function when the value is ready. - -One real problem with callback-based asynchronous programming is that it is common to end up with callbacks inside callbacks inside callbacks, with lines of code so highly indented that it is difficult to read. - -Promises allow this kind of nested callback to be re-expressed as a more linear Promise chain that tends to be easier to read and easier to reason about. - -Another problem with callbacks is that they can make handling errors difficult. If an asynchronous function (or an asynchronously invoked callback) throws an exception, there is no way for that exception to propagate back to the initiator of the asynchronous operation. This is a fundamental fact about asynchronous programming: it breaks exception handling. Promises help here by standardizing a way to handle errors and providing a way for errors to propagate correctly through a chain of promises. - -Note that Promises represent the future results of single asynchronous computations. They cannot be used to represent repeated asynchronous computations, however. - -We can't use Promises to replace `setInterval()` because that function invokes a callback function repeatedly, which is something that Promises are just not designed to do. - -### Using Promises - -How we would use this Promise returning utility function - - getJSON(url).then(jsonData => { - - // callback function that will be asynchronously invoked with the parsed JSON value when it becomes available. - - }); - -The Promise object defines a then() instance method. Instead of passing our callback function directly to `getJSON()`, we instead pass it to the then() method. When the HTTP response arrives, the body of that response is parsed as JSON, and the resulting parsed value is passed to the function that we passed to `then()`. - -If you call the `then()` method of a Promise object multiple times, each of the functions you specify will be called when the promised computation is complete. - -Unlike many event listeners, though, a Promise represents a single computation, and each function registered with then() will be invoked only once. - - function displayUserProfile(profile) { ...} - - getJSON("/api/user/profile").then(displayUserProfile); - -### HANDLING ERRORS WITH PROMISES - -Asynchronous operations, particularly those that involve networking, can typically fail in a number of ways, and robust code has to be written to handle the errors that will inevitably occur. - -`getJSON("/api/user/profile").then(displayUserProfile, handleProfileError);` - -if `getJSON()` runs normally, it passes its result to `displayUserProfile()`. If there is an error (the user is not logged in, the server is down, the user's internet connection dropped, the request timed out, etc.), then `getJSON()` passes an Error object to `handleProfileError()`. - -In practice, it is rare to see two functions passed to then(). There is a better and more idiomatic way of handling errors when working with Promises. - -To understand it, first consider what happens if `getJSON()` completes normally but an error occurs in `displayUserProfile()`. That callback function is invoked asynchronously when `getJSON()` returns, so it is also asynchronous and cannot meaningfully throw an exception (because there is no code on the call stack to handle it). - - getJSON("/api/user/profile").then(displayUserProfile).catch(handleProfileError); - -With this code, a normal result from` getJSON()` is still passed to `displayUserProfile()`, but any error in `getJSON()` or in `displayUserProfile()` (including any exceptions thrown by `displayUserProfile`) get passed to `handleProfileError()`. - -### Chaining Promises - -One of the most important benefits of Promises is that they provide a natural way to express a sequence of asynchronous operations as a linear chain of `then()` method invocations, without having to nest each operation within the callback of the previous one. - - fetch(documentURL) - - .then(response => response.json()) - - .then(document => {return render(document); }) - - .then(rendered => {cacheInDatabase(rendered); }) - - .catch(error => handle(error)); - -has largely been replaced by the newer, Promise-based Fetch API. In its simplest form, this new HTTP API is just the function fetch(). That promise is fulfilled when the HTTP response begins to arrive and the HTTP status and headers are available. - - fetch("/api/user/profile") - - .then(response => { - - if (response.ok && response.headers.get("Content-Type") === "application/json") { - - // What can we do here? We don't actually have the response body yet. - - } - - }); - -But although the initial Promise is fulfilled, the body of the response may not yet have arrived. So these `text()` and` json()` methods for accessing the body of the response themselves return Promises. - - fetch("/api/user/profile") - - .then(response => { - - return response.json(); - - }) - - .then(profile => { - - displayUserProfile(profile); - - }); - -There is a second `then()` in the chain, which means that the first invocation of the `then()` method must itself return a Promise. That is not how Promises work, however. - -When we write a chain of `.then()` invocations, we are not registering multiple callbacks on a single Promise object. Instead, each invocation of the `then()` method returns a new Promise object. That new Promise object is not fulfilled until the function passed to `then()` is complete. - - fetch(theURL) // task 1; returns promise 1 - - .then(callback1) // task 2; returns promise 2 - - .then(callback2); // task 3; returns promise 3 - -### Resolving Promises - -There is actually a fourth Promise object involved as which brings up the point of what it means for a Promise to be "resolved." - -fetch() returns a Promise object which, when fulfilled, passes a Response object to the callback function we register. This Response object has `.text(), .json(),` and other methods to request the body of the HTTP response in various forms. But since the body may not yet have arrived, these methods must return Promise objects. - -"task 2" calls the `.json()` method and returns its value. This is the fourth Promise object, and it is the return value of the `callback1()` function. - -Let's consider: - - function c1(response) { - - let p4 = response.json(); - - return p4; - - } - - // callback 1 - - // returns promise 4 - - function c2(profile) { - - displayUserProfile(profile); - - } - - // callback 2 - - let p1 = fetch("/api/user/profile"); - - promise 1, task 1 - - let p2 = p1.then(c1); - - promise 2, task 2 - - let p3 = p2.then(c2); - - promise 3, task 3 - -In order for Promise chains to work usefully, the output of task 2 must become the input to task 3. The input to task 3 is the body of the URL that was fetched, parsed as a JSON object. But the return value of callback c1 is not a JSON object, but Promise p4 for that JSON object. - -When p1 is fulfilled, c1 is invoked, and task 2 begins. And when p2 is fulfilled, c2 is invoked, and task 3 begins. - -And when p2 is fulfilled, c2 is invoked, and task 3 begins. But just because task 2 begins when c1 is invoked,it does not mean that task 2 must end when c1 returns. - -Promises are about managing asynchronous tasks, and if task 2 is asynchronous, then that task will not be complete by the time the callback returns. - -When you pass a callback c to the `then()` method, `then()` returns a Promise p and arranges to asynchronously invoke c at some later time. The callback performs some computation and returns a value v. When the callback returns, p is resolved with the value v. When a Promise is resolved with a value that is not itself a Promise, it is immediately fulfilled with that value. - -So if c returns a non-Promise, that return value becomes the value of p, p is fulfilled and we are done. But if the return value v is itself a Promise, then p is resolved but not yet fulfilled. - -At this stage, p cannot settle until the Promise v settles. If v is fulfilled, then p will be fulfilled to the same value. If v is rejected, then p will be rejected for the same reason. This is what the "resolved" state of a Promise means - -the Promise has become associated with, or "locked onto," another Promise. We don't know yet whether p will be fulfilled or rejected, but our callback c no longer has any control over that. p is "resolved" in the sense that its fate now depends entirely on what happens to Promise v. - -Let's bring this back to our URL-fetching example. When c1 returns p4, p2 is resolved. But being resolved is not the same as being fulfilled, so task 3 does not begin yet. When the full body of the HTTP response becomes available, then the .`json()` method can parse it and use that parsed value to fulfill p4. When p4 is fulfilled, p2 is automatically fulfilled as well, with the same parsed JSON value. At this point, the parsed JSON object is passed to c2, and task 3 begins. - -### More on Promises and Errors - -With synchronous code, if you leave out error-handling code, you'll at least get an exception and a stack trace that you can use to figure out what is going wrong. With asynchronous code, unhandled exceptions will often go unreported, and errors can occur silently, making them much harder to debug. The good news is that the `.catch()` method makes it easy to handle errors when working with Promises. - -THE CATCH AND FINALLY METHODS - -The `.catch()` method of a Promise is simply a shorthand way to call `.then()` with null as the first argument and an error-handling callback as the second argument. - -Normal exceptions don't work with asynchronous code. The `.catch()` method of Promises is an alternative that does work for asynchronous code. - - fetch("/api/user/profile") - - .then(response => { - - if (!response.ok) { - - return null; - - } - - let type = response.headers.get("content-type"); - - if (type !== "application/json") { - - throw new TypeError(`Expected JSON, got ${type}`); - - } - - return response.json(); - - }) - - .then(profile => { - - if (profile) { - - displayUserProfile(profile); - - } - - else { - - displayLoggedOutProfilePage(); - - } - - }) - - .catch(e => { - - if (e instanceof NetworkError) { - - displayErrorMessage("Check your internet connection."); - - } - - else if (e instanceof TypeError) { - - displayErrorMessage("Something is wrong with our server!"); - - } - - else { - - console.error(e); - - } - - }); - -p1 is the Promise returned by the `fetch()` call - -p2 is the Promise returned by the first `.then()` call - -c1 is the callback that we pass to that .`then()` call - -p3 is the Promise returned by the second `.then()` call - -c2 is the callback we pass to that call - -c3 is the callback that we pass to the `.catch()` call - -The first thing that could fail is the fetch() request itself. Let's say p1 was rejected with a NetworkError object. - -We didn't pass an error-handling callback function as the second argument to the `.then()` call, so p2 rejects as well with the same NetworkError object. - -Without a handler, though, p2 is rejected, and then p3 is rejected for the same reason. - -At this point, the c3 error-handling callback is called, and the NetworkError-specific code within it runs. - -There are a couple of things worth noting about this code. First, notice that the error object thrown with a regular, synchronous throw statement ends up being handled asynchronously with a `.catch()` method invocation in a Promise chain. This should make it clear why this shorthand method is preferred over passing a second argument to .`then()`, and also why it is so idiomatic to end Promise chains with a `.catch()` call. - -it is also perfectly valid to use `.catch()` elsewhere in a Promise chain. If one of the stages in your Promise chain can fail with an error, and if the error is some kind of recoverable error that should not stop the rest of the chain from running, then you can insert a `.catch()` call in the chain, resulting in code that might look like this: - - startAsyncOperation() - - .then(doStageTwo) - - .catch(recoverFromStageTwoError) - - .then(doStageThree) - - .then(doStageFour) - - .catch(logStageThreeAndFourErrors); - -If the callback returns normally, then the `.catch()` callback will be skipped, and the return value of the previous callback will become the input to the next .`then()` callback. - -Once an error has been passed to a `.catch()` callback, it stops propagating down the Promise chain. A `.catch()` callback can throw a new error, but if it returns normally, than that return value is used to resolve and/or fulfill the associated Promise, and - the error stops propagating. - -Sometimes, in complex network environments, errors can occur more or less at random, and it can be appropriate to handle those errors by simply retrying the asynchronous request. - - queryDatabase() - - .catch(e => wait(500).then(queryDatabase)) - - .then(displayTable) - - .catch(displayDatabaseError); - -### Promises in Parallel - -Sometimes,we want to execute a number of asynchronous operations in parallel. The function `Promise.all()` can do this. `Promise.all()` takes an array of Promise objects as its input and returns a Promise. - -The returned Promise will be rejected if any of the input Promises are rejected. Otherwise, it will be fulfilled with an array of the fulfillment values of each of the input Promises. - - const urls = [ /* zero or more URLs here */ ]; - - promises = urls.map(url => fetch(url).then(r => r.text())); - - Promise.all(promises) - - .then(bodies => { /* do something with the array of strings */ }) - - .catch(e => console.error(e)); - -The Promise returned by `Promise.all()` rejects when any of the input Promises is rejected. This happens immediately upon the first rejection and can happen while other input Promises are still pending. In ES2020, `Promise.allSettled()` takes an array of input - Promises and returns a Promise, just like Promise.all() does. But `Promise.allSettled()` never rejects the returned Promise, and it does not fulfill that Promise until all of the input Promises have settled. The Promise resolves to an array of objects, with one object for each input Promise. Each of these returned objects has a status property set to "fulfilled" or "rejected." If the status is "fulfilled", then the object will also have a value property that gives the fulfillment value. And if the status is "rejected", then the object will also have a reason property that gives the error or rejection value of the corresponding Promise. - - Promise.allSettled([Promise.resolve(1), Promise.reject(2),3]).then(results => { - - results[0] // => { status: "fulfilled", value: 1 } - - results[1] // => { status: "rejected", reason: 2 } - - results[2] // => { status: "fulfilled", value: 3 } - - }); - -Occasionally, you may want to run a number of Promises at once but may only care about the value of the first one to fulfill. In that case, you can use `Promise.race()` instead of `Promise.all()`. It returns a Promise that is fulfilled or rejected when the first of the Promises in the input array is fulfilled or rejected. - -### Making Promises - -### Promises in Sequence - -### async and await - -These new keywords dramatically simplify the use of Promises and allow us to write Promise-based, asynchronous code that looks like synchronous code that blocks while waiting for network responses or other asynchronous events. - -Asynchronous code can't return a value or throw an exception the way that regular synchronous code can. And this is why Promises are designed the way the are. The value of a fulfilled Promise is like the return value of a synchronous function. And the value of a rejected Promise is like a value thrown by a synchronous function. - -`async` and `await` take efficient, Promise-based code and hide the Promises so that your asynchronous code can be as easy to read and as easy to reason about as inefficient, blocking, synchronous code. - -Given a Promise object p, the expression await p waits until p settles. If p fulfills, then the value of await p is the fulfillment value of p. On the other hand, if p is rejected, then the await p expression throws the rejection value of p. - - let response = await fetch("/api/user/profile"); - - let profile = await response.json(); - -It is critical to understand right away that the `await` keyword does not cause your program to block and literally do nothing until the specified Promise settles. The code remains asynchronous, and the `await` simply disguises this fact. This means that any code that uses await is itself asynchronous. - -### async Functions - -Because any code that uses await is asynchronous, there is one critical rule: you can only use the await keyword within functions that have been declared with the `async` keyword. - - async function getHighScore() { - - let response = await fetch("/api/user/profile"); - - let profile = await response.json(); - - return profile.highScore; - - } - -Declaring a function `async` means that the return value of the function will be a Promise even if no Promise-related code appears in the body of the function. - -The `getHighScore()` function is declared `async`, so it returns a Promise. And because it returns a Promise, we can use the `await` keyword with it: - - displayHighScore(await getHighScore()); - -### Awaiting Multiple Promises - -Suppose that we've written our `getJSON()` function using async: - - async function getJSON(url) { - - let response = await fetch(url); - - let body = await response.json(); - - return body; - - } - -And now suppose that we want to fetch two JSON values with this function - - let value1 = await getJSON(url1); - - let value2 = await getJSON(url2); - -The problem with this code is that it is unnecessarily sequential: the fetch of the second URL will not begin until the first fetch is complete. If the second URL does not depend on the value obtained from the firstURL, then we should probably try to fetch the two values at the same time. - - let [value1, value2] = await Promise.all([getJSON(url1), getJSON(url2)]); - -### The for/await Loop - -Suppose you have an array of URLs: - - const urls = [url1, url2, url3]; - -You can call fetch() on each URL to get an array of Promises: - - const promises = urls.map(url => fetch(url)); - -We could now use` Promise.all()` to wait for all the Promises in the array to be fulfilled. But suppose we want the results of the first fetch as soon as they become available and don't want to wait for all the URLs to be fetched. - - for(const promise of promises) { - - response = await promise; - - handle(response); - - } - -←> - - for await (const response of promises) { - - handle(response); - - } - -both examples will only work if they are within functions declared async; a `for/await` loop is no different than a regular await expression in that way - -#### If you found this guide helpful feel free to checkout my GitHub/gist's where I host similar content: - -<a href="https://gist.github.com/bgoonz" class="markup--anchor markup--p-anchor"><strong>bgoonz's</strong> gists · GitHub</a> - -<a href="https://github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://github.com/bgoonz"><strong>bgoonz — Overview</strong> -<br/> - -<em>Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…</em>github.com</a><a href="https://github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -Or checkout my personal resource site: - -<a href="https://goofy-euclid-1cd736.netlify.app/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://goofy-euclid-1cd736.netlify.app/"><strong>a/A-Student-Resources</strong> -<br/> - -<em>Edit description</em>goofy-euclid-1cd736.netlify.app</a><a href="https://goofy-euclid-1cd736.netlify.app/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [March 8, 2021](https://medium.com/p/64306cd6b0db). - -<a href="https://medium.com/@bryanguner/complete-javascript-reference-guide-64306cd6b0db" class="p-canonical">Canonical link</a> - -August 6, 2021. diff --git a/notes/articles/medium/markdown/The-ExpressJS-Way-To-Write-APIs.md b/notes/articles/medium/markdown/The-ExpressJS-Way-To-Write-APIs.md deleted file mode 100644 index e29b2e84e4..0000000000 --- a/notes/articles/medium/markdown/The-ExpressJS-Way-To-Write-APIs.md +++ /dev/null @@ -1,803 +0,0 @@ -# The ExpressJS Way To Write APIs - -This article will cover the basics of express from the perspective of a beginner without concerning its self with the underlying mechanisms… - ---- - -### The ExpressJS Way To Write APIs - -#### This article will cover the basics of express from the perspective of a beginner without concerning its self with the underlying mechanisms and theory that underlies the application of the framework. - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*yUozFGA0FQpjcXFf.gif" class="graf-image" /></figure>### For starters, what is express JS¿ - -When introduced, node.js gave developers the chance to use JavaScript to write software that, up to that point, could only be written using lower level languages like C, C++, Java, Python… - -This tutorial will cover how to write **web services** that can communicate with clients (the front end application) using **J**ava**S**cript **O**bject **N**otation (JSON). - -- <span id="5334">JavaScript is asynchronous, which allows us to take full advantage of the processor it's running on. Taking full advantage of the processor is crucial because the node process will be running on a single CPU.</span> -- <span id="0b8b">Using JavaScript gives us access to the npm repository. This repository is the largest ecosystem of useful libraries (most of them free to use) in **npm modules**.</span> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*PTKhCN2p9S8EDZ4r.gif" class="graf-image" /></figure> - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Explain what Node.js is and its core features - -<span class="graf-dropCap">T</span>raditionally, developers only used the JavaScript language in web browsers. But, in 2009, **Node.js** was unveiled, and with it, the developer tool kit expanded greatly. Node.js gave developers the chance to use JavaScript to write software that, up to that point, could only be written using C, C++, Java, Python, Ruby, C\#, and the like. - -We will use Node to write server code. Specifically, **web services** that can communicate with clients using the **J**ava**S**cript **O**bject **N**otation (JSON) format for data interchange. - -Some of the advantages of using Node.js for writing server-side code are: - -- <span id="51f9">Uses the same programming language (JavaScript) and paradigm for both client and server. Using the same language, we minimize context switching and make it easy to share code between the client and the server.</span> -- <span id="ad6f">JavaScript is single-threaded, which removes the complexity involved in handling multiple threads.</span> -- <span id="c797">JavaScript is asynchronous, which allows us to take full advantage of the processor it's running on. Taking full advantage of the processor is crucial because the node process will be running on a single CPU.</span> -- <span id="7654">Using JavaScript gives us access to the npm repository. This repository is the largest ecosystem of useful libraries (most of them free to use) in **npm modules**.</span> - -Some of the disadvantages of using Node.js for writing server-side code are: - -- <span id="0f56">By strictly using JavaScript on the server, we lose the ability to use the right tool (a particular language) for the job.</span> -- <span id="cd1e">Because JavaScript is single-threaded, we can't take advantage of servers with multiple cores/processors.</span> -- <span id="12c7">Because JavaScript is asynchronous, it is harder to learn for developers that have only worked with languages that default to synchronous operations that block the execution thread.</span> -- <span id="07dc">In the npm repository, there are often too many packages that do the same thing. This excess of packages makes it harder to choose one and, in some cases, may introduce vulnerabilities into our code.</span> - -To write a simple web server with `Node.js`: - -1. <span id="b4ff">Use Node's `HTTP` module to abstract away complex network-related operations.</span> -2. <span id="9e58">Write the single **_request handler_** function to handle all requests to the server.</span> - -The request handler is a function that takes the `request` coming from the client and produces the `response`. The function takes two arguments: 1) an object representing the `request` and 2) an object representing the `response`. - -This process works, but the resulting code is verbose, even for the simplest of servers. Also, note that when using only Node.js to build a server, we use a single request handler function for all requests. - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Try It Out: - -Using only Node.js, let's write a simple web server that returns a message. Create a folder for the server and add an `index.js` file inside. - -Next, add the following code to the `index.js` file: - - const http = require("http"); // built in node.js module to handle http traffic - - const hostname = "127.0.0.1"; // the local computer where the server is running - const port = 3000; // a port we'll use to watch for traffic - - const server = http.createServer((req, res) => { - // creates our server - res.statusCode = 200; // http status code returned to the client - res.setHeader("Content-Type", "text/plain"); // inform the client that we'll be returning text - res.end("Hello World from Node\\n"); // end the request and send a response with the specified message - }); - - server.listen(port, hostname, () => { - // start watching for connections on the port specified - console.log(`Server running at <http://$>{hostname}:${port}/`); - }); - -Now navigate to the folder in a terminal/console window and type: `node index.js` to execute your file. A message that reads "_Server running at_ <a href="http://127.0.0.1:3000" class="markup--anchor markup--p-anchor"><em>http://127.0.0.1:3000</em></a>" should be displayed, and the server is now waiting for connections. - -Open a browser and visit: `http://localhost:3000`. `localhost` and the IP address `127.0.0.1` point to the same thing: your local computer. The browser should show the message: "_Hello World from Node_". There you have it, your first web server, built from scratch using nothing but `Node.js`. - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Explain what Express is and its core features: - -Node's built-in `HTTP` module provides a powerful way to build web applications and services. However, it requires a lot of code for everyday tasks like sending an HTML page to the browser. - -Introducing Express, a light and unopinionated framework that **sits on top of Node.js**, making it easier to create web applications and services. Sending an HTML file or image is now a one-line task with the `sendFile` helper method in `Express`. - -Ultimately, Express is **just a Node.js module** like any other module. - -What can we do with Express? So many things! For example: - -- <span id="0317">Build web applications.</span> -- <span id="6ae8">Serve _Single Page Applications_ (SPAs).</span> -- <span id="308c">Build RESTful web services that work with JSON.</span> -- <span id="7a9e">Serve static content, like HTML files, images, audio files, PDFs, and more.</span> -- <span id="823e">Power real-time applications using technologies like **Web Sockets** or **WebRTC**.</span> - -Some of the benefits of using Express are that it is: - -- <span id="fdf7">Simple</span> -- <span id="7f62">Unopinionated</span> -- <span id="63a7">Extensible</span> -- <span id="09a9">Light-weight</span> -- <span id="d44f">Compatible with <a href="https://www.npmjs.com/package/connect" class="markup--anchor markup--li-anchor">connect middleware (Links to an external site.)</a>. This compatibility means we can tap into an extensive collection of modules written for `connect`.</span> -- <span id="6dbf">All packaged into a clean, intuitive, and easy-to-use API.</span> -- <span id="cc47">Abstracts away common tasks (writing web applications can be verbose, hence the need for a library like this).</span> - -Some of the drawbacks of Express are: - -- <span id="e9d2">It's not a one-stop solution. Because of its simplicity, it does very little out of the box. Especially when compared to frameworks like **Ruby on Rails** and **Django**.</span> -- <span id="9bb7">We are forced to make more decisions due to the flexibility and control it provides.</span> - -### Main Features of Express - -<a href="https://expressjs.com/en/guide/writing-middleware.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://expressjs.com/en/guide/writing-middleware.html"><strong>Writing middleware for use in Express apps</strong> -<br/> - -<em>Middleware functions are functions that have access to the request object ( req), the response object ( res), and the…</em>expressjs.com</a><a href="https://expressjs.com/en/guide/writing-middleware.html" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*rdSEy1R5exC2Rpul.png" class="graf-image" /></figure>### Middleware - -Middleware functions can get the request and response objects, operate on them, and (when specified) trigger some action. Examples are logging or security. - -Express's middleware stack is an array of functions. - -Middleware _can_ change the request or response, but it doesn't have to. - -### Routing - -Routing is a way to select which request handler function is executed. It does so based on the URL visited and the HTTP method used. Routing provides a way to break an application into smaller parts. - -### Routers for Application Modularity - -We can break up applications into **routers**. We could have a router to serve our SPA and another router for our API. Each router can have its own middleware and routing. This combination provides improved functionality. - -### Convenience Helpers - -Express has many helpers that provide out of the box functionality to make writing web applications and API servers easier. - -A lot of those helpers are extension methods added to the request and response objects. - -Examples <a href="https://expressjs.com/en/4x/api.html" class="markup--anchor markup--p-anchor">from the Api Reference (Links to an external site.)</a> include: `response.redirect()`, `response.status()`, `response.send()`, and `request.ip`. - -### Views - -Views provide a way to dynamically render HTML on the server and even generate it using other languages. - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Try It: - -Let's write our first server using Express: - -- <span id="1a5f">Create a new file called `server.js` to host our server code.</span> -- <span id="2d2f">Type `npm init -y` to generate a `package.json`.</span> -- <span id="8b3a">Install the `express` npm module using: `npm install express`.</span> - -Inside `server.js` add the following code: - - const express = require('express'); // import the express package - - const server = express(); // creates the server - - // handle requests to the root of the api, the / route - server.get('/', (req, res) => { - res.send('Hello from Express'); - }); - - // watch for connections on port 5000 - server.listen(5000, () => - console.log('Server running on <http://localhost:5000>') - ); - -Run the server by typing: `node server.js` and visit `http://localhost:5000` in the browser. - -To stop the server, type `Ctrl + c` at the terminal window. - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Create an API that can respond to GET requests - -The steps necessary to build a simple Web API that returns the string "Hello World" on every incoming `GET` request. The program should return the string every time a request comes into the root route ("/"). For now, you don't need to code along, just read through the steps. - -To make things easier, we'll use an existing repository as the base for our API. Later in the week, as we learn more about Node.js and Express, we'll create an API from scratch. - -To build our first API, we will: - -1. <span id="ff64">clone the <a href="https://github.com/LambdaSchool/node-express-mini" class="markup--anchor markup--li-anchor">node-express-mini repository (Links to an external site.)</a> to a folder on our computer.</span> -2. <span id="288f">Navigate into the folder using `cd`.</span> -3. <span id="2043">Use `npm install` to download all dependencies.</span> -4. <span id="be2a">Add a file called `index.js` at the folder's root, next to the `package.json` file.</span> -5. <span id="d92a">Open the `index.js` file using our favorite code editor.</span> -6. <span id="d337">Add the following code:</span> - -<!-- --> - - // require the express npm module, needs to be added to the project using "npm install express" - const express = require('express'); - - // creates an express application using the express module - const server = express(); - - // configures our server to execute a function for every GET request to "/" - // the second argument passed to the .get() method is the "Route Handler Function" - // the route handler function will run on every GET request to "/" - server.get('/', (req, res) => { - // express will pass the request and response objects to this function - // the .send() on the response object can be used to send a response to the client - res.send('Hello World'); - }); - - // once the server is fully configured we can have it "listen" for connections on a particular "port" - // the callback function passed as the second argument will run once when the server starts - server.listen(8000, () => console.log('API running on port 8000')); - -**make sure to save your changes to** `index.js`**.** - -We are using the `express` npm module in our code, so we need to add it as a dependency to our project. To do this: - -- <span id="e9eb">Open a terminal/console/command prompt window and navigate to the root of our project.</span> -- <span id="b744">Add express to our `package.json` file by typing `npm install express`.</span> - -Now we're ready to test our API! - -In the terminal, still at the root of our project: - -- <span id="04b6">Type: `npm run server` to run our API. The message _"Api running on port 8000"_ should appear on the terminal.</span> -- <span id="440e">Open a web browser and navigate to "<a href="http://localhost:8000" class="markup--anchor markup--li-anchor">http://localhost:8000</a>".</span> - -There we have it, our first API! - -A lot is going on in those few lines of code (only six lines if we remove the comments and white space). We will cover every piece of it in detail over the following modules, but here is a quick rundown of the most important concepts. - -First, we used `require()` to **import** the `express module` and make it available to our application. `require()` is similar to the `import` keyword we have used before. The line `const express = require('express');` is equivalent to `import express from 'express';` if we were using ES2015 syntax. - -The following line creates our Express application. The return of calling `express()` is an instance of an Express application that we can use to configure our **server** and, eventually, start listening for and responding to requests. Notice we use the word server, not API. An Express application is generic, which means we can use it to serve static content (HTML, CSS, audio, video, PDFs, and more). We can also use an Express application to serve dynamically generated web pages, build real-time communications servers, and more. We will use it statically to accept requests from clients and respond with data in JSON format. - -An Express application publishes a set of methods we can use to configure functions. We are using the `.get()` method to set up a **route handler** function that will run on every `GET` request. As a part of this handler function, we specify the URL which will trigger the request. In this case, the URL is the site's root (represented by a `/`). There are also methods to handle the `POST`, `PUT`, and `DELETE` HTTP verbs. - -The first two arguments passed by `express` to a route handler function are 1) an object representing the `request` and 2) an object representing the `response`. Express expands those objects with a set of useful properties and methods. Our example uses the `.send()` method of the response object to specify the data we will send to the client as the response body. You can call the first two arguments anything you want, but it is prevalent to see them dubbed `req` and `res`. - -That's all the configuring we need to do for this first example We'll see other ways of configuring our server as we go forward. - -After configuring the server, it's time to turn it on. We use the `.listen()` method to monitor a port on the computer for any incoming connections and respond to those we have configured. Our server will only respond to `GET` requests made to the `/` route on port `8000`. - -That's it for our first Web API, and now it's time for you to follow along as we add a new **endpoint** to our server that returns JSON data! - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Try It Out: - -Let's try returning JSON instead of just a simple string. - -Please follow the steps outlined on the overview, but, to save time, copy and paste the content of `index.js` instead of typing it. Then run your API through a browser to make sure it works. - -Now follow along as we code a new _endpoint_ that returns an array of movie characters in JSON format. - -The first step is to define a new _route handler_ to respond to `GET` requests at the `/hobbits` endpoint. - - server.get('/hobbits', (req, res) => { - // route handler code here - }); - -Next, we define the return data that our endpoint will send back to the client. We do this inside the newly defined route handler function. - - const hobbits = [ - { - id: 1, - name: 'Samwise Gamgee', - }, - { - id: 2, - name: 'Frodo Baggins', - }, - ]; - -Now we can return the `hobbits` array. We could use `.send(hobbits)` as we did for the string on the `/` endpoint, but this time we'll learn about two other useful methods we find in the response object. - - res.status(200).json(hobbits); - -We should provide as much useful information as possible to the clients using our API. One such piece of data is the `HTTP status code` that reflects the client's operation outcome. In this case, the client is trying to get a list of a particular `resource`, a `hobbits` list. Sending back a `200 OK` status code communicates to the client that the operation was successful. - -We will see other status codes as we continue to build new endpoints during this week. You can see a list by following <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="markup--anchor markup--p-anchor">this link to the documentation about HTTP Response Codes on the Mozilla Developer Network site (Links to an external site.)</a>. - -We can use the `.status()` method of the response object to send any valid `HTTP status code`. - -We are also chaining the `.json()` method of the response object. We do this to communicate to both the client making the request and the next developer working with this code that we intend to send the data in `JSON format`. - -The complete code for `index.js` should now look like so: - - const express = require('express'); - - const server = express(); - - server.get('/', (req, res) => { - res.send('Hello World'); - }); - - server.get('/hobbits', (req, res) => { - const hobbits = [ - { - id: 1, - name: 'Samwise Gamgee', - }, - { - id: 2, - name: 'Frodo Baggins', - }, - ]; - - res.status(200).json(hobbits); - }); - - server.listen(8000, () => console.log('API running on port 8000')); - -Now we can visit `http://localhost:8000/hobbits` in our browser, and we should get back our JSON array. - -If you are using the Google Chrome browser, <a href="https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc" class="markup--anchor markup--p-anchor">this extension (Links to an external site.)</a> can format the JSON data in a more readable fashion. - -Congratulations! You just built an API that can return data in JSON format. - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Let's look at a basic example of routing in action. - -First, to make our Express application respond to `GET` requests on different URLs, add the following endpoints: - - // this request handler executes when making a GET request to /about - server.get('/about', (req, res) => { - res.status(200).send('<h1>About Us</h1>'); - }); - - // this request handler executes when making a GET request to /contact - server.get('/contact', (req, res) => { - res.status(200).send('<h1>Contact Form</h1>'); - }); - -Two things to note: - -> 1.) We are using the same HTTP Method on both endpoints, but express looks at the URL and executes the corresponding request handler. - -> 2.) We can return a string with valid HTML! - -Open a browser and navigate to the `/about` and `/contact` routes. The appropriate route handler will execute. - -Please follow along as we write endpoints that execute different request handlers on the same URL by changing the HTTP method. - -Let's start by adding the following code after the `GET` endpoint to `/hobbits`: - - // this request handler executes when making a POST request to /hobbits - server.post('/hobbits', (req, res) => { - res.status(201).json({ url: '/hobbits', operation: 'POST' }); - }); - -Note that we return HTTP status code 201 (created) for successful `POST` operations. - -Next, we need to add an endpoint for `PUT` requests to the same URL. - - // this request handler executes when making a PUT request to /hobbits - server.put('/hobbits', (req, res) => { - res.status(200).json({ url: '/hobbits', operation: 'PUT' }); - }); - -For successful `PUT` operations, we use HTTP Status Code 200 (OK). - -Finally, let's write an endpoint to handle `DELETE` requests. - - // this request handler executes when making a DELETE request to /hobbits - server.delete('/hobbits', (req, res) => { - res.status(204); - }); - -We are returning HTTP Status Code 204 (No Content). Suppose you are returning any data to the client, perhaps the removed resource, on successful deletes. In that case, you'd change that to be 200 instead. - -You may have noticed that we are not reading any data from the request, as that is something we'll learn later in the module. We are about to learn how to use a tool called `Postman` to test our `POST`, `PUT`, and `DELETE` endpoints. - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Reading and Using Route Parameters - -Let's revisit our `DELETE` endpoint. - - server.delete('/hobbits', (req, res) => { - res.status(204); - }); - -How does the client let the API know which hobbit should be deleted or updated? One way, the one we'll use, is through `route parameters`. Let's add support for route parameters to our `DELETE` endpoint. - -We define route parameters by adding it to the URL with a colon (`:`) in front of it. Express adds it to the `.params` property part of the request object. Let's see it in action: - - server.delete('/hobbits/:id', (req, res) => { - const id = req.params.id; - // or we could destructure it like so: const { id } = req.params; - res.status(200).json({ - url: `/hobbits/${id}`, - operation: `DELETE for hobbit with id ${id}`, - }); - }); - -This route handler will execute every `DELETE` for a URL that begins with `/hobbits/` followed by any value. So, `DELETE` requests to `/hobbits/123` and `/hobbits/frodo` will both trigger this request handler. The value passed after `/hobbits/` will end up as the `id` property on `req.params`. - -The value for a route parameter will always be `string`, even if the value passed is numeric. When hitting `/hobbits/123` in our example, the type of `req.params.id` will be `string`. - -Express routing has support for multiple route parameters. For example, defining a route URL that reads `/hobbits/:id/friends/:friendId`, will add properties for `id` and `friendId` to `req.params`. - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Using the Query String - -The query string is another strategy using the URL to pass information from clients to the server. The query string is structured as a set of key/value pairs. Each pair takes the form of `key=value`, and pairs are separated by an `&`. To mark the beginning of the query string, we add `?` and the end of the URL, followed by the set of key/value pairs. - -An example of a query string would be: `https://www.google.com/search?q=lambda&tbo=1`. The query string portion is `?q=lambda&tbo=1` and the key/value pairs are `q=lambda` and `tbo=1`. - -Let's add sorting capabilities to our API. We'll provide a way for clients to hit our `/hobbits` and pass the field they want to use to sort the responses, and our API will sort the data by that field in ascending order. - -Here's the new code for the `GET /hobbits` endpoint: - - server.get('/hobbits', (req, res) => { - // query string parameters get added to req.query - const sortField = req.query.sortby || 'id'; - const hobbits = [ - { - id: 1, - name: 'Samwise Gamgee', - }, - { - id: 2, - name: 'Frodo Baggins', - }, - ]; - - // apply the sorting - const response = hobbits.sort( - (a, b) => (a[sortField] < b[sortField] ? -1 : 1) - ); - - res.status(200).json(response); - }); - -Visit `localhost:8000/hobbits?sortby=name`, and the list should be sorted by `name`. Visit `localhost:8000/hobbits?sortby=id`, and the list should now be sorted by `id`. If no `sortby` parameter is provided, it should default to sorting by `id`. - -To read values from the query string, we use the `req.query` object added by Express. There will be a key and a value in the `req.query` object for each key/value pair found in the query string. - -The parameter's value will be of type `array` if more than one value is passed for the same key and `string` when only one value is passed. For example, in the query string `?id=123`, `req.query.id` will be a string, but for `?id=123&id=234`, it will be an array. - -Another gotcha is that the names of query string parameters are case sensitive, `sortby` and `sortBy` are two different parameters. - -The rest of the code sorts the array before sending it back to the client. - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Reading Data from the Request Body - -We begin by taking another look at the `POST /hobbits` endpoint. We need to read the hobbit's information to add it to the `hobbits` array. Let's do that next: - - // add this code right after const server = express(); - server.use(express.json()); - - let hobbits = [ - { - id: 1, - name: 'Bilbo Baggins', - age: 111, - }, - { - id: 2, - name: 'Frodo Baggins', - age: 33, - }, - ]; - let nextId = 3; - - // and modify the post endpoint like so: - server.post('/hobbits', (req, res) => { - const hobbit = req.body; - hobbit.id = nextId++; - - hobbits.push(hobbit); - - res.status(201).json(hobbits); - }); - -To make this work with the hobbits array, we first move it out of the get endpoint into the outer scope. Now we have access to it from all route handlers. - -Then we define a variable for manual id generation. When using a database, this is not necessary as the database management system generates ids automatically. - -To read data from the request body, we need to do two things: - -- <span id="02f1">Add the line: `server.use(express.json());` after the express application has been created.</span> -- <span id="5111">Read the data from the body property that Express adds to the request object. Express takes all the client's information from the body and makes it available as a nice JavaScript object.</span> - -**Note that we are skipping data validation to keep this demo simple, but in a production application, you would validate before attempting to save to the database.** - -Let's test it using Postman: - -- <span id="2351">Change the method to POST.</span> -- <span id="ca2a">Select the `Body` tab underneath the address bar.</span> -- <span id="ce2e">Click on the `raw` radio button.</span> -- <span id="fbac">From the dropdown menu to the right of the `binary` radio button, select \`JSON (application/json).</span> -- <span id="447b">Add the following JSON object as the body:</span> - -<!-- --> - - { - "name": "Samwise Gamgee", - "age": 30 - } - -Click on `Send`, and the API should return the list of hobbits, including Sam! - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Try It: - -Please code along as we implement the `PUT` endpoint and a way for the client to specify the sort direction. - -### Implement Update Functionality - -Let's continue practicing reading route parameters and information from the request body. Let's take a look at our existing PUT endpoint: - - server.put('/hobbits', (req, res) => { - res.status(200).json({ url: '/hobbits', operation: 'PUT' }); - }); - -We start by adding support for a route parameter the clients can use to specify the id of the hobbit they intend to update: - - server.put('/hobbits/:id', (req, res) => { - res.status(200).json({ url: '/hobbits', operation: 'PUT' }); - }); - -Next, we read the hobbit information from the request body using `req.body` and use it to update the existing hobbit. - - server.put('/hobbits/:id', (req, res) => { - const hobbit = hobbits.find(h => h.id == req.params.id); - - if (!hobbit) { - res.status(404).json({ message: 'Hobbit does not exist' }); - } else { - // modify the existing hobbit - Object.assign(hobbit, req.body); - - res.status(200).json(hobbit); - } - }); - -Concentrate on the code related to reading the `id` from the `req.params` object and reading the hobbit information from `req.body`. The rest of the code will change as this is a simple example using an in-memory array. Most production APIs will use a database. - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### TBC………………………………… - -### If you found this guide helpful feel free to checkout my GitHub/gists where I host similar content: - -<a href="https://gist.github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://gist.github.com/bgoonz"><strong>bgoonz's gists</strong> -<br/> - -<em>Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…</em>gist.github.com</a><a href="https://gist.github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://github.com/bgoonz"><strong>bgoonz — Overview</strong> -<br/> - -<em>Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…</em>github.com</a><a href="https://github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -### Discover More: - -<a href="https://bgoonz-blog.netlify.app/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://bgoonz-blog.netlify.app/"><strong>Web-Dev-Hub</strong> -<br/> - -<em>Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…</em>bgoonz-blog.netlify.app</a><a href="https://bgoonz-blog.netlify.app/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Update(Bonus Best Practices): - -### Things to do in your code - -Here are some things you can do in your code to improve your application's performance: - -- <span id="b2b0"><a href="#use-gzip-compression" class="markup--anchor markup--li-anchor" title="#use-gzip-compression">Use gzip compression</a></span> -- <span id="23bb"><a href="#dont-use-synchronous-functions" class="markup--anchor markup--li-anchor" title="#dont-use-synchronous-functions">Don't use synchronous functions</a></span> -- <span id="904e"><a href="#do-logging-correctly" class="markup--anchor markup--li-anchor" title="#do-logging-correctly">Do logging correctly</a></span> -- <span id="f619"><a href="#handle-exceptions-properly" class="markup--anchor markup--li-anchor" title="#handle-exceptions-properly">Handle exceptions properly</a></span> - -### Use gzip compression - -Gzip compressing can greatly decrease the size of the response body and hence increase the speed of a web app. Use the <a href="https://www.npmjs.com/package/compression" class="markup--anchor markup--p-anchor" title="https://www.npmjs.com/package/compression">compression</a> middleware for gzip compression in your Express app. For example: - - var compression = require('compression') - var express = require('express') - var app = express() - app.use(compression()) - -For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see <a href="#use-a-reverse-proxy" class="markup--anchor markup--p-anchor" title="#use-a-reverse-proxy">Use a reverse proxy</a>). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see <a href="http://nginx.org/en/docs/http/ngx_http_gzip_module.html" class="markup--anchor markup--p-anchor" title="http://nginx.org/en/docs/http/ngx_http_gzip_module.html">Module ngx_http_gzip_module</a> in the Nginx documentation. - -### Don't use synchronous functions - -Synchronous functions and methods tie up the executing process until they return. A single call to a synchronous function might return in a few microseconds or milliseconds, however in high-traffic websites, these calls add up and reduce the performance of the app. Avoid their use in production. - -Although Node and many modules provide synchronous and asynchronous versions of their functions, always use the asynchronous version in production. The only time when a synchronous function can be justified is upon initial startup. - -If you are using Node.js 4.0+ or io.js 2.1.0+, you can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn't want to use this in production, but rather to ensure that your code is ready for production. See the <a href="https://nodejs.org/api/cli.html#cli_trace_sync_io" class="markup--anchor markup--p-anchor" title="https://nodejs.org/api/cli.html#cli_trace_sync_io">node command-line options documentation</a> for more information. - -### Do logging correctly - -In general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But <a href="https://nodejs.org/api/console.html#console_console_1" class="markup--anchor markup--p-anchor" title="https://nodejs.org/api/console.html#console_console_1">these functions are synchronous</a> when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program. - -#### For debugging - -If you're logging for purposes of debugging, then instead of using `console.log()`, use a special debugging module like <a href="https://www.npmjs.com/package/debug" class="markup--anchor markup--p-anchor" title="https://www.npmjs.com/package/debug">debug</a>. This module enables you to use the DEBUG environment variable to control what debug messages are sent to `console.error()`, if any. To keep your app purely asynchronous, you'd still want to pipe `console.error()` to another program. But then, you're not really going to debug in production, are you? - -#### For app activity - -If you're logging app activity (for example, tracking traffic or API calls), instead of using `console.log()`, use a logging library like <a href="https://www.npmjs.com/package/winston" class="markup--anchor markup--p-anchor" title="https://www.npmjs.com/package/winston">Winston</a> or <a href="https://www.npmjs.com/package/bunyan" class="markup--anchor markup--p-anchor" title="https://www.npmjs.com/package/bunyan">Bunyan</a>. For a detailed comparison of these two libraries, see the StrongLoop blog post <a href="https://strongloop.com/strongblog/compare-node-js-logging-winston-bunyan/" class="markup--anchor markup--p-anchor" title="https://strongloop.com/strongblog/compare-node-js-logging-winston-bunyan/">Comparing Winston and Bunyan Node.js Logging</a>. - -### Handle exceptions properly - -Node apps crash when they encounter an uncaught exception. Not handling exceptions and taking appropriate actions will make your Express app crash and go offline. If you follow the advice in <a href="#ensure-your-app-automatically-restarts" class="markup--anchor markup--p-anchor" title="#ensure-your-app-automatically-restarts">Ensure your app automatically restarts</a> below, then your app will recover from a crash. Fortunately, Express apps typically have a short startup time. Nevertheless, you want to avoid crashing in the first place, and to do that, you need to handle exceptions properly. - -To ensure you handle all exceptions, use the following techniques: - -- <span id="4365"><a href="#use-try-catch" class="markup--anchor markup--li-anchor" title="#use-try-catch">Use try-catch</a></span> -- <span id="25cc"><a href="#use-promises" class="markup--anchor markup--li-anchor" title="#use-promises">Use promises</a></span> - -Before diving into these topics, you should have a basic understanding of Node/Express error handling: using error-first callbacks, and propagating errors in middleware. Node uses an "error-first callback" convention for returning errors from asynchronous functions, where the first parameter to the callback function is the error object, followed by result data in succeeding parameters. To indicate no error, pass null as the first parameter. The callback function must correspondingly follow the error-first callback convention to meaningfully handle the error. And in Express, the best practice is to use the next() function to propagate errors through the middleware chain. - -For more on the fundamentals of error handling, see: - -- <span id="e3b5"><a href="https://www.joyent.com/developers/node/design/errors" class="markup--anchor markup--li-anchor" title="https://www.joyent.com/developers/node/design/errors">Error Handling in Node.js</a></span> -- <span id="af28"><a href="https://strongloop.com/strongblog/robust-node-applications-error-handling/" class="markup--anchor markup--li-anchor" title="https://strongloop.com/strongblog/robust-node-applications-error-handling/">Building Robust Node Applications: Error Handling</a> (StrongLoop blog)</span> - -#### What not to do - -One thing you should _not_ do is to listen for the `uncaughtException` event, emitted when an exception bubbles all the way back to the event loop. Adding an event listener for `uncaughtException` will change the default behavior of the process that is encountering an exception; the process will continue to run despite the exception. This might sound like a good way of preventing your app from crashing, but continuing to run the app after an uncaught exception is a dangerous practice and is not recommended, because the state of the process becomes unreliable and unpredictable. - -Additionally, using `uncaughtException` is officially recognized as <a href="https://nodejs.org/api/process.html#process_event_uncaughtexception" class="markup--anchor markup--p-anchor" title="https://nodejs.org/api/process.html#process_event_uncaughtexception">crude</a>. So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error. - -We also don't recommend using <a href="https://nodejs.org/api/domain.html" class="markup--anchor markup--p-anchor" title="https://nodejs.org/api/domain.html">domains</a>. It generally doesn't solve the problem and is a deprecated module. - -#### Use try-catch - -Try-catch is a JavaScript language construct that you can use to catch exceptions in synchronous code. Use try-catch, for example, to handle JSON parsing errors as shown below. - -Use a tool such as <a href="http://jshint.com/" class="markup--anchor markup--p-anchor" title="http://jshint.com/">JSHint</a> or <a href="http://www.jslint.com/" class="markup--anchor markup--p-anchor" title="http://www.jslint.com/">JSLint</a> to help you find implicit exceptions like <a href="http://www.jshint.com/docs/options/#undef" class="markup--anchor markup--p-anchor" title="http://www.jshint.com/docs/options/#undef">reference errors on undefined variables</a>. - -Here is an example of using try-catch to handle a potential process-crashing exception. This middleware function accepts a query field parameter named "params" that is a JSON object. - - app.get('/search', function (req, res) { - // Simulating async operation - setImmediate(function () { - var jsonStr = req.query.params - try { - var jsonObj = JSON.parse(jsonStr) - res.send('Success') - } catch (e) { - res.status(400).send('Invalid JSON string') - } - }) - }) - -However, try-catch works only for synchronous code. Because the Node platform is primarily asynchronous (particularly in a production environment), try-catch won't catch a lot of exceptions. - -#### Use promises - -Promises will handle any exceptions (both explicit and implicit) in asynchronous code blocks that use `then()`. Just add `.catch(next)` to the end of promise chains. For example: - - app.get('/', function (req, res, next) { - // do some sync stuff - queryDb() - .then(function (data) { - // handle data - return makeCsv(data) - }) - .then(function (csv) { - // handle csv - }) - .catch(next) - }) - - app.use(function (err, req, res, next) { - // handle error - }) - -Now all errors asynchronous and synchronous get propagated to the error middleware. - -However, there are two caveats: - -1. <span id="f314">All your asynchronous code must return promises (except emitters). If a particular library does not return promises, convert the base object by using a helper function like <a href="http://bluebirdjs.com/docs/api/promise.promisifyall.html" class="markup--anchor markup--li-anchor" title="http://bluebirdjs.com/docs/api/promise.promisifyall.html">Bluebird.promisifyAll()</a>.</span> -2. <span id="319a">Event emitters (like streams) can still cause uncaught exceptions. So make sure you are handling the error event properly; for example:</span> -3. <span id="b3a0">const wrap = fn => (…args) => fn(…args).catch(args\[2\])</span> -4. <span id="37a8">app.get('/', wrap(async (req, res, next) => { const company = await getCompanyById(<a href="http://req.query.id" class="markup--anchor markup--li-anchor" title="http://req.query.id">req.query.id</a>) const stream = getLogoStreamById(<a href="http://company.id" class="markup--anchor markup--li-anchor" title="http://company.id">company.id</a>) stream.on('error', next).pipe(res) }))</span> - -The `wrap()` function is a wrapper that catches rejected promises and calls `next()` with the error as the first argument. For details, see <a href="https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/#cleaner-code-with-generators" class="markup--anchor markup--p-anchor" title="https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/#cleaner-code-with-generators">Asynchronous Error Handling in Express with Promises, Generators and ES7</a>. - -For more information about error-handling by using promises, see <a href="https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/" class="markup--anchor markup--p-anchor" title="https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/">Promises in Node.js with Q — An Alternative to Callbacks</a>. - -### Things to do in your environment / setup - -Here are some things you can do in your system environment to improve your app's performance: - -- <span id="4d6b"><a href="#set-node_env-to-production" class="markup--anchor markup--li-anchor" title="#set-node_env-to-production">Set NODE_ENV to "production"</a></span> -- <span id="05f1"><a href="#ensure-your-app-automatically-restarts" class="markup--anchor markup--li-anchor" title="#ensure-your-app-automatically-restarts">Ensure your app automatically restarts</a></span> -- <span id="c8e0"><a href="#run-your-app-in-a-cluster" class="markup--anchor markup--li-anchor" title="#run-your-app-in-a-cluster">Run your app in a cluster</a></span> -- <span id="f4af"><a href="#cache-request-results" class="markup--anchor markup--li-anchor" title="#cache-request-results">Cache request results</a></span> -- <span id="4d4a"><a href="#use-a-load-balancer" class="markup--anchor markup--li-anchor" title="#use-a-load-balancer">Use a load balancer</a></span> -- <span id="121c"><a href="#use-a-reverse-proxy" class="markup--anchor markup--li-anchor" title="#use-a-reverse-proxy">Use a reverse proxy</a></span> - -### Set NODE_ENV to "production" - -The NODE_ENV environment variable specifies the environment in which an application is running (usually, development or production). One of the simplest things you can do to improve performance is to set NODE_ENV to "production." - -Setting NODE_ENV to "production" makes Express: - -- <span id="3499">Cache view templates.</span> -- <span id="83b7">Cache CSS files generated from CSS extensions.</span> -- <span id="456c">Generate less verbose error messages.</span> - -<a href="http://apmblog.dynatrace.com/2015/07/22/the-drastic-effects-of-omitting-node_env-in-your-express-js-applications/" class="markup--anchor markup--p-anchor" title="http://apmblog.dynatrace.com/2015/07/22/the-drastic-effects-of-omitting-node_env-in-your-express-js-applications/">Tests indicate</a> that just doing this can improve app performance by a factor of three! - -If you need to write environment-specific code, you can check the value of NODE_ENV with `process.env.NODE_ENV`. Be aware that checking the value of any environment variable incurs a performance penalty, and so should be done sparingly. - -In development, you typically set environment variables in your interactive shell, for example by using `export` or your `.bash_profile` file. But in general you shouldn't do that on a production server; instead, use your OS's init system (systemd or Upstart). The next section provides more details about using your init system in general, but setting NODE_ENV is so important for performance (and easy to do), that it's highlighted here. - -With Upstart, use the `env` keyword in your job file. For example: - - # /etc/init/env.conf - env NODE_ENV=production - -For more information, see the <a href="http://upstart.ubuntu.com/cookbook/#environment-variables" class="markup--anchor markup--p-anchor" title="http://upstart.ubuntu.com/cookbook/#environment-variables">Upstart Intro, Cookbook and Best Practices</a>. - -With systemd, use the `Environment` directive in your unit file. For example: - - # /etc/systemd/system/myservice.service - Environment=NODE_ENV=production - -For more information, see <a href="https://coreos.com/os/docs/latest/using-environment-variables-in-systemd-units.html" class="markup--anchor markup--p-anchor" title="https://coreos.com/os/docs/latest/using-environment-variables-in-systemd-units.html">Using Environment Variables In systemd Units</a>. - -### Ensure your app automatically restarts - -In production, you don't want your application to be offline, ever. This means you need to make sure it restarts both if the app crashes and if the server itself crashes. Although you hope that neither of those events occurs, realistically you must account for both eventualities by: - -- <span id="9675">Using a process manager to restart the app (and Node) when it crashes.</span> -- <span id="d5af">Using the init system provided by your OS to restart the process manager when the OS crashes. It's also possible to use the init system without a process manager.</span> - -Node applications crash if they encounter an uncaught exception. The foremost thing you need to do is to ensure your app is well-tested and handles all exceptions (see <a href="#handle-exceptions-properly" class="markup--anchor markup--p-anchor" title="#handle-exceptions-properly">handle exceptions properly</a> for details). But as a fail-safe, put a mechanism in place to ensure that if and when your app crashes, it will automatically restart. - -#### Use a process manager - -In development, you started your app simply from the command line with `node server.js` or something similar. But doing this in production is a recipe for disaster. If the app crashes, it will be offline until you restart it. To ensure your app restarts if it crashes, use a process manager. A process manager is a "container" for applications that facilitates deployment, provides high availability, and enables you to manage the application at runtime. - -In addition to restarting your app when it crashes, a process manager can enable you to: - -- <span id="bf0c">Gain insights into runtime performance and resource consumption.</span> -- <span id="47ed">Modify settings dynamically to improve performance.</span> -- <span id="f0ed">Control clustering (StrongLoop PM and pm2).</span> - -The most popular process managers for Node are as follows: - -- <span id="1163"><a href="http://strong-pm.io/" class="markup--anchor markup--li-anchor" title="http://strong-pm.io/">StrongLoop Process Manager</a></span> -- <span id="bb4a"><a href="https://github.com/Unitech/pm2" class="markup--anchor markup--li-anchor" title="https://github.com/Unitech/pm2">PM2</a></span> -- <span id="1264"><a href="https://www.npmjs.com/package/forever" class="markup--anchor markup--li-anchor" title="https://www.npmjs.com/package/forever">Forever</a></span> - -For a feature-by-feature comparison of the three process managers, see <a href="http://strong-pm.io/compare/" class="markup--anchor markup--p-anchor" title="http://strong-pm.io/compare/">http://strong-pm.io/compare/</a>. For a more detailed introduction to all three, see <a href="/%7B%7B%20page.lang%20%7D%7D/advanced/pm.html" class="markup--anchor markup--p-anchor" title="/%7B%7B%20page.lang%20%7D%7D/advanced/pm.html">Process managers for Express apps</a>. - -Using any of these process managers will suffice to keep your application up, even if it does crash from time to time. - -However, StrongLoop PM has lots of features that specifically target production deployment. You can use it and the related StrongLoop tools to: - -- <span id="0a60">Build and package your app locally, then deploy it securely to your production system.</span> -- <span id="db02">Automatically restart your app if it crashes for any reason.</span> -- <span id="e1d5">Manage your clusters remotely.</span> -- <span id="6f8a">View CPU profiles and heap snapshots to optimize performance and diagnose memory leaks.</span> -- <span id="51e9">View performance metrics for your application.</span> -- <span id="7393">Easily scale to multiple hosts with integrated control for Nginx load balancer.</span> - -As explained below, when you install StrongLoop PM as an operating system service using your init system, it will automatically restart when the system restarts. Thus, it will keep your application processes and clusters alive forever. - -### Cache request results - -Another strategy to improve the performance in production is to cache the result of requests, so that your app does not repeat the operation to serve the same request repeatedly. - -Use a caching server like <a href="https://www.varnish-cache.org/" class="markup--anchor markup--p-anchor" title="https://www.varnish-cache.org/">Varnish</a> or <a href="https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/" class="markup--anchor markup--p-anchor" title="https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/">Nginx</a> (see also <a href="https://serversforhackers.com/nginx-caching/" class="markup--anchor markup--p-anchor" title="https://serversforhackers.com/nginx-caching/">Nginx Caching</a>) to greatly improve the speed and performance of your app. - -### Use a load balancer - -No matter how optimized an app is, a single instance can handle only a limited amount of load and traffic. One way to scale an app is to run multiple instances of it and distribute the traffic via a load balancer. Setting up a load balancer can improve your app's performance and speed, and enable it to scale more than is possible with a single instance. - -A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using <a href="http://nginx.org/en/docs/http/load_balancing.html" class="markup--anchor markup--p-anchor" title="http://nginx.org/en/docs/http/load_balancing.html">Nginx</a> or <a href="https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts" class="markup--anchor markup--p-anchor" title="https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts">HAProxy</a>. - -With load balancing, you might have to ensure that requests that are associated with a particular session ID connect to the process that originated them. This is known as _session affinity_, or _sticky sessions_, and may be addressed by the suggestion above to use a data store such as Redis for session data (depending on your application). For a discussion, see <a href="http://socket.io/docs/using-multiple-nodes/" class="markup--anchor markup--p-anchor" title="http://socket.io/docs/using-multiple-nodes/">Using multiple nodes</a>. - -### Use a reverse proxy - -A reverse proxy sits in front of a web app and performs supporting operations on the requests, apart from directing requests to the app. It can handle error pages, compression, caching, serving files, and load balancing among other things. - -Handing over tasks that do not require knowledge of application state to a reverse proxy frees up Express to perform specialized application tasks. For this reason, it is recommended to run Express behind a reverse proxy like <a href="https://www.nginx.com/" class="markup--anchor markup--p-anchor" title="https://www.nginx.com/">Nginx</a> or <a href="http://www.haproxy.org/" class="markup--anchor markup--p-anchor" title="http://www.haproxy.org/">HAProxy</a> in production. - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [August 4, 2021](https://medium.com/p/75e3267b284a). - -<a href="https://medium.com/@bryanguner/prerequisites-to-writing-express-apis-75e3267b284a" class="p-canonical">Canonical link</a> - -August 31, 2021. diff --git a/notes/articles/medium/markdown/The-ExpressJS-Way-To-Write.md b/notes/articles/medium/markdown/The-ExpressJS-Way-To-Write.md deleted file mode 100644 index fe026588b8..0000000000 --- a/notes/articles/medium/markdown/The-ExpressJS-Way-To-Write.md +++ /dev/null @@ -1,803 +0,0 @@ -# The ExpressJS Way To Write APIs - -This article will cover the basics of express from the perspective of a beginner without concerning its self with the underlying mechanisms… - ---- - -### The ExpressJS Way To Write APIs - -#### This article will cover the basics of express from the perspective of a beginner without concerning its self with the underlying mechanisms and theory that underlies the application of the framework. - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*yUozFGA0FQpjcXFf.gif" class="graf-image" /></figure>### For starters, what is express JS¿ - -When introduced, node.js gave developers the chance to use JavaScript to write software that, up to that point, could only be written using lower level languages like C, C++, Java, Python… - -This tutorial will cover how to write **web services** that can communicate with clients (the front end application) using **J**ava**S**cript **O**bject **N**otation (JSON). - -- <span id="5334">JavaScript is asynchronous, which allows us to take full advantage of the processor it's running on. Taking full advantage of the processor is crucial because the node process will be running on a single CPU.</span> -- <span id="0b8b">Using JavaScript gives us access to the npm repository. This repository is the largest ecosystem of useful libraries (most of them free to use) in **npm modules**.</span> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*PTKhCN2p9S8EDZ4r.gif" class="graf-image" /></figure> - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Explain what Node.js is and its core features - -<span class="graf-dropCap">T</span>raditionally, developers only used the JavaScript language in web browsers. But, in 2009, **Node.js** was unveiled, and with it, the developer tool kit expanded greatly. Node.js gave developers the chance to use JavaScript to write software that, up to that point, could only be written using C, C++, Java, Python, Ruby, C\#, and the like. - -We will use Node to write server code. Specifically, **web services** that can communicate with clients using the **J**ava**S**cript **O**bject **N**otation (JSON) format for data interchange. - -Some of the advantages of using Node.js for writing server-side code are: - -- <span id="51f9">Uses the same programming language (JavaScript) and paradigm for both client and server. Using the same language, we minimize context switching and make it easy to share code between the client and the server.</span> -- <span id="ad6f">JavaScript is single-threaded, which removes the complexity involved in handling multiple threads.</span> -- <span id="c797">JavaScript is asynchronous, which allows us to take full advantage of the processor it's running on. Taking full advantage of the processor is crucial because the node process will be running on a single CPU.</span> -- <span id="7654">Using JavaScript gives us access to the npm repository. This repository is the largest ecosystem of useful libraries (most of them free to use) in **npm modules**.</span> - -Some of the disadvantages of using Node.js for writing server-side code are: - -- <span id="0f56">By strictly using JavaScript on the server, we lose the ability to use the right tool (a particular language) for the job.</span> -- <span id="cd1e">Because JavaScript is single-threaded, we can't take advantage of servers with multiple cores/processors.</span> -- <span id="12c7">Because JavaScript is asynchronous, it is harder to learn for developers that have only worked with languages that default to synchronous operations that block the execution thread.</span> -- <span id="07dc">In the npm repository, there are often too many packages that do the same thing. This excess of packages makes it harder to choose one and, in some cases, may introduce vulnerabilities into our code.</span> - -To write a simple web server with `Node.js`: - -1. <span id="b4ff">Use Node's `HTTP` module to abstract away complex network-related operations.</span> -2. <span id="9e58">Write the single **_request handler_** function to handle all requests to the server.</span> - -The request handler is a function that takes the `request` coming from the client and produces the `response`. The function takes two arguments: 1) an object representing the `request` and 2) an object representing the `response`. - -This process works, but the resulting code is verbose, even for the simplest of servers. Also, note that when using only Node.js to build a server, we use a single request handler function for all requests. - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Try It Out: - -Using only Node.js, let's write a simple web server that returns a message. Create a folder for the server and add an `index.js` file inside. - -Next, add the following code to the `index.js` file: - - const http = require("http"); // built in node.js module to handle http traffic - - const hostname = "127.0.0.1"; // the local computer where the server is running - const port = 3000; // a port we'll use to watch for traffic - - const server = http.createServer((req, res) => { - // creates our server - res.statusCode = 200; // http status code returned to the client - res.setHeader("Content-Type", "text/plain"); // inform the client that we'll be returning text - res.end("Hello World from Node\\n"); // end the request and send a response with the specified message - }); - - server.listen(port, hostname, () => { - // start watching for connections on the port specified - console.log(`Server running at <http://$>{hostname}:${port}/`); - }); - -Now navigate to the folder in a terminal/console window and type: `node index.js` to execute your file. A message that reads "_Server running at_ <a href="http://127.0.0.1:3000" class="markup--anchor markup--p-anchor"><em>http://127.0.0.1:3000</em></a>" should be displayed, and the server is now waiting for connections. - -Open a browser and visit: `http://localhost:3000`. `localhost` and the IP address `127.0.0.1` point to the same thing: your local computer. The browser should show the message: "_Hello World from Node_". There you have it, your first web server, built from scratch using nothing but `Node.js`. - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Explain what Express is and its core features: - -Node's built-in `HTTP` module provides a powerful way to build web applications and services. However, it requires a lot of code for everyday tasks like sending an HTML page to the browser. - -Introducing Express, a light and unopinionated framework that **sits on top of Node.js**, making it easier to create web applications and services. Sending an HTML file or image is now a one-line task with the `sendFile` helper method in `Express`. - -Ultimately, Express is **just a Node.js module** like any other module. - -What can we do with Express? So many things! For example: - -- <span id="0317">Build web applications.</span> -- <span id="6ae8">Serve _Single Page Applications_ (SPAs).</span> -- <span id="308c">Build RESTful web services that work with JSON.</span> -- <span id="7a9e">Serve static content, like HTML files, images, audio files, PDFs, and more.</span> -- <span id="823e">Power real-time applications using technologies like **Web Sockets** or **WebRTC**.</span> - -Some of the benefits of using Express are that it is: - -- <span id="fdf7">Simple</span> -- <span id="7f62">Unopinionated</span> -- <span id="63a7">Extensible</span> -- <span id="09a9">Light-weight</span> -- <span id="d44f">Compatible with <a href="https://www.npmjs.com/package/connect" class="markup--anchor markup--li-anchor">connect middleware (Links to an external site.)</a>. This compatibility means we can tap into an extensive collection of modules written for `connect`.</span> -- <span id="6dbf">All packaged into a clean, intuitive, and easy-to-use API.</span> -- <span id="cc47">Abstracts away common tasks (writing web applications can be verbose, hence the need for a library like this).</span> - -Some of the drawbacks of Express are: - -- <span id="e9d2">It's not a one-stop solution. Because of its simplicity, it does very little out of the box. Especially when compared to frameworks like **Ruby on Rails** and **Django**.</span> -- <span id="9bb7">We are forced to make more decisions due to the flexibility and control it provides.</span> - -### Main Features of Express - -<a href="https://expressjs.com/en/guide/writing-middleware.html" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://expressjs.com/en/guide/writing-middleware.html"><strong>Writing middleware for use in Express apps</strong> -<br/> - -<em>Middleware functions are functions that have access to the request object ( req), the response object ( res), and the…</em>expressjs.com</a><a href="https://expressjs.com/en/guide/writing-middleware.html" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*rdSEy1R5exC2Rpul.png" class="graf-image" /></figure>### Middleware - -Middleware functions can get the request and response objects, operate on them, and (when specified) trigger some action. Examples are logging or security. - -Express's middleware stack is an array of functions. - -Middleware _can_ change the request or response, but it doesn't have to. - -### Routing - -Routing is a way to select which request handler function is executed. It does so based on the URL visited and the HTTP method used. Routing provides a way to break an application into smaller parts. - -### Routers for Application Modularity - -We can break up applications into **routers**. We could have a router to serve our SPA and another router for our API. Each router can have its own middleware and routing. This combination provides improved functionality. - -### Convenience Helpers - -Express has many helpers that provide out of the box functionality to make writing web applications and API servers easier. - -A lot of those helpers are extension methods added to the request and response objects. - -Examples <a href="https://expressjs.com/en/4x/api.html" class="markup--anchor markup--p-anchor">from the Api Reference (Links to an external site.)</a> include: `response.redirect()`, `response.status()`, `response.send()`, and `request.ip`. - -### Views - -Views provide a way to dynamically render HTML on the server and even generate it using other languages. - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Try It: - -Let's write our first server using Express: - -- <span id="1a5f">Create a new file called `server.js` to host our server code.</span> -- <span id="2d2f">Type `npm init -y` to generate a `package.json`.</span> -- <span id="8b3a">Install the `express` npm module using: `npm install express`.</span> - -Inside `server.js` add the following code: - - const express = require('express'); // import the express package - - const server = express(); // creates the server - - // handle requests to the root of the api, the / route - server.get('/', (req, res) => { - res.send('Hello from Express'); - }); - - // watch for connections on port 5000 - server.listen(5000, () => - console.log('Server running on <http://localhost:5000>') - ); - -Run the server by typing: `node server.js` and visit `http://localhost:5000` in the browser. - -To stop the server, type `Ctrl + c` at the terminal window. - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Create an API that can respond to GET requests - -The steps necessary to build a simple Web API that returns the string "Hello World" on every incoming `GET` request. The program should return the string every time a request comes into the root route ("/"). For now, you don't need to code along, just read through the steps. - -To make things easier, we'll use an existing repository as the base for our API. Later in the week, as we learn more about Node.js and Express, we'll create an API from scratch. - -To build our first API, we will: - -1. <span id="ff64">clone the <a href="https://github.com/LambdaSchool/node-express-mini" class="markup--anchor markup--li-anchor">node-express-mini repository (Links to an external site.)</a> to a folder on our computer.</span> -2. <span id="288f">Navigate into the folder using `cd`.</span> -3. <span id="2043">Use `npm install` to download all dependencies.</span> -4. <span id="be2a">Add a file called `index.js` at the folder's root, next to the `package.json` file.</span> -5. <span id="d92a">Open the `index.js` file using our favorite code editor.</span> -6. <span id="d337">Add the following code:</span> - -<!-- --> - - // require the express npm module, needs to be added to the project using "npm install express" - const express = require('express'); - - // creates an express application using the express module - const server = express(); - - // configures our server to execute a function for every GET request to "/" - // the second argument passed to the .get() method is the "Route Handler Function" - // the route handler function will run on every GET request to "/" - server.get('/', (req, res) => { - // express will pass the request and response objects to this function - // the .send() on the response object can be used to send a response to the client - res.send('Hello World'); - }); - - // once the server is fully configured we can have it "listen" for connections on a particular "port" - // the callback function passed as the second argument will run once when the server starts - server.listen(8000, () => console.log('API running on port 8000')); - -**make sure to save your changes to** `index.js`**.** - -We are using the `express` npm module in our code, so we need to add it as a dependency to our project. To do this: - -- <span id="e9eb">Open a terminal/console/command prompt window and navigate to the root of our project.</span> -- <span id="b744">Add express to our `package.json` file by typing `npm install express`.</span> - -Now we're ready to test our API! - -In the terminal, still at the root of our project: - -- <span id="04b6">Type: `npm run server` to run our API. The message _"Api running on port 8000"_ should appear on the terminal.</span> -- <span id="440e">Open a web browser and navigate to "<a href="http://localhost:8000" class="markup--anchor markup--li-anchor">http://localhost:8000</a>".</span> - -There we have it, our first API! - -A lot is going on in those few lines of code (only six lines if we remove the comments and white space). We will cover every piece of it in detail over the following modules, but here is a quick rundown of the most important concepts. - -First, we used `require()` to **import** the `express module` and make it available to our application. `require()` is similar to the `import` keyword we have used before. The line `const express = require('express');` is equivalent to `import express from 'express';` if we were using ES2015 syntax. - -The following line creates our Express application. The return of calling `express()` is an instance of an Express application that we can use to configure our **server** and, eventually, start listening for and responding to requests. Notice we use the word server, not API. An Express application is generic, which means we can use it to serve static content (HTML, CSS, audio, video, PDFs, and more). We can also use an Express application to serve dynamically generated web pages, build real-time communications servers, and more. We will use it statically to accept requests from clients and respond with data in JSON format. - -An Express application publishes a set of methods we can use to configure functions. We are using the `.get()` method to set up a **route handler** function that will run on every `GET` request. As a part of this handler function, we specify the URL which will trigger the request. In this case, the URL is the site's root (represented by a `/`). There are also methods to handle the `POST`, `PUT`, and `DELETE` HTTP verbs. - -The first two arguments passed by `express` to a route handler function are 1) an object representing the `request` and 2) an object representing the `response`. Express expands those objects with a set of useful properties and methods. Our example uses the `.send()` method of the response object to specify the data we will send to the client as the response body. You can call the first two arguments anything you want, but it is prevalent to see them dubbed `req` and `res`. - -That's all the configuring we need to do for this first example We'll see other ways of configuring our server as we go forward. - -After configuring the server, it's time to turn it on. We use the `.listen()` method to monitor a port on the computer for any incoming connections and respond to those we have configured. Our server will only respond to `GET` requests made to the `/` route on port `8000`. - -That's it for our first Web API, and now it's time for you to follow along as we add a new **endpoint** to our server that returns JSON data! - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Try It Out: - -Let's try returning JSON instead of just a simple string. - -Please follow the steps outlined on the overview, but, to save time, copy and paste the content of `index.js` instead of typing it. Then run your API through a browser to make sure it works. - -Now follow along as we code a new _endpoint_ that returns an array of movie characters in JSON format. - -The first step is to define a new _route handler_ to respond to `GET` requests at the `/hobbits` endpoint. - - server.get('/hobbits', (req, res) => { - // route handler code here - }); - -Next, we define the return data that our endpoint will send back to the client. We do this inside the newly defined route handler function. - - const hobbits = [ - { - id: 1, - name: 'Samwise Gamgee', - }, - { - id: 2, - name: 'Frodo Baggins', - }, - ]; - -Now we can return the `hobbits` array. We could use `.send(hobbits)` as we did for the string on the `/` endpoint, but this time we'll learn about two other useful methods we find in the response object. - - res.status(200).json(hobbits); - -We should provide as much useful information as possible to the clients using our API. One such piece of data is the `HTTP status code` that reflects the client's operation outcome. In this case, the client is trying to get a list of a particular `resource`, a `hobbits` list. Sending back a `200 OK` status code communicates to the client that the operation was successful. - -We will see other status codes as we continue to build new endpoints during this week. You can see a list by following <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status" class="markup--anchor markup--p-anchor">this link to the documentation about HTTP Response Codes on the Mozilla Developer Network site (Links to an external site.)</a>. - -We can use the `.status()` method of the response object to send any valid `HTTP status code`. - -We are also chaining the `.json()` method of the response object. We do this to communicate to both the client making the request and the next developer working with this code that we intend to send the data in `JSON format`. - -The complete code for `index.js` should now look like so: - - const express = require('express'); - - const server = express(); - - server.get('/', (req, res) => { - res.send('Hello World'); - }); - - server.get('/hobbits', (req, res) => { - const hobbits = [ - { - id: 1, - name: 'Samwise Gamgee', - }, - { - id: 2, - name: 'Frodo Baggins', - }, - ]; - - res.status(200).json(hobbits); - }); - - server.listen(8000, () => console.log('API running on port 8000')); - -Now we can visit `http://localhost:8000/hobbits` in our browser, and we should get back our JSON array. - -If you are using the Google Chrome browser, <a href="https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc" class="markup--anchor markup--p-anchor">this extension (Links to an external site.)</a> can format the JSON data in a more readable fashion. - -Congratulations! You just built an API that can return data in JSON format. - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Let's look at a basic example of routing in action. - -First, to make our Express application respond to `GET` requests on different URLs, add the following endpoints: - - // this request handler executes when making a GET request to /about - server.get('/about', (req, res) => { - res.status(200).send('<h1>About Us</h1>'); - }); - - // this request handler executes when making a GET request to /contact - server.get('/contact', (req, res) => { - res.status(200).send('<h1>Contact Form</h1>'); - }); - -Two things to note: - -> 1.) We are using the same HTTP Method on both endpoints, but express looks at the URL and executes the corresponding request handler. - -> 2.) We can return a string with valid HTML! - -Open a browser and navigate to the `/about` and `/contact` routes. The appropriate route handler will execute. - -Please follow along as we write endpoints that execute different request handlers on the same URL by changing the HTTP method. - -Let's start by adding the following code after the `GET` endpoint to `/hobbits`: - - // this request handler executes when making a POST request to /hobbits - server.post('/hobbits', (req, res) => { - res.status(201).json({ url: '/hobbits', operation: 'POST' }); - }); - -Note that we return HTTP status code 201 (created) for successful `POST` operations. - -Next, we need to add an endpoint for `PUT` requests to the same URL. - - // this request handler executes when making a PUT request to /hobbits - server.put('/hobbits', (req, res) => { - res.status(200).json({ url: '/hobbits', operation: 'PUT' }); - }); - -For successful `PUT` operations, we use HTTP Status Code 200 (OK). - -Finally, let's write an endpoint to handle `DELETE` requests. - - // this request handler executes when making a DELETE request to /hobbits - server.delete('/hobbits', (req, res) => { - res.status(204); - }); - -We are returning HTTP Status Code 204 (No Content). Suppose you are returning any data to the client, perhaps the removed resource, on successful deletes. In that case, you'd change that to be 200 instead. - -You may have noticed that we are not reading any data from the request, as that is something we'll learn later in the module. We are about to learn how to use a tool called `Postman` to test our `POST`, `PUT`, and `DELETE` endpoints. - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Reading and Using Route Parameters - -Let's revisit our `DELETE` endpoint. - - server.delete('/hobbits', (req, res) => { - res.status(204); - }); - -How does the client let the API know which hobbit should be deleted or updated? One way, the one we'll use, is through `route parameters`. Let's add support for route parameters to our `DELETE` endpoint. - -We define route parameters by adding it to the URL with a colon (`:`) in front of it. Express adds it to the `.params` property part of the request object. Let's see it in action: - - server.delete('/hobbits/:id', (req, res) => { - const id = req.params.id; - // or we could destructure it like so: const { id } = req.params; - res.status(200).json({ - url: `/hobbits/${id}`, - operation: `DELETE for hobbit with id ${id}`, - }); - }); - -This route handler will execute every `DELETE` for a URL that begins with `/hobbits/` followed by any value. So, `DELETE` requests to `/hobbits/123` and `/hobbits/frodo` will both trigger this request handler. The value passed after `/hobbits/` will end up as the `id` property on `req.params`. - -The value for a route parameter will always be `string`, even if the value passed is numeric. When hitting `/hobbits/123` in our example, the type of `req.params.id` will be `string`. - -Express routing has support for multiple route parameters. For example, defining a route URL that reads `/hobbits/:id/friends/:friendId`, will add properties for `id` and `friendId` to `req.params`. - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Using the Query String - -The query string is another strategy using the URL to pass information from clients to the server. The query string is structured as a set of key/value pairs. Each pair takes the form of `key=value`, and pairs are separated by an `&`. To mark the beginning of the query string, we add `?` and the end of the URL, followed by the set of key/value pairs. - -An example of a query string would be: `https://www.google.com/search?q=lambda&tbo=1`. The query string portion is `?q=lambda&tbo=1` and the key/value pairs are `q=lambda` and `tbo=1`. - -Let's add sorting capabilities to our API. We'll provide a way for clients to hit our `/hobbits` and pass the field they want to use to sort the responses, and our API will sort the data by that field in ascending order. - -Here's the new code for the `GET /hobbits` endpoint: - - server.get('/hobbits', (req, res) => { - // query string parameters get added to req.query - const sortField = req.query.sortby || 'id'; - const hobbits = [ - { - id: 1, - name: 'Samwise Gamgee', - }, - { - id: 2, - name: 'Frodo Baggins', - }, - ]; - - // apply the sorting - const response = hobbits.sort( - (a, b) => (a[sortField] < b[sortField] ? -1 : 1) - ); - - res.status(200).json(response); - }); - -Visit `localhost:8000/hobbits?sortby=name`, and the list should be sorted by `name`. Visit `localhost:8000/hobbits?sortby=id`, and the list should now be sorted by `id`. If no `sortby` parameter is provided, it should default to sorting by `id`. - -To read values from the query string, we use the `req.query` object added by Express. There will be a key and a value in the `req.query` object for each key/value pair found in the query string. - -The parameter's value will be of type `array` if more than one value is passed for the same key and `string` when only one value is passed. For example, in the query string `?id=123`, `req.query.id` will be a string, but for `?id=123&id=234`, it will be an array. - -Another gotcha is that the names of query string parameters are case sensitive, `sortby` and `sortBy` are two different parameters. - -The rest of the code sorts the array before sending it back to the client. - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Reading Data from the Request Body - -We begin by taking another look at the `POST /hobbits` endpoint. We need to read the hobbit's information to add it to the `hobbits` array. Let's do that next: - - // add this code right after const server = express(); - server.use(express.json()); - - let hobbits = [ - { - id: 1, - name: 'Bilbo Baggins', - age: 111, - }, - { - id: 2, - name: 'Frodo Baggins', - age: 33, - }, - ]; - let nextId = 3; - - // and modify the post endpoint like so: - server.post('/hobbits', (req, res) => { - const hobbit = req.body; - hobbit.id = nextId++; - - hobbits.push(hobbit); - - res.status(201).json(hobbits); - }); - -To make this work with the hobbits array, we first move it out of the get endpoint into the outer scope. Now we have access to it from all route handlers. - -Then we define a variable for manual id generation. When using a database, this is not necessary as the database management system generates ids automatically. - -To read data from the request body, we need to do two things: - -- <span id="02f1">Add the line: `server.use(express.json());` after the express application has been created.</span> -- <span id="5111">Read the data from the body property that Express adds to the request object. Express takes all the client's information from the body and makes it available as a nice JavaScript object.</span> - -**Note that we are skipping data validation to keep this demo simple, but in a production application, you would validate before attempting to save to the database.** - -Let's test it using Postman: - -- <span id="2351">Change the method to POST.</span> -- <span id="ca2a">Select the `Body` tab underneath the address bar.</span> -- <span id="ce2e">Click on the `raw` radio button.</span> -- <span id="fbac">From the dropdown menu to the right of the `binary` radio button, select \`JSON (application/json).</span> -- <span id="447b">Add the following JSON object as the body:</span> - -<!-- --> - - { - "name": "Samwise Gamgee", - "age": 30 - } - -Click on `Send`, and the API should return the list of hobbits, including Sam! - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Try It: - -Please code along as we implement the `PUT` endpoint and a way for the client to specify the sort direction. - -### Implement Update Functionality - -Let's continue practicing reading route parameters and information from the request body. Let's take a look at our existing PUT endpoint: - - server.put('/hobbits', (req, res) => { - res.status(200).json({ url: '/hobbits', operation: 'PUT' }); - }); - -We start by adding support for a route parameter the clients can use to specify the id of the hobbit they intend to update: - - server.put('/hobbits/:id', (req, res) => { - res.status(200).json({ url: '/hobbits', operation: 'PUT' }); - }); - -Next, we read the hobbit information from the request body using `req.body` and use it to update the existing hobbit. - - server.put('/hobbits/:id', (req, res) => { - const hobbit = hobbits.find(h => h.id == req.params.id); - - if (!hobbit) { - res.status(404).json({ message: 'Hobbit does not exist' }); - } else { - // modify the existing hobbit - Object.assign(hobbit, req.body); - - res.status(200).json(hobbit); - } - }); - -Concentrate on the code related to reading the `id` from the `req.params` object and reading the hobbit information from `req.body`. The rest of the code will change as this is a simple example using an in-memory array. Most production APIs will use a database. - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### TBC………………………………… - -### If you found this guide helpful feel free to checkout my GitHub/gists where I host similar content: - -<a href="https://gist.github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://gist.github.com/bgoonz"><strong>bgoonz's gists</strong> -<br/> - -<em>Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…</em>gist.github.com</a><a href="https://gist.github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<a href="https://github.com/bgoonz" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://github.com/bgoonz"><strong>bgoonz — Overview</strong> -<br/> - -<em>Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…</em>github.com</a><a href="https://github.com/bgoonz" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -### Discover More: - -<a href="https://bgoonz-blog.netlify.app/" class="markup--anchor markup--mixtapeEmbed-anchor" title="https://bgoonz-blog.netlify.app/"><strong>Web-Dev-Hub</strong> -<br/> - -<em>Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…</em>bgoonz-blog.netlify.app</a><a href="https://bgoonz-blog.netlify.app/" class="js-mixtapeImage mixtapeImage u-ignoreBlock"></a> - -<figure><img src="https://cdn-images-1.medium.com/max/1200/1*nGyJHK1Q_sSB6fjbBbF3xA.png" class="graf-image" /></figure> - -### Update(Bonus Best Practices): - -### Things to do in your code - -Here are some things you can do in your code to improve your application's performance: - -- <span id="b2b0"><a href="#use-gzip-compression" class="markup--anchor markup--li-anchor" title="#use-gzip-compression">Use gzip compression</a></span> -- <span id="23bb"><a href="#dont-use-synchronous-functions" class="markup--anchor markup--li-anchor" title="#dont-use-synchronous-functions">Don't use synchronous functions</a></span> -- <span id="904e"><a href="#do-logging-correctly" class="markup--anchor markup--li-anchor" title="#do-logging-correctly">Do logging correctly</a></span> -- <span id="f619"><a href="#handle-exceptions-properly" class="markup--anchor markup--li-anchor" title="#handle-exceptions-properly">Handle exceptions properly</a></span> - -### Use gzip compression - -Gzip compressing can greatly decrease the size of the response body and hence increase the speed of a web app. Use the <a href="https://www.npmjs.com/package/compression" class="markup--anchor markup--p-anchor" title="https://www.npmjs.com/package/compression">compression</a> middleware for gzip compression in your Express app. For example: - - var compression = require('compression') - var express = require('express') - var app = express() - app.use(compression()) - -For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see <a href="#use-a-reverse-proxy" class="markup--anchor markup--p-anchor" title="#use-a-reverse-proxy">Use a reverse proxy</a>). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see <a href="http://nginx.org/en/docs/http/ngx_http_gzip_module.html" class="markup--anchor markup--p-anchor" title="http://nginx.org/en/docs/http/ngx_http_gzip_module.html">Module ngx_http_gzip_module</a> in the Nginx documentation. - -### Don't use synchronous functions - -Synchronous functions and methods tie up the executing process until they return. A single call to a synchronous function might return in a few microseconds or milliseconds, however in high-traffic websites, these calls add up and reduce the performance of the app. Avoid their use in production. - -Although Node and many modules provide synchronous and asynchronous versions of their functions, always use the asynchronous version in production. The only time when a synchronous function can be justified is upon initial startup. - -If you are using Node.js 4.0+ or io.js 2.1.0+, you can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn't want to use this in production, but rather to ensure that your code is ready for production. See the <a href="https://nodejs.org/api/cli.html#cli_trace_sync_io" class="markup--anchor markup--p-anchor" title="https://nodejs.org/api/cli.html#cli_trace_sync_io">node command-line options documentation</a> for more information. - -### Do logging correctly - -In general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But <a href="https://nodejs.org/api/console.html#console_console_1" class="markup--anchor markup--p-anchor" title="https://nodejs.org/api/console.html#console_console_1">these functions are synchronous</a> when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program. - -#### For debugging - -If you're logging for purposes of debugging, then instead of using `console.log()`, use a special debugging module like <a href="https://www.npmjs.com/package/debug" class="markup--anchor markup--p-anchor" title="https://www.npmjs.com/package/debug">debug</a>. This module enables you to use the DEBUG environment variable to control what debug messages are sent to `console.error()`, if any. To keep your app purely asynchronous, you'd still want to pipe `console.error()` to another program. But then, you're not really going to debug in production, are you? - -#### For app activity - -If you're logging app activity (for example, tracking traffic or API calls), instead of using `console.log()`, use a logging library like <a href="https://www.npmjs.com/package/winston" class="markup--anchor markup--p-anchor" title="https://www.npmjs.com/package/winston">Winston</a> or <a href="https://www.npmjs.com/package/bunyan" class="markup--anchor markup--p-anchor" title="https://www.npmjs.com/package/bunyan">Bunyan</a>. For a detailed comparison of these two libraries, see the StrongLoop blog post <a href="https://strongloop.com/strongblog/compare-node-js-logging-winston-bunyan/" class="markup--anchor markup--p-anchor" title="https://strongloop.com/strongblog/compare-node-js-logging-winston-bunyan/">Comparing Winston and Bunyan Node.js Logging</a>. - -### Handle exceptions properly - -Node apps crash when they encounter an uncaught exception. Not handling exceptions and taking appropriate actions will make your Express app crash and go offline. If you follow the advice in <a href="#ensure-your-app-automatically-restarts" class="markup--anchor markup--p-anchor" title="#ensure-your-app-automatically-restarts">Ensure your app automatically restarts</a> below, then your app will recover from a crash. Fortunately, Express apps typically have a short startup time. Nevertheless, you want to avoid crashing in the first place, and to do that, you need to handle exceptions properly. - -To ensure you handle all exceptions, use the following techniques: - -- <span id="4365"><a href="#use-try-catch" class="markup--anchor markup--li-anchor" title="#use-try-catch">Use try-catch</a></span> -- <span id="25cc"><a href="#use-promises" class="markup--anchor markup--li-anchor" title="#use-promises">Use promises</a></span> - -Before diving into these topics, you should have a basic understanding of Node/Express error handling: using error-first callbacks, and propagating errors in middleware. Node uses an "error-first callback" convention for returning errors from asynchronous functions, where the first parameter to the callback function is the error object, followed by result data in succeeding parameters. To indicate no error, pass null as the first parameter. The callback function must correspondingly follow the error-first callback convention to meaningfully handle the error. And in Express, the best practice is to use the next() function to propagate errors through the middleware chain. - -For more on the fundamentals of error handling, see: - -- <span id="e3b5"><a href="https://www.joyent.com/developers/node/design/errors" class="markup--anchor markup--li-anchor" title="https://www.joyent.com/developers/node/design/errors">Error Handling in Node.js</a></span> -- <span id="af28"><a href="https://strongloop.com/strongblog/robust-node-applications-error-handling/" class="markup--anchor markup--li-anchor" title="https://strongloop.com/strongblog/robust-node-applications-error-handling/">Building Robust Node Applications: Error Handling</a> (StrongLoop blog)</span> - -#### What not to do - -One thing you should _not_ do is to listen for the `uncaughtException` event, emitted when an exception bubbles all the way back to the event loop. Adding an event listener for `uncaughtException` will change the default behavior of the process that is encountering an exception; the process will continue to run despite the exception. This might sound like a good way of preventing your app from crashing, but continuing to run the app after an uncaught exception is a dangerous practice and is not recommended, because the state of the process becomes unreliable and unpredictable. - -Additionally, using `uncaughtException` is officially recognized as <a href="https://nodejs.org/api/process.html#process_event_uncaughtexception" class="markup--anchor markup--p-anchor" title="https://nodejs.org/api/process.html#process_event_uncaughtexception">crude</a>. So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error. - -We also don't recommend using <a href="https://nodejs.org/api/domain.html" class="markup--anchor markup--p-anchor" title="https://nodejs.org/api/domain.html">domains</a>. It generally doesn't solve the problem and is a deprecated module. - -#### Use try-catch - -Try-catch is a JavaScript language construct that you can use to catch exceptions in synchronous code. Use try-catch, for example, to handle JSON parsing errors as shown below. - -Use a tool such as <a href="http://jshint.com/" class="markup--anchor markup--p-anchor" title="http://jshint.com/">JSHint</a> or <a href="http://www.jslint.com/" class="markup--anchor markup--p-anchor" title="http://www.jslint.com/">JSLint</a> to help you find implicit exceptions like <a href="http://www.jshint.com/docs/options/#undef" class="markup--anchor markup--p-anchor" title="http://www.jshint.com/docs/options/#undef">reference errors on undefined variables</a>. - -Here is an example of using try-catch to handle a potential process-crashing exception. This middleware function accepts a query field parameter named "params" that is a JSON object. - - app.get('/search', function (req, res) { - // Simulating async operation - setImmediate(function () { - var jsonStr = req.query.params - try { - var jsonObj = JSON.parse(jsonStr) - res.send('Success') - } catch (e) { - res.status(400).send('Invalid JSON string') - } - }) - }) - -However, try-catch works only for synchronous code. Because the Node platform is primarily asynchronous (particularly in a production environment), try-catch won't catch a lot of exceptions. - -#### Use promises - -Promises will handle any exceptions (both explicit and implicit) in asynchronous code blocks that use `then()`. Just add `.catch(next)` to the end of promise chains. For example: - - app.get('/', function (req, res, next) { - // do some sync stuff - queryDb() - .then(function (data) { - // handle data - return makeCsv(data) - }) - .then(function (csv) { - // handle csv - }) - .catch(next) - }) - - app.use(function (err, req, res, next) { - // handle error - }) - -Now all errors asynchronous and synchronous get propagated to the error middleware. - -However, there are two caveats: - -1. <span id="f314">All your asynchronous code must return promises (except emitters). If a particular library does not return promises, convert the base object by using a helper function like <a href="http://bluebirdjs.com/docs/api/promise.promisifyall.html" class="markup--anchor markup--li-anchor" title="http://bluebirdjs.com/docs/api/promise.promisifyall.html">Bluebird.promisifyAll()</a>.</span> -2. <span id="319a">Event emitters (like streams) can still cause uncaught exceptions. So make sure you are handling the error event properly; for example:</span> -3. <span id="b3a0">const wrap = fn => (…args) => fn(…args).catch(args\[2\])</span> -4. <span id="37a8">app.get('/', wrap(async (req, res, next) => { const company = await getCompanyById(<a href="http://req.query.id" class="markup--anchor markup--li-anchor" title="http://req.query.id">req.query.id</a>) const stream = getLogoStreamById(<a href="http://company.id" class="markup--anchor markup--li-anchor" title="http://company.id">company.id</a>) stream.on('error', next).pipe(res) }))</span> - -The `wrap()` function is a wrapper that catches rejected promises and calls `next()` with the error as the first argument. For details, see <a href="https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/#cleaner-code-with-generators" class="markup--anchor markup--p-anchor" title="https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/#cleaner-code-with-generators">Asynchronous Error Handling in Express with Promises, Generators and ES7</a>. - -For more information about error-handling by using promises, see <a href="https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/" class="markup--anchor markup--p-anchor" title="https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/">Promises in Node.js with Q — An Alternative to Callbacks</a>. - -### Things to do in your environment / setup - -Here are some things you can do in your system environment to improve your app's performance: - -- <span id="4d6b"><a href="#set-node_env-to-production" class="markup--anchor markup--li-anchor" title="#set-node_env-to-production">Set NODE_ENV to "production"</a></span> -- <span id="05f1"><a href="#ensure-your-app-automatically-restarts" class="markup--anchor markup--li-anchor" title="#ensure-your-app-automatically-restarts">Ensure your app automatically restarts</a></span> -- <span id="c8e0"><a href="#run-your-app-in-a-cluster" class="markup--anchor markup--li-anchor" title="#run-your-app-in-a-cluster">Run your app in a cluster</a></span> -- <span id="f4af"><a href="#cache-request-results" class="markup--anchor markup--li-anchor" title="#cache-request-results">Cache request results</a></span> -- <span id="4d4a"><a href="#use-a-load-balancer" class="markup--anchor markup--li-anchor" title="#use-a-load-balancer">Use a load balancer</a></span> -- <span id="121c"><a href="#use-a-reverse-proxy" class="markup--anchor markup--li-anchor" title="#use-a-reverse-proxy">Use a reverse proxy</a></span> - -### Set NODE_ENV to "production" - -The NODE_ENV environment variable specifies the environment in which an application is running (usually, development or production). One of the simplest things you can do to improve performance is to set NODE_ENV to "production." - -Setting NODE_ENV to "production" makes Express: - -- <span id="3499">Cache view templates.</span> -- <span id="83b7">Cache CSS files generated from CSS extensions.</span> -- <span id="456c">Generate less verbose error messages.</span> - -<a href="http://apmblog.dynatrace.com/2015/07/22/the-drastic-effects-of-omitting-node_env-in-your-express-js-applications/" class="markup--anchor markup--p-anchor" title="http://apmblog.dynatrace.com/2015/07/22/the-drastic-effects-of-omitting-node_env-in-your-express-js-applications/">Tests indicate</a> that just doing this can improve app performance by a factor of three! - -If you need to write environment-specific code, you can check the value of NODE_ENV with `process.env.NODE_ENV`. Be aware that checking the value of any environment variable incurs a performance penalty, and so should be done sparingly. - -In development, you typically set environment variables in your interactive shell, for example by using `export` or your `.bash_profile` file. But in general you shouldn't do that on a production server; instead, use your OS's init system (systemd or Upstart). The next section provides more details about using your init system in general, but setting NODE_ENV is so important for performance (and easy to do), that it's highlighted here. - -With Upstart, use the `env` keyword in your job file. For example: - - # /etc/init/env.conf - env NODE_ENV=production - -For more information, see the <a href="http://upstart.ubuntu.com/cookbook/#environment-variables" class="markup--anchor markup--p-anchor" title="http://upstart.ubuntu.com/cookbook/#environment-variables">Upstart Intro, Cookbook and Best Practices</a>. - -With systemd, use the `Environment` directive in your unit file. For example: - - # /etc/systemd/system/myservice.service - Environment=NODE_ENV=production - -For more information, see <a href="https://coreos.com/os/docs/latest/using-environment-variables-in-systemd-units.html" class="markup--anchor markup--p-anchor" title="https://coreos.com/os/docs/latest/using-environment-variables-in-systemd-units.html">Using Environment Variables In systemd Units</a>. - -### Ensure your app automatically restarts - -In production, you don't want your application to be offline, ever. This means you need to make sure it restarts both if the app crashes and if the server itself crashes. Although you hope that neither of those events occurs, realistically you must account for both eventualities by: - -- <span id="9675">Using a process manager to restart the app (and Node) when it crashes.</span> -- <span id="d5af">Using the init system provided by your OS to restart the process manager when the OS crashes. It's also possible to use the init system without a process manager.</span> - -Node applications crash if they encounter an uncaught exception. The foremost thing you need to do is to ensure your app is well-tested and handles all exceptions (see <a href="#handle-exceptions-properly" class="markup--anchor markup--p-anchor" title="#handle-exceptions-properly">handle exceptions properly</a> for details). But as a fail-safe, put a mechanism in place to ensure that if and when your app crashes, it will automatically restart. - -#### Use a process manager - -In development, you started your app simply from the command line with `node server.js` or something similar. But doing this in production is a recipe for disaster. If the app crashes, it will be offline until you restart it. To ensure your app restarts if it crashes, use a process manager. A process manager is a "container" for applications that facilitates deployment, provides high availability, and enables you to manage the application at runtime. - -In addition to restarting your app when it crashes, a process manager can enable you to: - -- <span id="bf0c">Gain insights into runtime performance and resource consumption.</span> -- <span id="47ed">Modify settings dynamically to improve performance.</span> -- <span id="f0ed">Control clustering (StrongLoop PM and pm2).</span> - -The most popular process managers for Node are as follows: - -- <span id="1163"><a href="http://strong-pm.io/" class="markup--anchor markup--li-anchor" title="http://strong-pm.io/">StrongLoop Process Manager</a></span> -- <span id="bb4a"><a href="https://github.com/Unitech/pm2" class="markup--anchor markup--li-anchor" title="https://github.com/Unitech/pm2">PM2</a></span> -- <span id="1264"><a href="https://www.npmjs.com/package/forever" class="markup--anchor markup--li-anchor" title="https://www.npmjs.com/package/forever">Forever</a></span> - -For a feature-by-feature comparison of the three process managers, see <a href="http://strong-pm.io/compare/" class="markup--anchor markup--p-anchor" title="http://strong-pm.io/compare/">http://strong-pm.io/compare/</a>. For a more detailed introduction to all three, see <a href="/%7B%7B%20page.lang%20%7D%7D/advanced/pm.html" class="markup--anchor markup--p-anchor" title="/%7B%7B%20page.lang%20%7D%7D/advanced/pm.html">Process managers for Express apps</a>. - -Using any of these process managers will suffice to keep your application up, even if it does crash from time to time. - -However, StrongLoop PM has lots of features that specifically target production deployment. You can use it and the related StrongLoop tools to: - -- <span id="0a60">Build and package your app locally, then deploy it securely to your production system.</span> -- <span id="db02">Automatically restart your app if it crashes for any reason.</span> -- <span id="e1d5">Manage your clusters remotely.</span> -- <span id="6f8a">View CPU profiles and heap snapshots to optimize performance and diagnose memory leaks.</span> -- <span id="51e9">View performance metrics for your application.</span> -- <span id="7393">Easily scale to multiple hosts with integrated control for Nginx load balancer.</span> - -As explained below, when you install StrongLoop PM as an operating system service using your init system, it will automatically restart when the system restarts. Thus, it will keep your application processes and clusters alive forever. - -### Cache request results - -Another strategy to improve the performance in production is to cache the result of requests, so that your app does not repeat the operation to serve the same request repeatedly. - -Use a caching server like <a href="https://www.varnish-cache.org/" class="markup--anchor markup--p-anchor" title="https://www.varnish-cache.org/">Varnish</a> or <a href="https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/" class="markup--anchor markup--p-anchor" title="https://www.nginx.com/resources/wiki/start/topics/examples/reverseproxycachingexample/">Nginx</a> (see also <a href="https://serversforhackers.com/nginx-caching/" class="markup--anchor markup--p-anchor" title="https://serversforhackers.com/nginx-caching/">Nginx Caching</a>) to greatly improve the speed and performance of your app. - -### Use a load balancer - -No matter how optimized an app is, a single instance can handle only a limited amount of load and traffic. One way to scale an app is to run multiple instances of it and distribute the traffic via a load balancer. Setting up a load balancer can improve your app's performance and speed, and enable it to scale more than is possible with a single instance. - -A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using <a href="http://nginx.org/en/docs/http/load_balancing.html" class="markup--anchor markup--p-anchor" title="http://nginx.org/en/docs/http/load_balancing.html">Nginx</a> or <a href="https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts" class="markup--anchor markup--p-anchor" title="https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts">HAProxy</a>. - -With load balancing, you might have to ensure that requests that are associated with a particular session ID connect to the process that originated them. This is known as _session affinity_, or _sticky sessions_, and may be addressed by the suggestion above to use a data store such as Redis for session data (depending on your application). For a discussion, see <a href="http://socket.io/docs/using-multiple-nodes/" class="markup--anchor markup--p-anchor" title="http://socket.io/docs/using-multiple-nodes/">Using multiple nodes</a>. - -### Use a reverse proxy - -A reverse proxy sits in front of a web app and performs supporting operations on the requests, apart from directing requests to the app. It can handle error pages, compression, caching, serving files, and load balancing among other things. - -Handing over tasks that do not require knowledge of application state to a reverse proxy frees up Express to perform specialized application tasks. For this reason, it is recommended to run Express behind a reverse proxy like <a href="https://www.nginx.com/" class="markup--anchor markup--p-anchor" title="https://www.nginx.com/">Nginx</a> or <a href="http://www.haproxy.org/" class="markup--anchor markup--p-anchor" title="http://www.haproxy.org/">HAProxy</a> in production. - -By <a href="https://medium.com/@bryanguner" class="p-author h-card">Bryan Guner</a> on [August 4, 2021](https://medium.com/p/75e3267b284a). - -<a href="https://medium.com/@bryanguner/prerequisites-to-writing-express-apis-75e3267b284a" class="p-canonical">Canonical link</a> - -August 6, 2021. diff --git a/notes/articles/medium/markdown/The-Penultimate-Web-Developer-s-Cheat-Sheet.md b/notes/articles/medium/markdown/The-Penultimate-Web-Developer-s-Cheat-Sheet.md deleted file mode 100644 index 288a2276d7..0000000000 --- a/notes/articles/medium/markdown/The-Penultimate-Web-Developer-s-Cheat-Sheet.md +++ /dev/null @@ -1,628 +0,0 @@ -# The Penultimate Web Developer's Cheat Sheet - -I am literally just going to combine a fair number of my Cheat Sheets in no particular order. - ---- - -### The Penultimate Web Developer's Cheat Sheet - -I am literally just going to combine a fair number of my Cheat Sheets in no particular order. - -<figure><img src="https://cdn-images-1.medium.com/max/800/0*Cfl2fI-p4Y1XGAkS.png" class="graf-image" /></figure>### HTML: - - <!-- Document Summary --> - - <!DOCTYPE html> <!-- Tells the browser that HTML5 version of HTML to be recognized by the browser --> - - <html lang="en"></html> <!-- The HTML lang attribute is used to identify the language of text content on the web. This information helps search engines return language specific results, --> - - <head></head> <!-- Contains Information specific to the page like title, styles and scripts --> - - <title> - - - - - - - - - - - - - - - - - -

    ...
    - -

    - -
    - - - -
    - -
    - - - - and - - and - - - -
           
    -
    -    
    - - - -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - text - - - -
      - -
        - -
      • - -
        - -
        - -
        - - - - - - - - method="somefunction()" - - enctype="" - - autocomplete="" - - novalidate - - accept-charset="" - - target="" - -
        - - - - - - - - - - name="" - - width="" - - value="" - - size="" - - maxlength="" - - required="" - - step="" - - - - - - - - name="" - - size="" - - multiple - - required - - autofocus - - - - - - - - - -
        - - - - - - - - - - - - - - - - - - - - - - - - - - type="" - - height="" - - width="" - - usemap="" - - - - - - src="" - - width="" - - - -
        - -
        - -
        - -
        - - - -
        - -
        - - - -
        - -
        - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - " " Quotation Marks - " - - & & Ampersand - & - - < < Less than sign - < - - > > Greater than sign - > - -     Non-breaking space - - © © Copyright Symbol - © - - @ Ü @ symbol - @ - - • ö Small bullet - . - - ™ û Trademark Symbol - ™ - -
        - -### GIT - -
        - -### CSS - -
        - ---- - -### Bootstrap - ---- - -
        - -### Bash - -> Continued: - ---- - -
        - -### Python - -- Python is an interpreted, high-level and general-purpose, dynamically typed programming language -- It is also Object oriented, modular oriented and a scripting language. -- In Python, everything is considered as an Object. -- A python file has an extension of .py -- Python follows Indentation to separate code blocks instead of flower brackets({}). -- We can run a python file by the following command in cmd(Windows) or shell(mac/linux). -- `python ` - -#### By default, the python doesn't require any imports to run a python file - -### Create and execute a program - -1. Open up a terminal/cmd -2. Create the program: nano/cat > nameProgram.py -3. Write the program and save it -4. python nameProgram.py - -### Basic Datatypes - -
        ### Keywords - -
        ### Operators - -
        ### Basic Data Structures - -### List - -- List is a collection which is ordered and changeable. Allows duplicate members. -- Lists are created using square brackets: - - - - thislist = ["apple", "banana", "cherry"] - -- List items are ordered, changeable, and allow duplicate values. -- List items are indexed, the first item has index `[0]`, the second item has index `[1]` etc. -- The list is changeable, meaning that we can change, add, and remove items in a list after it has been created. -- To determine how many items a list has, use the `len()` function. -- A list can contain different data types: - - - - list1 = ["abc", 34, True, 40, "male"] - -- It is also possible to use the list() constructor when creating a new list - - - - thislist = list(("apple", "banana", "cherry")) # note the double round-brackets - -### Tuple - -- Tuple is a collection which is ordered and unchangeable. Allows duplicate members. -- A tuple is a collection which is ordered and unchangeable. -- Tuples are written with round brackets. - - - - thistuple = ("apple", "banana", "cherry") - -- Tuple items are ordered, unchangeable, and allow duplicate values. -- Tuple items are indexed, the first item has index `[0]`, the second item has index `[1]` etc. -- When we say that tuples are ordered, it means that the items have a defined order, and that order will not change. -- Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created. -- Since tuple are indexed, tuples can have items with the same value: -- Tuples allow duplicate values: - - - - thistuple = ("apple", "banana", "cherry", "apple", "cherry") - -- To determine how many items a tuple has, use the `len()`function: - - - - thistuple = ("apple", "banana", "cherry") - print(len(thistuple)) - -- To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple. - - - - thistuple = ("apple",) - print(type(thistuple)) - - #NOT a tuple - thistuple = ("apple") - print(type(thistuple)) - -- It is also possible to use the tuple() constructor to make a tuple. - - - - thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets - print(thistuple) - -### Set - -- Set is a collection which is unordered and unindexed. No duplicate members. -- A set is a collection which is both unordered and unindexed. - - - - thisset = {"apple", "banana", "cherry"} - -- Set items are unordered, unchangeable, and do not allow duplicate values. -- Unordered means that the items in a set do not have a defined order. -- Set items can appear in a different order every time you use them, and cannot be referred to by index or key. -- Sets are unchangeable, meaning that we cannot change the items after the set has been created. -- Duplicate values will be ignored. -- To determine how many items a set has, use the `len()` method. - - - - thisset = {"apple", "banana", "cherry"} - - print(len(thisset)) - -- Set items can be of any data type: - - - - set1 = {"apple", "banana", "cherry"} - set2 = {1, 5, 7, 9, 3} - set3 = {True, False, False} - set4 = {"abc", 34, True, 40, "male"} - -- It is also possible to use the `set()` constructor to make a set. - - - - thisset = set(("apple", "banana", "cherry")) # note the double round-brackets - -### Dictionary - -- Dictionary is a collection which is unordered and changeable. No duplicate members. -- Dictionaries are used to store data values in key:value pairs. -- Dictionaries are written with curly brackets, and have keys and values: - - - - thisdict = { - "brand": "Ford", - "model": "Mustang", - "year": 1964 - } - -- Dictionary items are presented in key:value pairs, and can be referred to by using the key name. - - - - thisdict = { - "brand": "Ford", - "model": "Mustang", - "year": 1964 - } - print(thisdict["brand"]) - -- Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created. -- Dictionaries cannot have two items with the same key. -- Duplicate values will overwrite existing values. -- To determine how many items a dictionary has, use the `len()` function. - - - - print(len(thisdict)) - -- The values in dictionary items can be of any data type - - - - thisdict = { - "brand": "Ford", - "electric": False, - "year": 1964, - "colors": ["red", "white", "blue"] - } - -### Conditional branching - - if condition: - pass - elif condition2: - pass - else: - pass - -### Loops - -Python has two primitive loop commands: - -1. while loops -2. for loops - -#### While loop - -- With the `while` loop we can execute a set of statements as long as a condition is true. -- Example: Print i as long as i is less than 6 - - - - i = 1 - while i < 6: - print(i) - i += 1 - -- The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1. -- With the `break` statement we can stop the loop even if the while condition is true -- With the continue statement we can stop the current iteration, and continue with the next. -- With the else statement we can run a block of code once when the condition no longer is true. - -#### For loop - -- A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). -- This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages. -- With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. - - - - fruits = ["apple", "banana", "cherry"] - for x in fruits: - print(x) - -- The for loop does not require an indexing variable to set beforehand. -- To loop through a set of code a specified number of times, we can use the range() function. -- The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. -- The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3). -- The else keyword in a for loop specifies a block of code to be executed when the loop is finished. - A nested loop is a loop inside a loop. -- The "inner loop" will be executed one time for each iteration of the "outer loop": - - - - adj = ["red", "big", "tasty"] - fruits = ["apple", "banana", "cherry"] - - for x in adj: - for y in fruits: - print(x, y) - -- for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error. - - - - for x in [0, 1, 2]: - pass - -### Function definition - - def function_name(): - return - -### Function call - - function_name() - -- We need not to specify the return type of the function. -- Functions by default return `None` -- We can return any datatype. - ---- - -
        - -### JavaScript - ---- - -
        - -### TypeScript - -
        - -### React - -
        - -### Node - -
        - -### JQuery - -
        - -### Markdown - -
        - -### JSON - -
        - -### Discover More - -Web-Dev-Hub -
        - -Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…bgoonz-blog.netlify.app
        - -
        - -By Bryan Guner on [June 29, 2021](https://medium.com/p/a02a423139a4). - -Canonical link - -August 31, 2021. diff --git a/notes/articles/medium/markdown/The-Penultimate-Web-Developer-s-Cheat.md b/notes/articles/medium/markdown/The-Penultimate-Web-Developer-s-Cheat.md deleted file mode 100644 index e244b76152..0000000000 --- a/notes/articles/medium/markdown/The-Penultimate-Web-Developer-s-Cheat.md +++ /dev/null @@ -1,628 +0,0 @@ -# The Penultimate Web Developer's Cheat Sheet - -I am literally just going to combine a fair number of my Cheat Sheets in no particular order. - ---- - -### The Penultimate Web Developer's Cheat Sheet - -I am literally just going to combine a fair number of my Cheat Sheets in no particular order. - -
        ### HTML: - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        ...
        - -

        - -
        - - - -
        - -
        - - - - and - - and - - - -
               
        -
        -    
        - - - -
        - - - - - - - - - - - - - - - - - - - - - - - - - - - - text - - - -
          - -
            - -
          • - -
            - -
            - -
            - - - -
            - - - - method="somefunction()" - - enctype="" - - autocomplete="" - - novalidate - - accept-charset="" - - target="" - -
            - - - - - - - - - - name="" - - width="" - - value="" - - size="" - - maxlength="" - - required="" - - step="" - - - - - - - - name="" - - size="" - - multiple - - required - - autofocus - - - - - - - - - -
            - - - - - - - - - - - - - - - - - - - - - - - - - - type="" - - height="" - - width="" - - usemap="" - - - - - - src="" - - width="" - - - -
            - -
            - -
            - -
            - - - -
            - -
            - - - -
            - -
            - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - " " Quotation Marks - " - - & & Ampersand - & - - < < Less than sign - < - - > > Greater than sign - > - -     Non-breaking space - - © © Copyright Symbol - © - - @ Ü @ symbol - @ - - • ö Small bullet - . - - ™ û Trademark Symbol - ™ - -
            - -### GIT: - -
            - -### CSS: - -
            - ---- - -### Bootstrap: - ---- - -
            - -### Bash: - -> Continued: - ---- - -
            - -### Python: - -- Python is an interpreted, high-level and general-purpose, dynamically typed programming language -- It is also Object oriented, modular oriented and a scripting language. -- In Python, everything is considered as an Object. -- A python file has an extension of .py -- Python follows Indentation to separate code blocks instead of flower brackets({}). -- We can run a python file by the following command in cmd(Windows) or shell(mac/linux). -- `python ` - -#### By default, the python doesn't require any imports to run a python file. - -### Create and execute a program - -1. Open up a terminal/cmd -2. Create the program: nano/cat > nameProgram.py -3. Write the program and save it -4. python nameProgram.py - -### Basic Datatypes - -
            ### Keywords - -
            ### Operators - -
            ### Basic Data Structures - -### List - -- List is a collection which is ordered and changeable. Allows duplicate members. -- Lists are created using square brackets: - - - - thislist = ["apple", "banana", "cherry"] - -- List items are ordered, changeable, and allow duplicate values. -- List items are indexed, the first item has index `[0]`, the second item has index `[1]` etc. -- The list is changeable, meaning that we can change, add, and remove items in a list after it has been created. -- To determine how many items a list has, use the `len()` function. -- A list can contain different data types: - - - - list1 = ["abc", 34, True, 40, "male"] - -- It is also possible to use the list() constructor when creating a new list - - - - thislist = list(("apple", "banana", "cherry")) # note the double round-brackets - -### Tuple - -- Tuple is a collection which is ordered and unchangeable. Allows duplicate members. -- A tuple is a collection which is ordered and unchangeable. -- Tuples are written with round brackets. - - - - thistuple = ("apple", "banana", "cherry") - -- Tuple items are ordered, unchangeable, and allow duplicate values. -- Tuple items are indexed, the first item has index `[0]`, the second item has index `[1]` etc. -- When we say that tuples are ordered, it means that the items have a defined order, and that order will not change. -- Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created. -- Since tuple are indexed, tuples can have items with the same value: -- Tuples allow duplicate values: - - - - thistuple = ("apple", "banana", "cherry", "apple", "cherry") - -- To determine how many items a tuple has, use the `len()`function: - - - - thistuple = ("apple", "banana", "cherry") - print(len(thistuple)) - -- To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple. - - - - thistuple = ("apple",) - print(type(thistuple)) - - #NOT a tuple - thistuple = ("apple") - print(type(thistuple)) - -- It is also possible to use the tuple() constructor to make a tuple. - - - - thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets - print(thistuple) - -### Set - -- Set is a collection which is unordered and unindexed. No duplicate members. -- A set is a collection which is both unordered and unindexed. - - - - thisset = {"apple", "banana", "cherry"} - -- Set items are unordered, unchangeable, and do not allow duplicate values. -- Unordered means that the items in a set do not have a defined order. -- Set items can appear in a different order every time you use them, and cannot be referred to by index or key. -- Sets are unchangeable, meaning that we cannot change the items after the set has been created. -- Duplicate values will be ignored. -- To determine how many items a set has, use the `len()` method. - - - - thisset = {"apple", "banana", "cherry"} - - print(len(thisset)) - -- Set items can be of any data type: - - - - set1 = {"apple", "banana", "cherry"} - set2 = {1, 5, 7, 9, 3} - set3 = {True, False, False} - set4 = {"abc", 34, True, 40, "male"} - -- It is also possible to use the `set()` constructor to make a set. - - - - thisset = set(("apple", "banana", "cherry")) # note the double round-brackets - -### Dictionary - -- Dictionary is a collection which is unordered and changeable. No duplicate members. -- Dictionaries are used to store data values in key:value pairs. -- Dictionaries are written with curly brackets, and have keys and values: - - - - thisdict = { - "brand": "Ford", - "model": "Mustang", - "year": 1964 - } - -- Dictionary items are presented in key:value pairs, and can be referred to by using the key name. - - - - thisdict = { - "brand": "Ford", - "model": "Mustang", - "year": 1964 - } - print(thisdict["brand"]) - -- Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created. -- Dictionaries cannot have two items with the same key. -- Duplicate values will overwrite existing values. -- To determine how many items a dictionary has, use the `len()` function. - - - - print(len(thisdict)) - -- The values in dictionary items can be of any data type - - - - thisdict = { - "brand": "Ford", - "electric": False, - "year": 1964, - "colors": ["red", "white", "blue"] - } - -### Conditional branching - - if condition: - pass - elif condition2: - pass - else: - pass - -### Loops - -Python has two primitive loop commands: - -1. while loops -2. for loops - -#### While loop - -- With the `while` loop we can execute a set of statements as long as a condition is true. -- Example: Print i as long as i is less than 6 - - - - i = 1 - while i < 6: - print(i) - i += 1 - -- The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1. -- With the `break` statement we can stop the loop even if the while condition is true -- With the continue statement we can stop the current iteration, and continue with the next. -- With the else statement we can run a block of code once when the condition no longer is true. - -#### For loop - -- A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). -- This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages. -- With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. - - - - fruits = ["apple", "banana", "cherry"] - for x in fruits: - print(x) - -- The for loop does not require an indexing variable to set beforehand. -- To loop through a set of code a specified number of times, we can use the range() function. -- The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. -- The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3). -- The else keyword in a for loop specifies a block of code to be executed when the loop is finished. - A nested loop is a loop inside a loop. -- The "inner loop" will be executed one time for each iteration of the "outer loop": - - - - adj = ["red", "big", "tasty"] - fruits = ["apple", "banana", "cherry"] - - for x in adj: - for y in fruits: - print(x, y) - -- for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error. - - - - for x in [0, 1, 2]: - pass - -### Function definition - - def function_name(): - return - -### Function call - - function_name() - -- We need not to specify the return type of the function. -- Functions by default return `None` -- We can return any datatype. - ---- - -
            - -### JavaScript: - ---- - -
            - -### TypeScript: - -
            - -### React: - -
            - -### Node: - -
            - -### JQuery: - -
            - -### Markdown: - -
            - -### JSON: - -
            - -### Discover More: - -Web-Dev-Hub -
            - -Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…bgoonz-blog.netlify.app
            - -
            - -By Bryan Guner on [June 29, 2021](https://medium.com/p/a02a423139a4). - -Canonical link - -August 6, 2021. diff --git a/notes/articles/medium/markdown/These-Are-A-Few-Of-My-Favorite-Things.md b/notes/articles/medium/markdown/These-Are-A-Few-Of-My-Favorite-Things.md deleted file mode 100644 index bb2695437a..0000000000 --- a/notes/articles/medium/markdown/These-Are-A-Few-Of-My-Favorite-Things.md +++ /dev/null @@ -1,537 +0,0 @@ -# These Are A Few Of My Favorite Things - -A web development student's declassified school survival guide. - ---- - -### These Are A Few Of My Favorite Things - -#### A web development student's declassified school survival guide. - -
            Photo by Christin Hume on Unsplash
            Photo by Christin Hume on Unsplash
            A list of all of my articles to link to future posts -
            - -You should probably skip this one… seriously it's just for internal use! - -Also here's an even better list by someone I don't know but would be doing you a disservice by failing to include… **There's very little overlap so you should probably read both :** - -25 Free Resources to Learn Web Development -
            - -Start where you are, use what you have, and do what you can.medium.com
            - -
            ### Disclaimer: This guide roughly goes in reverse order of awesomeness… i.e. you have to scroll to get to the coolest content… sorry not sorry - ---- - -> UPDATE: - -### 12.)Bit.Dev: - -
            Bit.dev **the world's best and only component marketplace solution provided as a service**. It's enterprise-grade in every way and provides all features out of the box. Bit empowers organizations with a "Lego-box" where all developers can push, discover, and reuse every component. - -This means much faster development, less time and effort spent re-inventing the wheel, and 100% focus on innovation. - -### What's the game-changer? - -- **Enterprise-grade component hub** with all features out of the box. -- **All the organization's reusable code** in **one central place**. -- **Semantic search** and **discoverability** for components — find **in seconds**. **Smart filtering** for component **weight**, **dependencies**, **labels** and more. -- **Automated visual documentation** for components- generated from the code, **always updated**, and rich with props, API reference, **visually rendered** examples, and **customizable** with all the latest techs like MDX. -- **View Adoption Metrics** to understand how and where components are used and the impact of components across teams and apps. -- **Super easy for devs to push** reusable components to the hub with Bit right from any codebase. -- **Built-in world-class registry** that supports npm, yarn, and Bit. -- **Give leadership visibility** to all tech assets they have. Make it easy for product managers and others to plan new features based on the available components, so **cut delivery times** and **ensure consistency**. -- **Get fast automated updates** to components across all projects. -- **Less code is reinvented**, and **more innovation is delivered**. - -Here are 4 use-cases for gaining a fast yet meaningful impact with Bit. These reflect how many world-class teams, whose products you use daily, chose to unlock the benefits of Bit to better build frontend applications together. - -1. **Micro Frontends (Autonomous Teams)** -2. **Component Marketplace** -3. **Design Systems (Distribution & Adoption)** -4. **Rapid App Development and Delivery** - -To learn more about how Bit can help unlock these benefits for you just drop a ping to our experts and we'd be happy to share our experience. - -### 11.)Dillinger: - -Online Markdown Editor - Dillinger, the Last Markdown Editor ever. -
            - -Dillinger is an online cloud based HTML5 filled Markdown Editor. Sync with Dropbox, Github, Google Drive or OneDrive…dillinger.io
            - -Dillinger is a cloud-enabled, mobile-ready, offline-storage compatible, AngularJS-powered HTML5 Markdown editor. - -- Type some Markdown on the left -- See HTML in the right - -
            - -### Features - -- Import a HTML file and watch it magically convert to Markdown -- Drag and drop images (requires your Dropbox account be linked) -- Import and save files from GitHub, Dropbox, Google Drive and One Drive -- Drag and drop markdown and HTML files into Dillinger -- Export documents as Markdown, HTML and PDF - -Markdown is a lightweight markup language based on the formatting conventions that people naturally use in email. As John Gruber writes on the Markdown site - -> _The overriding design goal for Markdown's formatting syntax is to make it as readable as possible. The idea is that a Markdown-formatted document should be publishable as-is, as plain text, without looking like it's been marked up with tags or formatting instructions._ - -This text you see here is _actually_ written in Markdown! To get a feel for Markdown's syntax, type some text into the left window and watch the results in the right. - -Dillinger was first designed and developed by @joemccann because he needed a decent Markdown editor. 2014, it got redesigned and coded by @mrtnbroder. - -Dillinger is a 100% open source project so fork the code and contribute! - -Follow Dillinger on Twitter at @dillingerapp. - -### 1.) Codepen: - -#### For quick prototyping and experimentation: - -### FAQ: - -You write code in the editors, the results of that code are shown to you in the preview area. It's simple, but powerful! Beginners and experts alike work best when they can see the results of what they are doing as they do it. - -### How do you make a Pen? - -You must have an account and be logged in, then you head to the Pen Editor, and save it when you are ready. - -### How do I save changes? - -After the first save, changes you make in the Pen Editor are automatically saved on a timer, but that is a Pen-level setting you can change if you wish. - -You can also fork a Pen to make another copy. - -### How do I share a Pen? - -By default, Pens are public, meaning the Pen will have a URL you can share anywhere you like and anyone will be able to see it. You could share it to Twitter, Facebook, over email… anywhere you like. - -Just by virtue of saving a public Pen, you're also making it public to the world of CodePen. Your followers will see it in their following page and it will be available in global search. - -**Important Concept:** You can make Pens private as well. A private Pen will not show up in global search (we'll even try to hide it from search engines) and won't be on your public profile or anywhere else. _But you can still share a private Pen._ If you give someone the URL, they'll still be able to see it. - ---- - -### 2.) Free Code Camp: - -
            - -More than 40,000 people have gotten developer jobs after completing this — including at big companies like Google and Microsoft. If you are new to programming, we recommend you start at the beginning and earn these certifications in order. To earn each certification, build its 5 required projects and get all their tests to pass. You can add these certifications to your résumé or LinkedIn. But more important than the certifications is the practice you get along the way. If you feel overwhelmed, that is normal. Programming is hard. Practice is the key. Practice, practice, practice. And this curriculum will give you thousands of hours of hands-on programming practice. - -And if you want to learn more math and computer science theory, we also have thousands of hours of video courses on freeCodeCamp's YouTube channel. If you want to get a developer job or freelance clients, programming skills will be just part of the puzzle. You also need to build your personal network and your reputation as a developer. You can do this on Twitter and GitHub, and also on the freeCodeCamp forum. - ---- - -### 3.) Cloudconvert(and Pandoc): - -CloudConvert is a German-based conversion site that was launched in 2012. Today, it's one of the most popular format converters, boasting of over 10,000 customers and at least four files per second. - -CloudConvert -
            - -CloudConvert is your Swiss army knife for file conversions. We support nearly all audio, video, document, ebook…cloudconvert.com
            - -Just upload the file you want to convert and CloudConvert gives you a list of file types it can convert it to. It can then send that file directly to your Dropbox or Google Drive account. It's a pretty simple process and if you don't need to convert between file types very often, CloudConvert's handy to keep around. - -
            Lot's of features
            Lot's of features
            - -
            - -CloudConvert transforms a file from one format into another. It recognizes files in more than 200 different formats, and connects with Box, Dropbox, Google Drive, and OneDrive. This makes CloudConvert an essential web utility for anyone who uses a Chromebook. - -CloudConvert supports over 200 formats from audio, spreadsheet, video, document, image, eBook, and presentation. And yes, CloudConvert is a safe platform that uses SSL encryption. - ---- - -### 4.) Pandoc: - -Pandoc dubs itself a "markup format" converter. It can take a document in one of the supported formats and convert only its markup to another format. Maintaining the look and feel of the document is not a priority. - -Plug-ins for custom formats can also be written in Lua, which has been used to create an exporting tool for the Journal Article Tag Suite, for example - -An included CiteProc option allows Pandoc to use bibliographic data from reference management software in any of four formats: BibTeX, BibLaTeX, CSL JSON or CSL YAML. The information is automatically transformed into a citation in various styles (such as APA, Chicago, or MLA) using an implementation of the Citation Style Language. This allows the program to serve as a simpler alternative to LaTeX for producing academic writing - -### Supported file formats - -Pandoc's most thoroughly supported file format is an extended version of Markdown but it can also read many other forms of: - -- Creole -- DocBook -- EPUB -- FictionBook (FB2) -- Haddock -- HTML -- Jira wiki markup -- Journal Article Tag Suite (JATS) -- JSON -- LaTeX -- Lightweight markup language -- man -- Markdown: Strict, CommonMark, GitHub Flavored Markdown (GFM), MultiMarkdown (MMD) and Markdown Extra (PHP Extra) variants -- OpenDocument (ODT) -- OPML -- Office Open XML: Microsoft Word variant -- Org-mode -- reStructuredText -- Textile -- txt2tags (t2t) -- Wiki markup: MediaWiki, Muse, TikiWiki, TWiki and Vimwiki variants - -It can create files in the following formats, which are not necessarily the same as the input formats: - -- AsciiDoc -- ConTeXt -- DocBook: Versions 4 and 5 -- EPUB: Versions 2 and 3 -- FictionBook (FB2) -- Haddock -- HTML: HTML4 and HTML5 variants, respectively compliant with XHTML 1.0 Transitional and XHTML Strict -- InDesign ICML -- Jira wiki markup -- Journal Article Tag Suite (JATS) -- JSON -- LaTeX -- man -- Markdown: Strict, CommonMark, GitHub Flavored Markdown (GFM), MultiMarkdown (MMD) and Markdown Extra (PHP Extra) variants -- OpenDocument (ODT/ODF) -- OPML -- Office Open XML: Microsoft Word and Microsoft PowerPoint variants -- Org-mode -- PDF (needs a third-party add-on like ConTeXt, `pdfroff`, `wkhtmltopdf`, `weasyprint` or `prince`) -- Plain text -- reStructuredText -- Rich Text Format (RTF) -- TEI -- Texinfo -- Textile -- Web-based slideshows: LaTeX Beamer, Slideous, Slidy, DZSlides, reveal.js and S5 variants -- Wiki markup: DokuWiki, MediaWiki, Muse, TikiWiki, TWiki and Vimwiki variants - ---- - -### 3.) Code Sandbox: - -CodeSandbox works with JavaScript (including TypeScript) and has front-end and full-stack support. - -Codesandbox client templates for React, Vue, Angular, Preact, Svelte, Dojo, CX, Reason, as well as vanilla JavaScript that uses Parcel, and one for static (HTML, JavaScript, CSS) projects. - -Pre-configured: Node.js, Angular, Adonis, Gatsby, Marko, Nuxt, Next, Sapper, Apollo, Ember, Nest, Styleguidist, MDX Deck, Gridsome, Quasar, Docusaurus, and Vuepress. - ---- - -### 4.) DirHTML - -Dirhtml creates HTML files from a directory list using the GUI or command line, optionally including HTML code of your own design at any point in generated file(s). - -#### Installation - -Dirhtml is not installable, just unzip and run dirhtml.exe. - -
            Problems, questions? Email the author: dirhtml@enware.info - -Dirhtml (Windows) -
            - -Dirhtml is a lite application that creates HTML files listing the content of a certain folder with links to each file…dirhtml.en.uptodown.com
            - -Dirhtml is a lite application that creates HTML files listing the content of a certain folder with links to each file automatically, - -Its interface is simple and beautiful, it's not difficult to understand, you'll be able to use it with no problems. - -It features some interesting options such as content filter, different templates, and designs for the output HTML file, add your own code to the template… You can also choose if the information about the file will be featured on the webpage or not if you prefer to hide it. - -Dirhtml is a good choice if you are planning to create a directory of your files for your website. It is perfect if you don't need extra options. - -It's how I create site navigation as it appears here: - -Site Navigation -
            - -Edit descriptionlambda-resources.netlify.app
            - -This enables me to take a folder full of my notes … no matter the file extension and rapidly turn the contents of that folder into a static documentation site… not to mention that having (potentially) thousands of nonbroken hyperlinks between pages in your website will help boost your SEO rating. - -
            - ---- - -### 5.) **Google Colaboratory** - -Google Colaboratory -
            - -Edit descriptioncolab.research.google.com
            - -### The Basics - -**What is Colaboratory?** - -Colaboratory, or "Colab" for short, is a product from Google Research. Colab allows anybody to write and execute arbitrary python code through the browser and is especially well suited to machine learning, data analysis, and education. More technically, Colab is a hosted Jupyter notebook service that requires no setup to use, while providing free access to computing resources including GPUs. - -**Is it really free to use?** - -Yes. Colab is free to use. - -**Seems too good to be true. What are the limitations?** - -Colab resources are not guaranteed and not unlimited, and the usage limits sometimes fluctuate. This is necessary for Colab to be able to provide resources for free. For more details, see Resource Limits - -Users who are interested in more reliable access to better resources may be interested in Colab Pro. - -**What is the difference between Jupyter and Colab?** - -Jupyter is the open-source project on which Colab is based. Colab allows you to use and share Jupyter notebooks with others without having to download, install, or run anything. - -Google Colaboratory -
            - -Edit descriptioncolab.research.google.com
            - -### 6.) Github Gists: - -Here's a repo where I backup my gists… I keep hundreds: - -bgoonz/my-gists -
            - -Contribute to bgoonz/my-gists development by creating an account on GitHub.github.com
            - ---- - -### 7.) Screen To Gif: - -NickeManarin/ScreenToGif -
            - -This tool allows you to record a selected area of your screen, live feed from your webcam or live drawings from a…github.com
            - -#### Recorders - -- Use ScreenToGif to record your screen, your webcam feed or sketch board drawings. - -#Screen - -
            This is the default screen recorder UI. You simply move this window on top of the content that you want to record. - -
            This is the new recorder UI, which lets you click and drag to select an area of your screen. -You can also switch to the window and screen modes. - -- Use the record, pause, discard or stop buttons to control your capture. -- Select the capture frequency mode (manual, normal in fps, timelapse in fpm/fph). -- Older UI -- Drag or resize the window to adjust what you want to capture. -- Type the exact size of the capture region. -- Drag the crosshair button and drop it on top of a window to move the recorder to capture that. -- Newer UI Beta -- Enter selection mode, which lets you select a region, a window or an entire screen to capture. - ---- - -#Webcam - -
            This is the webcam recorder. - -- Use the record, pause, discard or stop buttons to control your capture. -- Select the maximum FPS of the capture. -- Resize the window to adjust the size of the capture. - ---- - -#Sketch board - -
            The board recorder lets you capture your drawings automatically as you draw them. - -- Enable the auto-capture or press Ctrl to toggle (_pauses_ or _captures_ it, depending if the auto-capture is enabled or disabled). -- Select the maximum FPS of the capture. -- Resize the window to adjust the size of the capture. - ---- - -### #Editor - -
            This is the editor, where you can edit your recordings and export it to gif, apng, video, project, images and psd. - -- File -- Start a new recording or open a media (videos or images) or project file. -- Insert a new recording or media file (videos or images) into an existing project. -- Open recent projects. -- Export your project to: -- Gif -- Apng -- Video -- Image -- PSD -- ScreenToGif project -- Basic controls -- Undo, redo or reset your edits. -- Copy, cut and paste frames. -- Select multiple frames or browse to a specific frame. -- Preview the playback of the animation. -- Frame manipulation -- Delete selected frames. -- Remove duplicates. -- Reduce framerate. -- Delete all previous or all next frames. -- Reverse, apply yoyo (forwards and backwards) or move frames around. -- Alter the delay of the frames (override, increase/decrease or scale). -- Add title frames. -- Add transitions (fade or slide effects). -- Image manipulation -- Resize, crop or flip/rotate. -- Add overlays: -- Captions/text. -- Drawings or shapes. -- Key strokes or mouse clicks. -- Borders, shadows, and obfuscation (pixelate). -- Watermarks (pick your own image). -- Cinemagraph (select parts of the animation to stay static or move). - ---- - -### 8. Traversy Media (Free) - --source: https://codeburst.io/8-websites-you-should-visit-to-learn-web-development-620e93b3f1c5 - -Traversy media is a youtube channel created by Brad Traversy. **His youtube channel covers nearly every topic regarding web development, from HTML, CSS, and Javascript to all the different frameworks and libraries (Sass, Bootstrap, Angular, React, Vue Js).** - -#### While I am at it I will list some youtube videos/channels that I think provide amazing content … just for the love of sharing knowledge. - ---- - -### 9.) Stackbit: - -I am currently building myself a new blog site… I sometimes develop it locally in vscode… but there's no doubt that it took something very similar to it's present form in a GUI! - -https://bgoonz-blog.netlify.app/ - -
            Stackbit takes all the tools you'd need for a site's stack (theme, static site generator, CMS, and deployment) and quickly bundles them together for you. It offers options in each category, so you can mix and match the tools in your stack that best suit your needs. - -At this point, you may be thinking, Ok, but "fast" is a relative term in this space… how "fast" are we really talking here? - -Great question. Let me put it to you this way: you could literally throw a HotPocket in the microwave, go build an incredibly sleek JAMstack site, and you'd still be waiting for your food to be cool enough to eat. - -### Site Preview - -The preview of your site in Stackbit is generated by the development server of your static-site-generator such as Gatsby or Jekyll. Because the preview is served by the SSG development server, any changes to site's content and code are immediately reflected in the preview. To show you the preview Stackbit runs the development server of your SSG and routes the site pages to your browser. - -### Running Preview - -Stackbit runs the following steps to show you the preview of your site: - -
            1. It clones your site's repository -2. It checks-out the `preview` branch -3. It installs your site dependencies depending on your static site generator (e.g., `npm install` for Node based SSGs such as Gatsby and Next.js, and `bundle install` for Jekyll) -4. It runs your static site generator's development server (e.g.: `gatsby develop` for Gatsby, and `bundle exec jekyll serve` for Jekyll). -5. It routes any page requests made from your browser to SSG's development server and returns responses back to your browser, as if you are developing your site locally on your local machine. - -For example, suppose your site uses Gatsby. In that case, after cloning your repository, checking out the `preview` branch, and installing dependencies, Stackbit executes `gatsby develop` in its preview-server to start Gatsby's development server and then routes page requests from your browser to that development server running internally on `http://localhost`. - -If your site uses Hugo, Stackbit executes `hugo server` and routes page requests to Hugo's development server running internally on `http://localhost`. - -You can see the logs of how Stackbit pulls your repository, installs dependencies, and runs your SSG's development server by clicking on the "Logs" button in the "Advanced Tools" bottom bar: - -
            ### Preview Updates - -Because the preview is served by the SSG development server, any changes to site's content and code are immediately reflected in the preview. - -Your SSG's development server should listen to content changes and respond to them by refreshing any opened browser sessions via live-reload or HMR. Most of the static-site-generators have these functionalities enabled by default, so you don't have to do anything. - -Due to the nature of static site generators and how their development server work, any changes made to the code, or the content are immediately picked up by the SSG and reflected in the browser. - -Of course, in order for Stackbit to show you the preview of your site, your SSG's development server must work without crashing. - ---- - -### 10.) File Locator Pro: - -FileLocator is a search utility for Windows - -First things first, Windows Search can't find a thing. For anyone used to Mac OS X or Linux and having access to advanced search functionality on their computers, Windows Search (formerly Windows Desktop Search) is a huge disappointment. - -Just watch how quickly it finds files by name in a 20GB folder! - -
            FileLocator Lite is free for personal and commercial use, although commercial use requires a per-user registration after a month. - -The user interface and experience is as good as it gets in an advanced program aimed at experienced users. The Pro version adds more controllers, but they can all be safely ignored unless you need something specific. The main program window opens up with three main input fields: search by file name or file contents, and where to look for the file. - -The true power of FileLocator is that it can search inside any kind of file to find what you're looking for. Other search programs will only go through files it assumes the user is looking for. - -However, you'll need FileLocator if you're looking for something inside an unusual document format, a string from a program, software source-code, your browser cache, or anything else really. Note that only the Pro version can search inside compressed archives like ZIP. - -In the search result section, you can not only see a list of files that match your search query; you can see the line number and line content where the match is made. This little feature alone takes FileLocator a few notches up and beyond their meager competition from the Windows search utility. - -- Source: - -FileLocator Lite and Pro review -
            - -Find "everything" with Lite Finding even more and do it faster with Pro Windows and tabs management, and keyboard…www.ctrl.blog
            - ---- - -### Rapid Fire Bonus Inclusions: - -### Notion: - -The best note taking app ever: - -Notion - The all-in-one workspace for your notes, tasks, wikis, and databases. -
            - -A new tool that blends your everyday work apps into one. It's the all-in-one workspace for you and your team.www.notion.so
            - -
            - ---- - -### Team wiki - -Turn your tribal knowledge into easy-to-find answers. - -
            Replaces - -
            ### Projects & tasks - -Kanban boards, tables, lists, and more. Customize any workflow. - -
            Replaces - -
            ### Notes & docs - -Systems that keep notes organized. Add any type of content. - -
            Replaces - -
            - ---- - -### Gitbook: - -GitBook - Where software teams break knowledge silos. -
            - -Centralize your knowledge and collaborate with your team in a single, organized workspace for increased efficiency…www.gitbook.com
            - -GitBook started as a simple open source tool designed to let developers quickly publish content from a git repo. We've changed a bunch since then, but fundamentally we've stayed true to the vision of empowering software teams to document and distribute their knowledge. - -Not only does this tool allow you to seamlessly create documentation and notes in perfect synchrony with the git repo of your choice .. you can also import/export html, markdown and pdf documents and the cherry on top… it turns your notes into a beautiful website…. 11/10 would recommend. - -Closure-and-Scope -
            - -Variables are used to store information to be referenced and manipulated in a computer program. A variable's sole…bryan-guner.gitbook.io
            - -If you're familiar with facebook's opensource docusaurous … this is a lot like that if it were way better and much easier… Also for no extra cost to you… they don't spy on you… sell your data or help influence foreign/domestic elections. … - -
            - -By Bryan Guner on [May 28, 2021](https://medium.com/p/82e8b6e61879). - -Canonical link - -August 31, 2021. diff --git a/notes/articles/medium/markdown/These-Are-A-Few-Of-My-Favorite.md b/notes/articles/medium/markdown/These-Are-A-Few-Of-My-Favorite.md deleted file mode 100644 index 9c02db121f..0000000000 --- a/notes/articles/medium/markdown/These-Are-A-Few-Of-My-Favorite.md +++ /dev/null @@ -1,537 +0,0 @@ -# These Are A Few Of My Favorite Things - -A web development student's declassified school survival guide. - ---- - -### These Are A Few Of My Favorite Things - -#### A web development student's declassified school survival guide. - -
            Photo by Christin Hume on Unsplash
            Photo by Christin Hume on Unsplash
            A list of all of my articles to link to future posts -
            - -You should probably skip this one… seriously it's just for internal use! - -Also here's an even better list by someone I don't know but would be doing you a disservice by failing to include… **There's very little overlap so you should probably read both :** - -25 Free Resources to Learn Web Development -
            - -Start where you are, use what you have, and do what you can.medium.com
            - -
            ### Disclaimer: This guide roughly goes in reverse order of awesomeness… i.e. you have to scroll to get to the coolest content… sorry not sorry - ---- - -> UPDATE: - -### 12.)Bit.Dev: - -
            Bit.dev **the world's best and only component marketplace solution provided as a service**. It's enterprise-grade in every way and provides all features out of the box. Bit empowers organizations with a "Lego-box" where all developers can push, discover, and reuse every component. - -This means much faster development, less time and effort spent re-inventing the wheel, and 100% focus on innovation. - -### What's the game-changer? - -- **Enterprise-grade component hub** with all features out of the box. -- **All the organization's reusable code** in **one central place**. -- **Semantic search** and **discoverability** for components — find **in seconds**. **Smart filtering** for component **weight**, **dependencies**, **labels** and more. -- **Automated visual documentation** for components- generated from the code, **always updated**, and rich with props, API reference, **visually rendered** examples, and **customizable** with all the latest techs like MDX. -- **View Adoption Metrics** to understand how and where components are used and the impact of components across teams and apps. -- **Super easy for devs to push** reusable components to the hub with Bit right from any codebase. -- **Built-in world-class registry** that supports npm, yarn, and Bit. -- **Give leadership visibility** to all tech assets they have. Make it easy for product managers and others to plan new features based on the available components, so **cut delivery times** and **ensure consistency**. -- **Get fast automated updates** to components across all projects. -- **Less code is reinvented**, and **more innovation is delivered**. - -Here are 4 use-cases for gaining a fast yet meaningful impact with Bit. These reflect how many world-class teams, whose products you use daily, chose to unlock the benefits of Bit to better build frontend applications together. - -1. **Micro Frontends (Autonomous Teams)** -2. **Component Marketplace** -3. **Design Systems (Distribution & Adoption)** -4. **Rapid App Development and Delivery** - -To learn more about how Bit can help unlock these benefits for you just drop a ping to our experts and we'd be happy to share our experience. - -### 11.)Dillinger: - -Online Markdown Editor - Dillinger, the Last Markdown Editor ever. -
            - -Dillinger is an online cloud based HTML5 filled Markdown Editor. Sync with Dropbox, Github, Google Drive or OneDrive…dillinger.io
            - -Dillinger is a cloud-enabled, mobile-ready, offline-storage compatible, AngularJS-powered HTML5 Markdown editor. - -- Type some Markdown on the left -- See HTML in the right - -
            - -### Features - -- Import a HTML file and watch it magically convert to Markdown -- Drag and drop images (requires your Dropbox account be linked) -- Import and save files from GitHub, Dropbox, Google Drive and One Drive -- Drag and drop markdown and HTML files into Dillinger -- Export documents as Markdown, HTML and PDF - -Markdown is a lightweight markup language based on the formatting conventions that people naturally use in email. As John Gruber writes on the Markdown site - -> _The overriding design goal for Markdown's formatting syntax is to make it as readable as possible. The idea is that a Markdown-formatted document should be publishable as-is, as plain text, without looking like it's been marked up with tags or formatting instructions._ - -This text you see here is _actually_ written in Markdown! To get a feel for Markdown's syntax, type some text into the left window and watch the results in the right. - -Dillinger was first designed and developed by @joemccann because he needed a decent Markdown editor. 2014, it got redesigned and coded by @mrtnbroder. - -Dillinger is a 100% open source project so fork the code and contribute! - -Follow Dillinger on Twitter at @dillingerapp. - -### 1.) Codepen: - -#### For quick prototyping and experimentation: - -### FAQ: - -You write code in the editors, the results of that code are shown to you in the preview area. It's simple, but powerful! Beginners and experts alike work best when they can see the results of what they are doing as they do it. - -### How do you make a Pen? - -You must have an account and be logged in, then you head to the Pen Editor, and save it when you are ready. - -### How do I save changes? - -After the first save, changes you make in the Pen Editor are automatically saved on a timer, but that is a Pen-level setting you can change if you wish. - -You can also fork a Pen to make another copy. - -### How do I share a Pen? - -By default, Pens are public, meaning the Pen will have a URL you can share anywhere you like and anyone will be able to see it. You could share it to Twitter, Facebook, over email… anywhere you like. - -Just by virtue of saving a public Pen, you're also making it public to the world of CodePen. Your followers will see it in their following page and it will be available in global search. - -**Important Concept:** You can make Pens private as well. A private Pen will not show up in global search (we'll even try to hide it from search engines) and won't be on your public profile or anywhere else. _But you can still share a private Pen._ If you give someone the URL, they'll still be able to see it. - ---- - -### 2.) Free Code Camp: - -
            - -More than 40,000 people have gotten developer jobs after completing this — including at big companies like Google and Microsoft. If you are new to programming, we recommend you start at the beginning and earn these certifications in order. To earn each certification, build its 5 required projects and get all their tests to pass. You can add these certifications to your résumé or LinkedIn. But more important than the certifications is the practice you get along the way. If you feel overwhelmed, that is normal. Programming is hard. Practice is the key. Practice, practice, practice. And this curriculum will give you thousands of hours of hands-on programming practice. - -And if you want to learn more math and computer science theory, we also have thousands of hours of video courses on freeCodeCamp's YouTube channel. If you want to get a developer job or freelance clients, programming skills will be just part of the puzzle. You also need to build your personal network and your reputation as a developer. You can do this on Twitter and GitHub, and also on the freeCodeCamp forum. - ---- - -### 3.) Cloudconvert(and Pandoc): - -CloudConvert is a German-based conversion site that was launched in 2012. Today, it's one of the most popular format converters, boasting of over 10,000 customers and at least four files per second. - -CloudConvert -
            - -CloudConvert is your Swiss army knife for file conversions. We support nearly all audio, video, document, ebook…cloudconvert.com
            - -Just upload the file you want to convert and CloudConvert gives you a list of file types it can convert it to. It can then send that file directly to your Dropbox or Google Drive account. It's a pretty simple process and if you don't need to convert between file types very often, CloudConvert's handy to keep around. - -
            Lot's of features
            Lot's of features
            - -
            - -CloudConvert transforms a file from one format into another. It recognizes files in more than 200 different formats, and connects with Box, Dropbox, Google Drive, and OneDrive. This makes CloudConvert an essential web utility for anyone who uses a Chromebook. - -CloudConvert supports over 200 formats from audio, spreadsheet, video, document, image, eBook, and presentation. And yes, CloudConvert is a safe platform that uses SSL encryption. - ---- - -### 4.) Pandoc: - -Pandoc dubs itself a "markup format" converter. It can take a document in one of the supported formats and convert only its markup to another format. Maintaining the look and feel of the document is not a priority. - -Plug-ins for custom formats can also be written in Lua, which has been used to create an exporting tool for the Journal Article Tag Suite, for example - -An included CiteProc option allows Pandoc to use bibliographic data from reference management software in any of four formats: BibTeX, BibLaTeX, CSL JSON or CSL YAML. The information is automatically transformed into a citation in various styles (such as APA, Chicago, or MLA) using an implementation of the Citation Style Language. This allows the program to serve as a simpler alternative to LaTeX for producing academic writing - -### Supported file formats - -Pandoc's most thoroughly supported file format is an extended version of Markdown but it can also read many other forms of: - -- Creole -- DocBook -- EPUB -- FictionBook (FB2) -- Haddock -- HTML -- Jira wiki markup -- Journal Article Tag Suite (JATS) -- JSON -- LaTeX -- Lightweight markup language -- man -- Markdown: Strict, CommonMark, GitHub Flavored Markdown (GFM), MultiMarkdown (MMD) and Markdown Extra (PHP Extra) variants -- OpenDocument (ODT) -- OPML -- Office Open XML: Microsoft Word variant -- Org-mode -- reStructuredText -- Textile -- txt2tags (t2t) -- Wiki markup: MediaWiki, Muse, TikiWiki, TWiki and Vimwiki variants - -It can create files in the following formats, which are not necessarily the same as the input formats: - -- AsciiDoc -- ConTeXt -- DocBook: Versions 4 and 5 -- EPUB: Versions 2 and 3 -- FictionBook (FB2) -- Haddock -- HTML: HTML4 and HTML5 variants, respectively compliant with XHTML 1.0 Transitional and XHTML Strict -- InDesign ICML -- Jira wiki markup -- Journal Article Tag Suite (JATS) -- JSON -- LaTeX -- man -- Markdown: Strict, CommonMark, GitHub Flavored Markdown (GFM), MultiMarkdown (MMD) and Markdown Extra (PHP Extra) variants -- OpenDocument (ODT/ODF) -- OPML -- Office Open XML: Microsoft Word and Microsoft PowerPoint variants -- Org-mode -- PDF (needs a third-party add-on like ConTeXt, `pdfroff`, `wkhtmltopdf`, `weasyprint` or `prince`) -- Plain text -- reStructuredText -- Rich Text Format (RTF) -- TEI -- Texinfo -- Textile -- Web-based slideshows: LaTeX Beamer, Slideous, Slidy, DZSlides, reveal.js and S5 variants -- Wiki markup: DokuWiki, MediaWiki, Muse, TikiWiki, TWiki and Vimwiki variants - ---- - -### 3.) Code Sandbox: - -CodeSandbox works with JavaScript (including TypeScript) and has front-end and full-stack support. - -Codesandbox client templates for React, Vue, Angular, Preact, Svelte, Dojo, CX, Reason, as well as vanilla JavaScript that uses Parcel, and one for static (HTML, JavaScript, CSS) projects. - -Pre-configured: Node.js, Angular, Adonis, Gatsby, Marko, Nuxt, Next, Sapper, Apollo, Ember, Nest, Styleguidist, MDX Deck, Gridsome, Quasar, Docusaurus, and Vuepress. - ---- - -### 4.) DirHTML - -Dirhtml creates HTML files from a directory list using the GUI or command line, optionally including HTML code of your own design at any point in generated file(s). - -#### Installation - -Dirhtml is not installable, just unzip and run dirhtml.exe. - -
            Problems, questions? Email the author: dirhtml@enware.info - -Dirhtml (Windows) -
            - -Dirhtml is a lite application that creates HTML files listing the content of a certain folder with links to each file…dirhtml.en.uptodown.com
            - -Dirhtml is a lite application that creates HTML files listing the content of a certain folder with links to each file automatically, - -Its interface is simple and beautiful, it's not difficult to understand, you'll be able to use it with no problems. - -It features some interesting options such as content filter, different templates, and designs for the output HTML file, add your own code to the template… You can also choose if the information about the file will be featured on the webpage or not if you prefer to hide it. - -Dirhtml is a good choice if you are planning to create a directory of your files for your website. It is perfect if you don't need extra options. - -It's how I create site navigation as it appears here: - -Site Navigation -
            - -Edit descriptionlambda-resources.netlify.app
            - -This enables me to take a folder full of my notes … no matter the file extension and rapidly turn the contents of that folder into a static documentation site… not to mention that having (potentially) thousands of nonbroken hyperlinks between pages in your website will help boost your SEO rating. - -
            - ---- - -### 5.) **Google Colaboratory** - -Google Colaboratory -
            - -Edit descriptioncolab.research.google.com
            - -### The Basics - -**What is Colaboratory?** - -Colaboratory, or "Colab" for short, is a product from Google Research. Colab allows anybody to write and execute arbitrary python code through the browser and is especially well suited to machine learning, data analysis, and education. More technically, Colab is a hosted Jupyter notebook service that requires no setup to use, while providing free access to computing resources including GPUs. - -**Is it really free to use?** - -Yes. Colab is free to use. - -**Seems too good to be true. What are the limitations?** - -Colab resources are not guaranteed and not unlimited, and the usage limits sometimes fluctuate. This is necessary for Colab to be able to provide resources for free. For more details, see Resource Limits - -Users who are interested in more reliable access to better resources may be interested in Colab Pro. - -**What is the difference between Jupyter and Colab?** - -Jupyter is the open-source project on which Colab is based. Colab allows you to use and share Jupyter notebooks with others without having to download, install, or run anything. - -Google Colaboratory -
            - -Edit descriptioncolab.research.google.com
            - -### 6.) Github Gists: - -Here's a repo where I backup my gists… I keep hundreds: - -bgoonz/my-gists -
            - -Contribute to bgoonz/my-gists development by creating an account on GitHub.github.com
            - ---- - -### 7.) Screen To Gif: - -NickeManarin/ScreenToGif -
            - -This tool allows you to record a selected area of your screen, live feed from your webcam or live drawings from a…github.com
            - -#### Recorders - -- Use ScreenToGif to record your screen, your webcam feed or sketch board drawings. - -#Screen - -
            This is the default screen recorder UI. You simply move this window on top of the content that you want to record. - -
            This is the new recorder UI, which lets you click and drag to select an area of your screen. -You can also switch to the window and screen modes. - -- Use the record, pause, discard or stop buttons to control your capture. -- Select the capture frequency mode (manual, normal in fps, timelapse in fpm/fph). -- Older UI -- Drag or resize the window to adjust what you want to capture. -- Type the exact size of the capture region. -- Drag the crosshair button and drop it on top of a window to move the recorder to capture that. -- Newer UI Beta -- Enter selection mode, which lets you select a region, a window or an entire screen to capture. - ---- - -#Webcam - -
            This is the webcam recorder. - -- Use the record, pause, discard or stop buttons to control your capture. -- Select the maximum FPS of the capture. -- Resize the window to adjust the size of the capture. - ---- - -#Sketch board - -
            The board recorder lets you capture your drawings automatically as you draw them. - -- Enable the auto-capture or press Ctrl to toggle (_pauses_ or _captures_ it, depending if the auto-capture is enabled or disabled). -- Select the maximum FPS of the capture. -- Resize the window to adjust the size of the capture. - ---- - -### #Editor - -
            This is the editor, where you can edit your recordings and export it to gif, apng, video, project, images and psd. - -- File -- Start a new recording or open a media (videos or images) or project file. -- Insert a new recording or media file (videos or images) into an existing project. -- Open recent projects. -- Export your project to: -- Gif -- Apng -- Video -- Image -- PSD -- ScreenToGif project -- Basic controls -- Undo, redo or reset your edits. -- Copy, cut and paste frames. -- Select multiple frames or browse to a specific frame. -- Preview the playback of the animation. -- Frame manipulation -- Delete selected frames. -- Remove duplicates. -- Reduce framerate. -- Delete all previous or all next frames. -- Reverse, apply yoyo (forwards and backwards) or move frames around. -- Alter the delay of the frames (override, increase/decrease or scale). -- Add title frames. -- Add transitions (fade or slide effects). -- Image manipulation -- Resize, crop or flip/rotate. -- Add overlays: -- Captions/text. -- Drawings or shapes. -- Key strokes or mouse clicks. -- Borders, shadows, and obfuscation (pixelate). -- Watermarks (pick your own image). -- Cinemagraph (select parts of the animation to stay static or move). - ---- - -### 8. Traversy Media (Free) - --source: https://codeburst.io/8-websites-you-should-visit-to-learn-web-development-620e93b3f1c5 - -Traversy media is a youtube channel created by Brad Traversy. **His youtube channel covers nearly every topic regarding web development, from HTML, CSS, and Javascript to all the different frameworks and libraries (Sass, Bootstrap, Angular, React, Vue Js).** - -#### While I am at it I will list some youtube videos/channels that I think provide amazing content … just for the love of sharing knowledge. - ---- - -### 9.) Stackbit: - -I am currently building myself a new blog site… I sometimes develop it locally in vscode… but there's no doubt that it took something very similar to it's present form in a GUI! - -https://bgoonz-blog.netlify.app/ - -
            Stackbit takes all the tools you'd need for a site's stack (theme, static site generator, CMS, and deployment) and quickly bundles them together for you. It offers options in each category, so you can mix and match the tools in your stack that best suit your needs. - -At this point, you may be thinking, Ok, but "fast" is a relative term in this space… how "fast" are we really talking here? - -Great question. Let me put it to you this way: you could literally throw a HotPocket in the microwave, go build an incredibly sleek JAMstack site, and you'd still be waiting for your food to be cool enough to eat. - -### Site Preview - -The preview of your site in Stackbit is generated by the development server of your static-site-generator such as Gatsby or Jekyll. Because the preview is served by the SSG development server, any changes to site's content and code are immediately reflected in the preview. To show you the preview Stackbit runs the development server of your SSG and routes the site pages to your browser. - -### Running Preview - -Stackbit runs the following steps to show you the preview of your site: - -
            1. It clones your site's repository -2. It checks-out the `preview` branch -3. It installs your site dependencies depending on your static site generator (e.g., `npm install` for Node based SSGs such as Gatsby and Next.js, and `bundle install` for Jekyll) -4. It runs your static site generator's development server (e.g.: `gatsby develop` for Gatsby, and `bundle exec jekyll serve` for Jekyll). -5. It routes any page requests made from your browser to SSG's development server and returns responses back to your browser, as if you are developing your site locally on your local machine. - -For example, suppose your site uses Gatsby. In that case, after cloning your repository, checking out the `preview` branch, and installing dependencies, Stackbit executes `gatsby develop` in its preview-server to start Gatsby's development server and then routes page requests from your browser to that development server running internally on `http://localhost`. - -If your site uses Hugo, Stackbit executes `hugo server` and routes page requests to Hugo's development server running internally on `http://localhost`. - -You can see the logs of how Stackbit pulls your repository, installs dependencies, and runs your SSG's development server by clicking on the "Logs" button in the "Advanced Tools" bottom bar: - -
            ### Preview Updates - -Because the preview is served by the SSG development server, any changes to site's content and code are immediately reflected in the preview. - -Your SSG's development server should listen to content changes and respond to them by refreshing any opened browser sessions via live-reload or HMR. Most of the static-site-generators have these functionalities enabled by default, so you don't have to do anything. - -Due to the nature of static site generators and how their development server work, any changes made to the code, or the content are immediately picked up by the SSG and reflected in the browser. - -Of course, in order for Stackbit to show you the preview of your site, your SSG's development server must work without crashing. - ---- - -### 10.) File Locator Pro: - -FileLocator is a search utility for Windows - -First things first, Windows Search can't find a thing. For anyone used to Mac OS X or Linux and having access to advanced search functionality on their computers, Windows Search (formerly Windows Desktop Search) is a huge disappointment. - -Just watch how quickly it finds files by name in a 20GB folder! - -
            FileLocator Lite is free for personal and commercial use, although commercial use requires a per-user registration after a month. - -The user interface and experience is as good as it gets in an advanced program aimed at experienced users. The Pro version adds more controllers, but they can all be safely ignored unless you need something specific. The main program window opens up with three main input fields: search by file name or file contents, and where to look for the file. - -The true power of FileLocator is that it can search inside any kind of file to find what you're looking for. Other search programs will only go through files it assumes the user is looking for. - -However, you'll need FileLocator if you're looking for something inside an unusual document format, a string from a program, software source-code, your browser cache, or anything else really. Note that only the Pro version can search inside compressed archives like ZIP. - -In the search result section, you can not only see a list of files that match your search query; you can see the line number and line content where the match is made. This little feature alone takes FileLocator a few notches up and beyond their meager competition from the Windows search utility. - -- Source: - -FileLocator Lite and Pro review -
            - -Find "everything" with Lite Finding even more and do it faster with Pro Windows and tabs management, and keyboard…www.ctrl.blog
            - ---- - -### Rapid Fire Bonus Inclusions: - -### Notion: - -The best note taking app ever: - -Notion - The all-in-one workspace for your notes, tasks, wikis, and databases. -
            - -A new tool that blends your everyday work apps into one. It's the all-in-one workspace for you and your team.www.notion.so
            - -
            - ---- - -### Team wiki - -Turn your tribal knowledge into easy-to-find answers. - -
            Replaces - -
            ### Projects & tasks - -Kanban boards, tables, lists, and more. Customize any workflow. - -
            Replaces - -
            ### Notes & docs - -Systems that keep notes organized. Add any type of content. - -
            Replaces - -
            - ---- - -### Gitbook: - -GitBook - Where software teams break knowledge silos. -
            - -Centralize your knowledge and collaborate with your team in a single, organized workspace for increased efficiency…www.gitbook.com
            - -GitBook started as a simple open source tool designed to let developers quickly publish content from a git repo. We've changed a bunch since then, but fundamentally we've stayed true to the vision of empowering software teams to document and distribute their knowledge. - -Not only does this tool allow you to seamlessly create documentation and notes in perfect synchrony with the git repo of your choice .. you can also import/export html, markdown and pdf documents and the cherry on top… it turns your notes into a beautiful website…. 11/10 would recommend. - -Closure-and-Scope -
            - -Variables are used to store information to be referenced and manipulated in a computer program. A variable's sole…bryan-guner.gitbook.io
            - -If you're familiar with facebook's opensource docusaurous … this is a lot like that if it were way better and much easier… Also for no extra cost to you… they don't spy on you… sell your data or help influence foreign/domestic elections. … - -
            - -By Bryan Guner on [May 28, 2021](https://medium.com/p/82e8b6e61879). - -Canonical link - -August 6, 2021. diff --git a/notes/articles/medium/markdown/These-Are-The-Bash-Shell-Commands-That-Stand-Between-Me-And-Insanity.md b/notes/articles/medium/markdown/These-Are-The-Bash-Shell-Commands-That-Stand-Between-Me-And-Insanity.md deleted file mode 100644 index 1589f021fb..0000000000 --- a/notes/articles/medium/markdown/These-Are-The-Bash-Shell-Commands-That-Stand-Between-Me-And-Insanity.md +++ /dev/null @@ -1,65 +0,0 @@ -# These Are The Bash Shell Commands That Stand Between Me And Insanity - -I will not profess to be a bash shell wizard… but I have managed to scour some pretty helpful little scripts from Stack Overflow and modify… - ---- - -### These Are The Bash Shell Commands That Stand Between Me And Insanity - -#### I will not profess to be a bash shell wizard… but I have managed to scour some pretty helpful little scripts from Stack Overflow and modify them to suit my needs. - -
            Photo by George Girnas on Unsplash
            Photo by George Girnas on Unsplash
            All of these commands are for Ubuntu/WSL … some may work in other scenarios but I can't guarantee it. - -> _As of this writing I have about 120 more bash snippets I regularly use… I am not writing the whole article right now but I wanted to get it started so I feel obligated to finish it!_ - -### Recursive Unzip followed by recursive delete zip: - -### Remove spaces from file and folder names - -### Find and replace in string/folder names - - find . -type f -exec rename 's/string1/string2/g' {} + - -### Remove numbers from file names - - find $dir -type f | sed 's|\(.*/\)[^A-Z]*\([A-Z].*\)|mv \"&\" \"\1\2\"|' | sh - -### Delete files within size range ( for when GitHub cries about file size): - - find . -size +386b -a -size -390b -exec rm -f {} \; - -### Create symbolic link to working directory - - ln -s "$(pwd)" ~/mylink - -### **Remove any traces of a git repository:** - - find . \( -name ".git" -o -name ".gitignore" -o -name ".gitmodules" -o -name ".gitattributes" \) -exec rm -rf — {} + - -### Replace spaces in filenames with underscores - - for file in *; do mv "$file" `echo $file | tr ' ' '_'` ; done - -### Remove Empty Files and Folders: - - find . -empty -type f -print -delete - find . -empty -type d -print -delete - -**_or_** - - find . -depth -exec rmdir {} \; - -### Autogenerate a navigable HTML directory for all the files in the current working directory you exicute the script in: - -### For more content… go to : - -bgoonz - Overview -
            - -Web Developer, Electrical Engineer https://bryanguner.medium.com/ https://portfolio42.netlify.app/…github.com
            - -By Bryan Guner on [May 15, 2021](https://medium.com/p/984865ba5d1b). - -Canonical link - -August 31, 2021. diff --git a/notes/articles/medium/markdown/These-Are-The-Bash-Shell-Commands-That-Stand-Between-Me-And.md b/notes/articles/medium/markdown/These-Are-The-Bash-Shell-Commands-That-Stand-Between-Me-And.md deleted file mode 100644 index 5c9a8aa770..0000000000 --- a/notes/articles/medium/markdown/These-Are-The-Bash-Shell-Commands-That-Stand-Between-Me-And.md +++ /dev/null @@ -1,65 +0,0 @@ -# These Are The Bash Shell Commands That Stand Between Me And Insanity - -I will not profess to be a bash shell wizard… but I have managed to scour some pretty helpful little scripts from Stack Overflow and modify… - ---- - -### These Are The Bash Shell Commands That Stand Between Me And Insanity - -#### I will not profess to be a bash shell wizard… but I have managed to scour some pretty helpful little scripts from Stack Overflow and modify them to suit my needs. - -
            Photo by George Girnas on Unsplash
            Photo by George Girnas on Unsplash
            All of these commands are for Ubuntu/WSL … some may work in other scenarios but I can't guarantee it. - -> _As of this writing I have about 120 more bash snippets I regularly use… I am not writing the whole article right now but I wanted to get it started so I feel obligated to finish it!_ - -### Recursive Unzip followed by recursive delete zip: - -### Remove spaces from file and folder names - -### Find and replace in string/folder names - - find . -type f -exec rename 's/string1/string2/g' {} + - -### Remove numbers from file names - - find $dir -type f | sed 's|\(.*/\)[^A-Z]*\([A-Z].*\)|mv \"&\" \"\1\2\"|' | sh - -### Delete files within size range ( for when GitHub cries about file size): - - find . -size +386b -a -size -390b -exec rm -f {} \; - -### Create symbolic link to working directory - - ln -s "$(pwd)" ~/mylink - -### **Remove any traces of a git repository:** - - find . \( -name ".git" -o -name ".gitignore" -o -name ".gitmodules" -o -name ".gitattributes" \) -exec rm -rf — {} + - -### Replace spaces in filenames with underscores - - for file in *; do mv "$file" `echo $file | tr ' ' '_'` ; done - -### Remove Empty Files and Folders: - - find . -empty -type f -print -delete - find . -empty -type d -print -delete - -**_or_** - - find . -depth -exec rmdir {} \; - -### Autogenerate a navigable HTML directory for all the files in the current working directory you exicute the script in: - -### For more content… go to : - -bgoonz - Overview -
            - -Web Developer, Electrical Engineer https://bryanguner.medium.com/ https://portfolio42.netlify.app/…github.com
            - -By Bryan Guner on [May 15, 2021](https://medium.com/p/984865ba5d1b). - -Canonical link - -August 6, 2021. diff --git a/notes/articles/medium/markdown/This-is-really-cool-.md b/notes/articles/medium/markdown/This-is-really-cool-.md deleted file mode 100644 index fd91330de1..0000000000 --- a/notes/articles/medium/markdown/This-is-really-cool-.md +++ /dev/null @@ -1,11 +0,0 @@ -# This is really cool! - ---- - -This is really cool! I don't have the time to read it thoroughly right now but I've bookmarked it so that I will later... This includes a lot of the feature extraction techniques I considered in my college capstone project. It was an automated guitar effects triggering platform that would track the progress of a live performance and use an algorithm called dynamic time warping to determine when it was the appropriate time in the song to change the effects/settings. This repo is not optimized for readability but I'll link it incase you have any interest. https://github.com/bgoonz/Revamped-Automatic-Guitar-Effect-Triggering - -By Bryan Guner on [May 30, 2021](https://medium.com/p/691dbf4081b5). - -Canonical link - -August 31, 2021. diff --git a/notes/articles/medium/markdown/This-is-really-cool.md b/notes/articles/medium/markdown/This-is-really-cool.md deleted file mode 100644 index 5b21319c82..0000000000 --- a/notes/articles/medium/markdown/This-is-really-cool.md +++ /dev/null @@ -1,11 +0,0 @@ -# This is really cool! - ---- - -This is really cool! I don't have the time to read it thoroughly right now but I've bookmarked it so that I will later... This includes a lot of the feature extraction techniques I considered in my college capstone project. It was an automated guitar effects triggering platform that would track the progress of a live performance and use an algorithm called dynamic time warping to determine when it was the appropriate time in the song to change the effects/settings. This repo is not optimized for readability but I'll link it incase you have any interest. https://github.com/bgoonz/Revamped-Automatic-Guitar-Effect-Triggering - -By Bryan Guner on [May 30, 2021](https://medium.com/p/691dbf4081b5). - -Canonical link - -August 6, 2021. diff --git a/notes/articles/medium/markdown/UBVV8pch1dM.html.md b/notes/articles/medium/markdown/UBVV8pch1dM.html.md deleted file mode 100644 index a86c9e56cb..0000000000 --- a/notes/articles/medium/markdown/UBVV8pch1dM.html.md +++ /dev/null @@ -1,11 +0,0 @@ -# https://youtu.be/UBVV8pch1dM - ---- - -https://youtu.be/UBVV8pch1dM - -By Bryan Guner on [May 29, 2021](https://medium.com/p/74f38d3ac640). - -Canonical link - -August 6, 2021. diff --git a/notes/articles/medium/markdown/UBVV8pch1dM.md b/notes/articles/medium/markdown/UBVV8pch1dM.md deleted file mode 100644 index 21e863c56b..0000000000 --- a/notes/articles/medium/markdown/UBVV8pch1dM.md +++ /dev/null @@ -1,11 +0,0 @@ -# https://youtu.be/UBVV8pch1dM - ---- - -https://youtu.be/UBVV8pch1dM - -By Bryan Guner on [May 29, 2021](https://medium.com/p/74f38d3ac640). - -Canonical link - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Understanding-Git--A-Beginners-Guide-Containing-Cheat-Sheets---Resources-.md b/notes/articles/medium/markdown/Understanding-Git--A-Beginners-Guide-Containing-Cheat-Sheets---Resources-.md deleted file mode 100644 index 7c5dc60d51..0000000000 --- a/notes/articles/medium/markdown/Understanding-Git--A-Beginners-Guide-Containing-Cheat-Sheets---Resources-.md +++ /dev/null @@ -1,1257 +0,0 @@ -<<<<<<< HEAD:notes/articles/medium/markdown/Understanding-Git--A-Beginners-Guide-Containing-Cheat-Sheets---Resources-.md -======= ---- -title: Git and Github -weight: 0 -excerpt: Why is looking at runtime not a reliable method of calculating time complexity? -seo: - title: Git and Github - description: A Quick Guide to Git and Github - robots: [] - extra: [] -template: docs ---- ->>>>>>> master:src/pages/docs/git/git/index.md -# Understanding Git (A Beginners Guide Containing Cheat Sheets & Resources) - -Basic Git Work Flow. - ---- - -### Understanding Git (A Beginners Guide Containing Cheat Sheets & Resources) - -### Resources, Cheat Sheets & Links @Bottom of the Page! - -
            For More Advanced Readers, or those with very limited free time… here's an abridged Git Reference. - -Git-Tricks -
            - -Refs
            - -### What's a distributed version control system? - -Git is an example of a distributed version control system (DVCS) commonly used for open source and commercial software development. DVCSs allow full access to every file, branch, and iteration of a project, and allows every user access to a full and self-contained history of all changes. Unlike once popular centralized version control systems, DVCSs like Git don't need a constant connection to a central repository. Developers can work anywhere and collaborate asynchronously from any time zone. - -Without version control, team members are subject to redundant tasks, slower timelines, and multiple copies of a single project. To eliminate unnecessary work, Git and other VCSs give each contributor a unified and consistent view of a project, surfacing work that's already in progress. Seeing a transparent history of changes, who made them, and how they contribute to the development of a project helps team members stay aligned while working independently. - -### Why Git? - -According to the latest Stack Overflow developer survey, more than 70 percent of developers use Git, making it the most-used VCS in the world. Git is commonly used for both open source and commercial software development, **with significant benefits** for individuals, teams and businesses. - -- Git lets developers see the entire timeline of their changes, decisions, and progression of any project in one place. From the moment they access the history of a project, the developer has all the context they need to understand it and start contributing. -- Developers work in every time zone. With a DVCS like Git, collaboration can happen any time while maintaining source code integrity. Using branches, developers can safely propose changes to production code. -- Businesses using Git can break down communication barriers between teams and keep them focused on doing their best work. Plus, Git makes it possible to align experts across a business to collaborate on major projects. - -### Table Of Contents: - -Editing Understanding Git (A Beginners Guide Containing Cheat Sheets & Resources) — Medium - -<<<<<<< HEAD:notes/articles/medium/markdown/Understanding-Git--A-Beginners-Guide-Containing-Cheat-Sheets---Resources-.md -> What's a distributed version control system? - -> Why Git? - -> What's a repository? - -> Git Flow - -> Cloning a repo and changing the remote url - -> 1. The first step is to clone the repo! - -> 2. Make your own repo_._ - -> 3. Next, copy the .git link that is on the next page. - -> 4. Whenver you clone a repo - -> 5. Thats its! You can now run `git push` and it will push to your newly created repo. - -> Basic Git Work Flow. - -> Cheat Sheet: - -> My Git Reference Repo: - -> Git basics - -> A glance into GIT - -> Tracking changes in a repository - -> Branches and workflow - -> Bringing it back together - -> Connect-W-Github - -> I ❤️ Open Source - -> Merging your code on GitHub - -> Browsing Your Git Repository - -> Seeing changes in real time - -> Diff options - -> Time travel - -> Why checkout? - -> Git 'Do-Overs': Reset & Rebase - -> Resetting the past - -> Soft resets - -> Risky Business: Mixed resets - -> Red alert! Hard resets - -> Rebase: 'Alt-time travel' - -> I see you too like to live life Dangerously… tell me about Rebase.. - -> `working-on-the-header` - -> "Golden Rule of Git" - -> **How 2's** - -> Troubleshooting Git -======= -> - -What's a distributed version control system? - - - -> -Why Git? - - -> -What's a repository? - - -> - -Git Flow - - - -> -Cloning a repo and changing the remote url - - -> -1. The first step is to clone the repo! - - -> -2. Make your own repo -_._ - -> -3. Next, copy the .git link that is on the next page. - - -> -4. Whenver you clone a repo - - -> -5. Thats its! You can now run - `git push` -and it will push to your newly created repo. - - -> -Basic Git Work Flow. - - -> - -Cheat Sheet: - - - -> -My Git Reference Repo: - - -> -Git basics - - -> -A glance into GIT - - -> -Tracking changes in a repository - - -> -Branches and workflow - - -> -Bringing it back together - - -> -Connect-W-Github - - -> -I ❤️ Open Source - - -> -Merging your code on GitHub - - -> -Browsing Your Git Repository - - -> -Seeing changes in real time - - -> -Diff options - - -> -Time travel - - -> -Why checkout? - - -> -Git ‘Do-Overs': Reset & Rebase - - -> -Resetting the past - - -> -Soft resets - - -> -Risky Business: Mixed resets - - -> -Red alert! Hard resets - - -> -Rebase: ‘Alt-time travel' - - -> -I see you too like to live life Dangerously… tell me about Rebase.. - - -> `working-on-the-header` - -> -"Golden Rule of Git" - - -> **How 2's** - -> - -Troubleshooting Git - - ->>>>>>> master:src/pages/docs/git/git/index.md - -> **Further Reading & Resources** - -### What's a repository? - -A _repository_, or Git project, encompasses the entire collection of files and folders associated with a project, along with each file's revision history. The file history appears as snapshots in time called _commits_, and the commits exist as a linked-list relationship, and can be organized into multiple lines of development called _branches_. Because Git is a DVCS, repositories are self-contained units and anyone who owns a copy of the repository can access the entire codebase and its history. Using the command line or other ease-of-use interfaces, a git repository also allows for: interaction with the history, cloning, creating branches, committing, merging, comparing changes across versions of code, and more. - -Working in repositories keeps development projects organized and protected. Developers are encouraged to fix bugs, or create fresh features, without fear of derailing mainline development efforts. Git facilitates this through the use of topic branches: lightweight pointers to commits in history that can be easily created and deprecated when no longer needed. - -### Git Flow - -### Cloning a repo and changing the remote url - -(These steps are only for when you initially clone a project repo. Not when you clone your partners repo to collaborate together. To do that, you only have to complete step 1!) - -### 1. The first step is to clone the repo! - -- Navigate to the repo you want to clone and hit the big green code button. Copy the link given. - -
            - Navigate in your terminal to the directory where you want this repo to live. I've chosen downloads -- `git clone HTTPS://LINKTOURL/THATYOUCOPIED` - -
            ### 2. Sweet, you have the cloned repo in your preferred directory. Now lets make your own repo. On github, create a new repository. - -- Default settings are fine. Hit the big green button `Create Repository` - -
            ### 3. Next, - -**_copy the .git link that is on the next page. Do not do any other steps on this page — That is for when you do not clone a repo._** - ---- - -### These are the commands GitHub provides when you create a new Repo: - -#### Quick setup — if you've done this kind of thing before - -Set up in Desktop - -or - -HTTPSSSH - -Get started by creating a new file or uploading an existing file. We recommend every repository include a README, LICENSE, and .gitignore. - -### …or create a new repository on the command line - - echo "# the-meaning-of-life-is-42" >> README.md - git init - git add README.md - git commit -m "first commit" - git branch -M master - git remote add origin https://github.com/bgoonz/the-meaning-of-life-is-42.git - git push -u origin master - -### …or push an existing repository from the command line - - git remote add origin https://github.com/bgoonz/the-meaning-of-life-is-42.git - git branch -M master - git push -u origin master - -### …or import code from another repository - -You can initialize this repository with code from a Subversion, Mercurial, or TFS project. - -Import code - -### 4. Whenever you clone a repo: - -#### It already has a .git directory with certain configurations set up. To be able to push this repo to your newly created GitHub repo we have to change the remote origin. - -- To do that, just run this command: (Make sure you are inside the repo you cloned) - - - - git remote set-url origin https://LINK/TO/YOUR/GIT/THAT/YOU/COPIED/FROM/PREVIOUS/STEP.git - -OR: - -
            ### 5. You can now run `git push` and it will push to your newly created repo. - -### Basic Git Work Flow. - -- After making changes to a file and you are ready to commit / push to your repo you can run the following commands: -- `git add .` - stages modified files to be committed. -- `git status` - displays files that have been modified -- `git commit -m 'A helpfully commit message'` - commits the changes to your local repo. Get in the habit now of making helpful commit messages -- `git push` - pushes your local commits to your GitHub repo! -- To pull down changes that your partner pushed to the repo you simply have to run: -- `git pull` - this will fetch the most recent updates! - -### Cheat Sheet: - -### My Git Reference Repo: - -bgoonz/github-reference-repo -
            - -Cloning a repo and changing the remote url Basic Git Workflow (These steps are only for when you initially clone a…github.com
            - -### Git basics - -Like many disciplines, learning Git is just a matter of learning a new language. You'll cover a lot of new vocabulary in this lesson! Remember that the vocabulary you'll learn will allow you to communicate clearly with other developers worldwide, so it's important to understand the meaning of each term. - -It's also important to note that Git is a complex and powerful tool. As such, its documentation and advanced examples may be tough to understand. As your knowledge grows, you may choose to dive deeper into Git. Today, you'll focus on the commands you'll use every day — possibly for the rest of your programming career! Get comfortable with these commands and resist the urge to copy/paste or create keyboard shortcuts as you're getting started. - -### A glance into GIT - -Before you look at any practical examples, let's talk about how Git works behind the scenes. - -Here is your first new word in Git-speak: _repository_, often shortened to _repo_. A Git repo comprises all the source code for a particular project. In the "dark ages" example above, the repo is the first directory you created, where work is saved to, and which acts as the source for code shared to others. Without a repo, Git has nothing to act on. - -Git manages your project as a series of _commits_. A commit is a collection of changes grouped towards a shared purpose. By tracking these commits, you can see your project on a timeline instead of only as a finished project: - -
            Notice the notes and seemingly random numbers by each commit? These are referred to as *commit messages* and *commit hashes*, respectively. Git identifies your commits by their hash, a specially-generated series of letters and numbers. You add commit messages to convey meaning and to help humans track your commits, as those hashes aren't very friendly to read! - -A Git hash is 40 characters long, but you only need the first few characters to identify which hash you're referring to. By default, Git abbreviates hashes to 7 characters. You'll follow this convention, too. - -Git provides a helpful way for us to "alias" a commit in plain English as well. These aliases are called _refs_, short for "references". A special one that Git creates for all repositories is `HEAD`, which references the most recent commit. You'll learn more about creating your own refs when you learn about "branching". - -Git maintains three separate lists of changes: the _working directory_, the _staging area_, and the _commit history_. The working directory includes all of your in-progress changes, the staging area is reserved for changes you're ready to commit, and the commit history is made up of changes you've already committed. You'll look more at these three lists soon. - -Git only cares about changes that are "tracked". To track a file, you must add it to the commit history. The working directory will always show the changes, even if they aren't tracked. In the commit history, you'll only have a history of files that have been formally tracked by your repository. - -### Tracking changes in a repository - -Now, let's get practical! - -You can create a repository with `git init`. Running this command will initialize a new Git repo in your current directory. It's important to remember that you only want a repository for your project and not your whole hard drive, so always run this command inside a project folder and not your home folder or desktop. You can create a new repo in an empty folder or within a project directory you've already created. - -What good is an empty repo? Not much! To add content to your repository, use `git add`. You can pass this command a specific filename, a directory, a "wildcard" to select a series of similarly-named files, or a `.` to add every untracked file in the current directory: - - # This will add only my_app.js to the repo: - - > git add my_app.js - - # This will add all the files within ./objects: - - > git add objects/ - - # This will add all the files in the current directory ending in `.js`: - - > git add *.js - - # This will add everything in your current directory: - - > git add . - -Adding a file (or files) moves them from Git's working directory to the staging area. You can see what's been "staged" and what hasn't by using `git status`: - -
            In this example, "Changes to be committed" is your staging area and "Changes not staged for commit" is your working directory. Notice that you also have "Untracked files", Git's way of reminding us that you may have forgotten to `git add` a file to your repo. Most Git commands will include a bit of help text in the output, so always read the messages carefully before moving forward. Thanks, Git! - -Once you're happy with your files and have staged them, you'll use `git commit` to push them into the commit history. It's significantly more work to make changes after a commit, so be sure your files are staged and exactly as you'd like them before running this command. Your default text editor will pop up, and you'll be asked to enter a commit message for this group of changes. - -**Heads Up:** You may find yourself in an unfamiliar place! The default text editor for MacOS (and many variants of Linux) is called _Vim_. Vim is a terminal-based text editor you'll discuss in the near future. It's visually bare and may just look like terminal text to you! If this happens, don't worry — just type `:q` and press your "return" key to exit. - -You'll want to ensure that future commit messages open in a more familiar editor. You can run the following commands in your terminal to ensure that Visual Studio Code is your `git commit` editor from now on: - - > git config --global core.editor "code --wait" - - > git config --global -e - -If you experience any issues, you may be missing Visual Studio Code's command line tools. You can find more details and some troubleshooting tips on Microsoft's official VS Code and macOS documentation. - -Once you close your editor, the commit will be added to your repository's commit history. Use `git log` to see this history at any time. This command will show all the commits in your repository's history, beginning with the most recent: - -
            Like many Git commands, `git commit` includes some helpful shorthand. If you need a rather short commit message, you can use the `-m` flag to include the message inline. Here's an example: - - > git commit -m "Fix typo" - -This will commit your changes with the message "Fix typo" and avoid opening your default text editor. Remember the commit messages are how you make your project's history friendly to humans, so don't use the `-m` flag as an excuse to write lame commit messages! A commit message should always explain why changes were made in clear, concise language. It is also best practice to use imperative voice in commit messages (i.e. use "Fix typo" instead of "Fixing the typo" or "Typo was fixed"). - -### Branches and workflow - -
            You've seen what a project looks like with a linear commit history, but that's just scratching the surface of Git's utility. Let's explore a new realm with *branches*. A branch is a separate timeline in Git, reserved for its own changes. You'll use branches to make your own changes independently of others. These branches can then be *merged* back into the main branch at a later time. - -Let's consider a common scenario: a school project. It's a lot of extra hassle to schedule time together and argue over exactly what should be done next! Instead, group members will often assign tasks amongst themselves, work independently on their tasks, and reunite to bring it all together as a final report. Git branches let us emulate this workflow for code: you can make a copy of what's been done so far, complete a task on your new branch, and merge that branch back into the shared repository for others to use. - -By default, Git repos begin on the `master` branch. To create a new branch, use `git branch `. This will create a named reference to your current commit and let you add commits without affecting the `master` branch. Here's what a branch looks like: - -
            Notice how your refs help to identify branches here: `master` stays to itself and can have changes added to it independently of your new branch (`footer`). `HEAD`, Git's special ref, follows us around, so you know that in the above diagram you're working on the `footer` branch. - -You can create a new branch or visit an existing branch in your repository. This is especially helpful for returning the `master` branch or for projects you've received from teammates. To open an existing branch, use `git checkout `. - -### Bringing it back together - -Once you're happy with the code in the branch you've been working on, you'll likely want to integrate the code into the `master` branch. You can do this via `git merge`. Merging will bring the changes in from another branch and integrate them into yours. Here's an example workflow: - - > git branch my-changes - - > git add new-file.js - - > git commit -m "Add new file" - - > git checkout master - - > git merge my-changes - -Following these steps will integrate the commit from `my-changes` over to `master`. Boom! Now you have your `new-file.js` on your default branch. - -As you can imagine, branching can get _very_ complicated. Your repository's history may look more like a shrub than a beautiful tree! You'll discuss advanced merging and other options in an upcoming lesson. - -### Connect-W-Github - -Git can act as a great history tool and source code backup for your local projects, but it can also help you work with a team! Git is classified as a "DVCS", or "Distributed Version Control System". This means it has built-in support for managing code both locally and from a distant source. - -You can refer to a repository source that's not local as a _remote_. Your Git repository can have any number of remotes, but you'll usually only have one. By default you'll refer to the primary remote of a repo as the `origin`. - -You can add a remote to an existing repository on your computer, or you can retrieve a repository from a remote source. You can refer to this as _cloning_ the repo. Once you have a repository with a remote, you can update your local code from the remote by _pulling_ code down, and you can _push_ up your own code so others have access to it. - -### I ❤️ Open Source - -While a remote Git server can be run anywhere, there are a few places online that have become industry standards for hosting remote Git repositories. The best-known and most widely-used Git source is a website called GitHub. As the name suggests, GitHub is a global hub for Git repositories. It's free to make a Github account, and you'll find literally millions of public repositories you can browse. - -GitHub takes a lot of work out of managing remote Git repositories. Instead of having to manage your own server, GitHub provides managed hosting and even includes some helpful graphical tools for complicated tasks like deployment, branch merging, and code review. - -Let's look at a typical workflow using Git and GitHub. Imagine it's your first day on the job. How do you get access to your team's codebase? By cloning the repository! - - > git clone https://github.com/your-team/your-codebase.git - -Using the `git clone` command will create a new folder in your current directory named after the repo you're cloning (in this case, `your-codebase`). Inside that folder will be a git repository of your very own, containing the repo's entire commit history. - -You'll likely start on the `master` branch, but remember that this is the default branch and it's unlikely you want to make changes to it. **_Since you're working on a team now, it's important to think of how your changes to the repository might affect others._** - -The safest way to make changes is to create a new branch, make your changes there, and then push your branch up to the remote repository for review. You'll use the `git push` command to do this. Let's look at an example: - - > git branch add-my-new-file - - > git add my-new-file.js - - > git commit -m "Add new file" - - > git push -u origin add-my-new-file - -Notice how you used the `-u` flag with `git push`. This flag, shorthand for `--set-upstream`, lets Git know that you want your local branch to follow a remote branch. You've passed the same name in, so you'll now have two branches in your local repository: `add-my-new-file`, which is where your changes live after being committed, and `origin/add-my-new-file`, which keeps up with your remote branch and updates it after you use `git push`. - -**You only need to use the** `-u` **flag the first time you push each new branch - Git will know what to do with a simple** `git push` **from then on.** - -You now know how to push your changes up, but what about getting the changes your teammates have made? For this, you'll use `git pull`. Pulling from the remote repo will update all of your local branches with the code from each branch's remote counterpart. - -**Behind the scenes,** Git is running two separate commands: `git fetch` and `git merge`. - -
            Fetching retrieves the repository code and updates any remote tracking branches in your local repo, and merge does just you've already explored: integrates changes into the local branches. Here's a graphic to explain this a little better: - -
            It's important to remember to use `git pull` often. A dynamic team may commit and push code many times during the day, and it's easy to fall behind. The more often you `pull`, the more certain you can be that your own code is based on the "latest and greatest". - -### Merging your code on GitHub - -If you're paying close attention, you may have noticed that there's a missing step in your workflows so far: how do you get your code merged into your default branch? This is done by a process called a _Pull Request_. - -A pull request (or "PR") is a feature specific to GitHub, not a feature of Git. It's a safety net to prevent bugs, and it's a critical part of the collaboration workflow. Here's a high-level of overview of how it works: - -You push your code up to GitHub in its own branch. - -You open a pull request against a _base branch_. - -GitHub creates a comparison page just for your code, detailing the changes you've made. - -Other members of the team can review your code for errors. - -You make changes to your branch based on feedback and push the new commits up. - -The PR automatically updates with your changes. - -Once everyone is satisfied, a repo maintainer on GitHub can merge your branch. - -Huzzah! Your code is in the main branch and ready for everyone else to `git pull`. - -You'll create and manage your pull requests via GitHub's web portal, instead of the command line. You'll walk through the process of creating, reviewing, and merging a pull request in an upcoming project. - -### Browsing Your Git Repository - -Repositories can feel intimidating at first, but it won't take you long to navigate code like you own the place — because you do! Let's discuss a few tools native to Git that help us browse our changes over time. - -We'll be covering: - -Comparing changes with `git diff` - -Browsing through our code "checkpoints" with `git checkout` - -### Seeing changes in real time - -Git is all about change tracking, so it makes sense that it would include a utility for visualizing a set of changes. We refer to a list of differences between two files (or the same file over time) as a _diff_, and we can use `git diff` to visualize diffs in our repo! - -When run with no extra options, `git diff` will return any tracked changes in our working directory since the last commit. **Tracked** is a key word here; `git diff` won't show us changes to files that haven't been included in our repo via `git add`. This is helpful for seeing what you've changed before committing! Here's an example of a small change: - -
            Let's break down some of the new syntax in this output. - -The diff opens with some Git-specific data, including the branch/files we're checking, and some unique hashes that Git uses to track each diff. You can skip past this to get to the important bits. - -`---` & `+++` let us know that there are both additions and subtractions in the file "App.js". A diff doesn't have a concept of inline changes - it treats a single change as removing something old and replacing it with something new. - -`@@` lets us know that we're starting a single "chunk" of the diff. A diff could have multiple chunks for a single file (for example: if you made changes far apart, like the header & footer). The numbers in between tell us how many lines we're seeing and where they start. For example: `@@ +1,3 -1,3 @@` means we'll see three lines of significant content, including both addition & removal, beginning at line one. - -In the code itself, lines that were removed are prefixed with a `-` and lines that were added are prefixed with a `+`. Remember that you won't see these on the same lines. Even if you only changed a few words, Git will still treat it like the whole line was replaced. - -### Diff options - -Remember that, by default, `git diff` compares the current working directory to the last commit. You can compare the staging area instead of the working directory with `git diff --staged`. This is another great way to double-check your work before pushing up to a remote branch. - -You're also not limited to your current branch — or even your current commit! You can pass a base & target branch to compare, and you can use some special characters to help you browse faster! Here are a few examples: - - # See differences between the 'feature' - - # branch and the 'master' branch. - - > git diff master feature - - # Compare two different commits - - > git diff 1fc345a 2e3dff - - # Compare a specific file across separate commits - - > git diff 1fc345a 2e3dff my-file.js - -### Time travel - -`git diff` gives us the opportunity to explore our code's current state, but what if we wanted to see its state at a different point in time? We can use _checkout_! `git checkout` lets us take control of our `HEAD` to bounce around our timeline as we please. - -Remember that `HEAD` is a special Git reference that usually follows the latest commit on our current branch. We can use `git checkout` to point our `HEAD` reference at a different commit, letting us travel to any commit in our repository's history. By reading the commit message and exploring the code at the time of the commit, we can see not only what changed but also why it changed! This can be great for debugging a problem or understanding how an app evolved. - -Let's look at a diagram to understand what `checkout` does a little better: - -
            Notice that we haven't lost any commits, commit messages, or code changes. Using `git checkout` is entirely non-destructive. - -To browse to a different commit, simply pass in a reference or hash for the commit you'd like to explore. `git checkout` also supports a few special characters & reserved references: - - # You can checkout a branch name. - - # You'll be using this particular branch a lot! - - > git checkout master - - # You can also use commit hashes directly - - > git checkout 7d3e2f1 - - # Using a hyphen instead of a hash will take - - # you to the last branch you checked out - - > git checkout - - - # You can use "HEAD~N" to move N commits prior - - # to the current HEAD - - > git checkout HEAD~3 - -Once you're done browsing the repo's history, you can use `git checkout ` to move `HEAD` back to the front of the line (your most recent commit). For example, in our diagram above, we could use `git checkout master` to take our `HEAD` reference back to commit `42ffa1`. - -### Why checkout? - -Most of Git's power comes from a simple ability: viewing commits in the past and understanding how they connect. This is why mastering the `git checkout` command is so important: it lets you think more like Git and gives you full freedom of navigation without risking damage to the repo's contents. - -That said, you'll likely use shortcuts like `git checkout -` far more often than specifically checking out commit hashes. Especially with the advent of user-friendly tools like GitHub, it's much easier to visualize changes outside the command line. We'll demonstrate browsing commit histories on GitHub in a future lesson. - -### Git 'Do-Overs': Reset & Rebase - -
            Git is designed to protect you — not only from others, but also from yourself! Of course, there are times where you'd like to exercise your own judgement, even if it may not be the best thing to do. For this, Git provides some helpful tools to change commits and "time travel". - -Before we talk about these, a warning: **The commands in this lesson are destructive!** If used improperly, you could lose work, damage a teammate's branch, or even rewrite the history of your entire project. You should exercise caution when using these on production code, and don't hesitate to ask for help if you're unsure what a command might do. - -After this lesson, you should: - -Be able to roll back changes to particular commit. - -Have an understanding of how rebasing affects your commit history. - -Know when to rebase/reset and when **not** to. - -### Resetting the past - -Remember how our commits form a timeline? We can see the state of our project at any point using `git checkout`. What if we want to travel back in time to a point before we caused a new bug or chose a terrible font? `git reset` is the answer! - -> _Resetting_ involves moving our `HEAD` ref back to a different commit. - -No matter how we reset, `HEAD` will move with us. Unlike `git checkout`, this will also destroy intermediate commits. We can use some additional flags to determine how our code changes are handled. - -### Soft resets - -The least-dangerous reset of all is `git reset --soft`. - -A soft reset will move our `HEAD` ref to the commit we've specified, and will leave any intermediate changes in the staging area. - -This means you won't lose any code, though you will lose commit messages. - -A practical example of when a soft reset would be handy is joining some small commits into a larger one. We'll pretend we've been struggling with "their", "there", and "they're" in our app. Here's our commit history:Those commit messages aren't great: they're not very explanatory, and they don't provide a lot of value in our commit history. We'll fix them with a soft reset: - - git reset --soft 9c5e2fc - -This moves our `HEAD` ref back to our first commit. Looking at our commit log now, we might be worried we've lost our changes: - -
            Our changes are still present in the staging area, ready to be re-committed when we're ready! We can use `git commit` to re-apply those changes to our commit history with a new, more helpful message instead: - -
            Notice that the new commit has a totally new hash. The old commit messages (and their associated hashes) have been lost, but our code changes are safe and sound! - -### Risky Business: Mixed resets - -If soft resets are the safest form of `git reset`, mixed resets are the most average! This is exactly why they're the default: running `git reset` without adding a flag is the same as running `git reset --mixed`. - -In a mixed reset, your changes are preserved, but they're moved from the commit history directly to the working directory. This means you'll have to use `git add` to choose everything you want in future commits. - -Mixed resets are a good option when you want to alter a change in a previous commit. Let's use a mixed reset with our "their", "there", "they're" example again. - -We'll start with "they're": - -
            Notice again that you don't lose your code with a mixed reset, but you do lose your commit messages & hashes. The difference between `--soft` and `--mixed` comes down to whether you'll be keeping the code exactly the same before re-committing it or making changes. - -### Hard resets - -Hard resets are the most dangerous type of reset in Git. Hard resets adjust your `HEAD` ref and _totally destroy any interim code changes_. Poof. Gone forever. - -There are very few good uses for a hard reset, but one is to get yourself out of a tight spot. Let's say you've made a few changes to your repository but you now realize those changes were unnecessary. You'd like to move back in time so that your code looks exactly as it did before any changes were made. `git reset --hard` can take you there. - -It's our last round with "their", "there", and "they're". We've tried it all three ways and decided we don't need to use that word at all! Let's walk through a hard reset to get rid of our changes. - -We'll start in the same place we began for our soft reset: - -
            It turns out that we'll be using a video on our homepage and don't need text at all! Let's step back in time: - - git reset --hard 9c5e2fc - -Our Git log output is much simpler now: - -
            It's empty — no changes in your working directory and no changes in your staging area. This is major difference between a hard reset and a soft/mixed reset: you will lose *all your changes* back to the commit you've reset to. - -If your teammate came rushing in to tell you that the boss has changed their mind and wants that homepage text after all, you're going to be re-doing all that work! Be very confident that the changes you're losing are unimportant before embarking on a hard reset. - -### Rebase: 'Alt-time travel' - -
            Sometimes we want to change more than a few commits on a linear timeline. What if we want to move multiple commits across branches? `git rebase` is the tool for us! - -_Rebasing_ involves changing your current branch's base branch. We might do this if we accidentally started our branch from the wrong commit or if we'd like to incorporate changes from another branch into our own. - -> Isn't that the same as git merge? - -`git merge`?" In almost all cases, you'd be right. Rebasing is a dangerous process that effectively rewrites history. - -### I see you too like to live life Dangerously… tell me about Rebase.. - -Let's look at a situation where we might be tempted to rebase. We've added a couple commits to a feature branch while other team members have been merging their code into the `master` branch. Once we're ready to merge our own branch, we probably want to follow a tried-and-true procedure: - - > git pull origin master - -This will fetch our remote `master` branch and merge its changes into our own feature branch, so it's safe to pull request or `git push`. However, every time we do that, a merge commit will be created! This can make a big mess of our Git commit history, especially if lots of people are making small changes. - -We can use `git rebase` to move our changes silently onto the latest version of `master`. Here's what the `git log` history of our two example branches looks like: - -
            Notice that both branches start at `9c5e2fc`. That's our common ancestor commit, and is where `git merge` would start stitching these branches together! We're going to avoid that entirely with a rebase. We'll run this command while we have `working-on-the-header` checked out: - - git rebase master - -**Here's our new commit history:** - -
            ### `working-on-the-header` - -See how we changed the color of our commits after the rebase? Take a close look at the commit history changes as well. Even though our commits have the same content, they have a new hash assigned, meaning they're entirely new commits! This is what we mean by "rewriting history": we've actually changed how Git refers to these changes now. - -### "Golden Rule of Git" - -These tools can all feel pretty nifty, but be very wary of using them too much! While they can augment your Git skills from good to great, they can also have catastrophic side effects. - -There's a "Golden Rule of Git" you should know that directly relates to both `git reset` and `git rebase`: - -**_Never change the history of a branch that's shared with others._** - -That's it! It's simple and to the point. If you're resetting or rebasing your own code and you make a mistake, your worst case scenario is losing your own changes. However, if you start changing the history of code that others have contributed or are relying on, your accidental loss could affect many others! - -### How to check your Git configuration: - -The command below returns a list of information about your git configuration including user name and email: - - git config -l - -### How to setup your Git username: - -With the command below you can configure your user name: - - git config --global user.name "Fabio" - -### How to setup your Git user email: - -This command lets you setup the user email address you'll use in your commits. - - git config --global user.email "signups@fabiopacifici.com" - -### How to cache your login credentials in Git: - -You can store login credentials in the cache so you don't have to type them in each time. Just use this command: - - git config --global credential.helper cache - -### How to initialize a Git repo: - -Everything starts from here. The first step is to initialize a new Git repo locally in your project root. You can do so with the command below: - - git init - -### How to add a file to the staging area in Git: - -The command below will add a file to the staging area. Just replace `filename_here` with the name of the file you want to add to the staging area. - - git add filename_here - -### How to add all files in the staging area in Git - -If you want to add all files in your project to the staging area, you can use a wildcard `.` and every file will be added for you. - - git add . - -### How to add only certain files to the staging area in Git - -With the asterisk in the command below, you can add all files starting with 'fil' in the staging area. - - git add fil* - -### How to check a repository's status in Git: - -This command will show the status of the current repository including staged, unstaged, and untracked files. - - git status - -### How to commit changes in the editor in Git: - -This command will open a text editor in the terminal where you can write a full commit message. - -A commit message is made up of a short summary of changes, an empty line, and a full description of the changes after it. - - git commit - -### How to commit changes with a message in Git: - -You can add a commit message without opening the editor. This command lets you only specify a short summary for your commit message. - - git commit -m "your commit message here" - -### How to commit changes (and skip the staging area) in Git: - -You can add and commit tracked files with a single command by using the -a and -m options. - - git commit -a -m"your commit message here" - -### How to see your commit history in Git: - -This command shows the commit history for the current repository: - - git log - -### How to see your commit history including changes in Git: - -This command shows the commit's history including all files and their changes: - - git log -p - -### How to see a specific commit in Git: - -This command shows a specific commit. - -Replace commit-id with the id of the commit that you find in the commit log after the word commit. - - git show commit-id - -### How to see log stats in Git: - -This command will cause the Git log to show some statistics about the changes in each commit, including line(s) changed and file names. - - git log --stat - -### How to see changes made before committing them using "diff" in Git: - -You can pass a file as a parameter to only see changes on a specific file. -`git diff` shows only unstaged changes by default. - -We can call diff with the `--staged` flag to see any staged changes. - - git diff - git diff all_checks.py - git diff --staged - -### How to see changes using "git add -p": - -This command opens a prompt and asks if you want to stage changes or not, and includes other options. - - git add -p - -### How to remove tracked files from the current working tree in Git: - -This command expects a commit message to explain why the file was deleted. - - git rm filename - -### How to rename files in Git: - -This command stages the changes, then it expects a commit message. - - git mv oldfile newfile - -### How to ignore files in Git: - -Create a `.gitignore` file and commit it. - -### How to revert unstaged changes in Git: - - git checkout filename - -### How to revert staged changes in Git: - -You can use the -p option flag to specify the changes you want to reset. - - git reset HEAD filename - git reset HEAD -p - -### How to amend the most recent commit in Git: - -`git commit --amend` allows you to modify and add changes to the most recent commit. - - git commit --amend - -!!Note!!: fixing up a local commit with amend is great and you can push it to a shared repository after you've fixed it. But you should avoid amending commits that have already been made public. - -### How to rollback the last commit in Git: - -`git revert` will create a new commit that is the opposite of everything in the given commit. -We can revert the latest commit by using the head alias like this: - - git revert HEAD - -### How to rollback an old commit in Git: - -You can revert an old commit using its commit id. This opens the editor so you can add a commit message. - - git revert comit_id_here - -### How to create a new branch in Git: - -By default, you have one branch, the main branch. With this command, you can create a new branch. Git won't switch to it automatically — you will need to do it manually with the next command. - - git branch branch_name - -### How to switch to a newly created branch in Git: - -When you want to use a different or a newly created branch you can use this command: - - git checkout branch_name - -### How to list branches in Git: - -You can view all created branches using the `git branch` command. It will show a list of all branches and mark the current branch with an asterisk and highlight it in green. - - git branch - -### How to create a branch in Git and switch to it immediately: - -In a single command, you can create and switch to a new branch right away. - - git checkout -b branch_name - -### How to delete a branch in Git: - -When you are done working with a branch and have merged it, you can delete it using the command below: - - git branch -d branch_name - -### How to merge two branches in Git: - -To merge the history of the branch you are currently in with the `branch_name`, you will need to use the command below: - - git merge branch_name - -### How to show the commit log as a graph in Git: - -We can use `--graph` to get the commit log to show as a graph. Also, -`--oneline` will limit commit messages to a single line. - - git log --graph --oneline - -### How to show the commit log as a graph of all branches in Git: - -Does the same as the command above, but for all branches. - - git log --graph --online --all - -### How to abort a conflicting merge in Git: - -If you want to throw a merge away and start over, you can run the following command: - - git merge --abort - -### How to add a remote repository in Git - -This command adds a remote repository to your local repository (just replace `https://repo_here` with your remote repo URL). - - git add remote https://repo_here - -### How to see remote URLs in Git: - -You can see all remote repositories for your local repository with this command: - - git remote -v - -### How to get more info about a remote repo in Git: - -Just replace `origin` with the name of the remote obtained by -running the git remote -v command. - - git remote show origin - -### How to push changes to a remote repo in Git: - -When all your work is ready to be saved on a remote repository, you can push all changes using the command below: - - git push - -### How to pull changes from a remote repo in Git: - -If other team members are working on your repository, you can retrieve the latest changes made to the remote repository with the command below: - - git pull - -### How to check remote branches that Git is tracking: - -This command shows the name of all remote branches that Git is tracking for the current repository: - - git branch -r - -### How to fetch remote repo changes in Git: - -This command will download the changes from a remote repo but will not perform a merge on your local branch (as git pull does that instead). - - git fetch - -### How to check the current commits log of a remote repo in Git - -Commit after commit, Git builds up a log. You can find out the remote repository log by using this command: - - git log origin/main - -### How to merge a remote repo with your local repo in Git: - -If the remote repository has changes you want to merge with your local, then this command will do that for you: - - git merge origin/main - -### How to get the contents of remote branches in Git without automatically merging: - -This lets you update the remote without merging any content into the -local branches. You can call git merge or git checkout to do the merge. - - git remote update - -### How to push a new branch to a remote repo in Git: - -If you want to push a branch to a remote repository you can use the command below. Just remember to add -u to create the branch upstream: - - git push -u origin branch_name - -### How to remove a remote branch in Git: - -If you no longer need a remote branch you can remove it using the command below: - - git push --delete origin branch_name_here - -### How to use Git rebase: - -You can transfer completed work from one branch to another using `git rebase`. - - git rebase branch_name_here - -Git Rebase can get really messy if you don't do it properly. Before using this command I suggest that you re-read the official documentation here - -### How to run rebase interactively in Git: - -You can run git rebase interactively using the -i flag. -It will open the editor and present a set of commands you can use. - - git rebase -i master - # p, pick = use commit - # r, reword = use commit, but edit the commit message - # e, edit = use commit, but stop for amending - # s, squash = use commit, but meld into previous commit - # f, fixup = like "squash", but discard this commit's log message - # x, exec = run command (the rest of the line) using shell - # d, drop = remove commit - -### How to force a push request in Git: - -This command will force a push request. This is usually fine for pull request branches because nobody else should have cloned them. -But this isn't something that you want to do with public repos. - - git push -f - ---- - -### Git Alias Overview - -It is important to note that there is no direct `git alias` command. Aliases are created through the use of the `git config` command and the Git configuration files. As with other configuration values, aliases can be created in a local or global scope. - -To better understand Git aliases let us create some examples. - - $ git config --global alias.co checkout - $ git config --global alias.br branch - $ git config --global alias.ci commit - $ git config --global alias.st status - -The previous code example creates globally stored shortcuts for common git commands. Creating the aliases will not modify the source commands. So `git checkout` will still be available even though we now have the `git co` alias. These aliases were created with the `--global` flag which means they will be stored in Git's global operating system level configuration file. On linux systems, the global config file is located in the User home directory at `/.gitconfig`. - - [alias] - co = checkout - br = branch - ci = commit - st = status - -This demonstrates that the aliases are now equivalent to the source commands. - -### Usage - -Git aliasing is enabled through the use of `git config`, For command-line option and usage examples please review the `git config `documentation. - -### Examples - -### Using aliases to create new Git commands - -A common Git pattern is to remove recently added files from the staging area. This is achieved by leveraging options to the `git reset` command. A new alias can be created to encapsulate this behavior and create a new alias-command-keyword which is easy to remember: - - git config --global alias.unstage 'reset HEAD --' - -The preceding code example creates a new alias `unstage`. This now enables the invocation of `git unstage. git unstage` which will perform a reset on the staging area. This makes the following two commands equivalent. - - git unstage fileA - $ git reset HEAD -- fileA - -### My Default Gitignore: - ---- - -### Troubleshooting Git - -
            ### Here are some tips on troubleshooting and resolving issues with Git. - -### Broken pipe errors on `git push` - -'Broken pipe' errors can occur when attempting to push to a remote repository. When pushing you usually see: - - Write failed: Broken pipe - fatal: The remote end hung up unexpectedly - -To fix this issue, here are some possible solutions. - -### Increase the POST buffer size in Git - -**If you're using Git over HTTP instead of SSH**, you can try increasing the POST buffer size in Git's configuration. - -Example of an error during a clone: `fatal: pack has bad object at offset XXXXXXXXX: inflate returned -5` - -Open a terminal and enter: - - git config http.postBuffer 52428800 - -The value is specified in bytes, so in the above case the buffer size has been set to 50MB. The default is 1MB. - -### Check your SSH configuration - -**If pushing over SSH**, first check your SSH configuration as 'Broken pipe' errors can sometimes be caused by underlying issues with SSH (such as authentication). Make sure that SSH is correctly configured by following the instructions in the SSH troubleshooting documentation. - -If you're a GitLab administrator and have access to the server, you can also prevent session timeouts by configuring SSH `keep alive` either on the client or on the server. - -Configuring both the client and the server is unnecessary. - -**To configure SSH on the client side**: - -- On UNIX, edit `~/.ssh/config` (create the file if it doesn't exist) and add or edit: -- `Host your-gitlab-instance-url.com ServerAliveInterval 60 ServerAliveCountMax 5` -- On Windows, if you are using PuTTY, go to your session properties, then navigate to "Connection" and under "Sending of null packets to keep session active", set `Seconds between keepalives (0 to turn off)` to `60`. - -**To configure SSH on the server side**, edit `/etc/ssh/sshd_config` and add: - - ClientAliveInterval 60 - ClientAliveCountMax 5 - -### Running a `git repack` - -**If 'pack-objects' type errors are also being displayed**, you can try to run a `git repack` before attempting to push to the remote repository again: - - git repack - git push - -### Upgrade your Git client - -In case you're running an older version of Git (< 2.9), consider upgrading to >= 2.9 (see Broken pipe when pushing to Git repository). - -### `ssh_exchange_identification` error - -Users may experience the following error when attempting to push or pull using Git over SSH: - - Please make sure you have the correct access rights - and the repository exists. - ... - ssh_exchange_identification: read: Connection reset by peer - fatal: Could not read from remote repository. - -or - - ssh_exchange_identification: Connection closed by remote host - fatal: The remote end hung up unexpectedly - -This error usually indicates that SSH daemon's `MaxStartups` value is throttling SSH connections. This setting specifies the maximum number of concurrent, unauthenticated connections to the SSH daemon. This affects users with proper authentication credentials (SSH keys) because every connection is 'unauthenticated' in the beginning. The default value is `10`. - -Increase `MaxStartups` on the GitLab server by adding or modifying the value in `/etc/ssh/sshd_config`: - - MaxStartups 100:30:200 - -`100:30:200` means up to 100 SSH sessions are allowed without restriction, after which 30% of connections are dropped until reaching an absolute maximum of 200. - -Once configured, restart the SSH daemon for the change to take effect. - - # Debian/Ubuntu - sudo systemctl restart ssh - - # CentOS/RHEL - sudo service sshd restart - -### Timeout during `git push` / `git pull` - -If pulling/pushing from/to your repository ends up taking more than 50 seconds, a timeout is issued. It contains a log of the number of operations performed and their respective timings, like the example below: - - remote: Running checks for branch: master - remote: Scanning for LFS objects... (153ms) - remote: Calculating new repository size... (cancelled after 729ms) - -This could be used to further investigate what operation is performing poorly and provide GitLab with more information on how to improve the service. - -### `git clone` over HTTP fails with `transfer closed with outstanding read data remaining` error - -If the buffer size is lower than what is allowed in the request, the action fails with an error similar to the one below: - - error: RPC failed; curl 18 transfer closed with outstanding read data remaining - fatal: The remote end hung up unexpectedly - fatal: early EOF - fatal: index-pack failed - -This can be fixed by increasing the existing `http.postBuffer` value to one greater than the repository size. For example, if `git clone` fails when cloning a 500M repository, you should set `http.postBuffer` to `524288000`. That setting ensures the request only starts buffering after the first 524288000 bytes. - -The default value of `http.postBuffer`, 1 MiB, is applied if the setting is not configured. - - git config http.postBuffer 524288000 - ---- - -### **Further Reading:** - -### If you found this guide helpful feel free to checkout my GitHub/gists where I host similar content: - -bgoonz's gists -
            - -Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…gist.github.com
            - -bgoonz — Overview -
            - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
            - -### Or Checkout my personal Resource Site: - -Web-Dev-Hub -
            - -Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…bgoonz-blog.netlify.app
            - -By Bryan Guner on [March 12, 2021](https://medium.com/p/b50c9c01a107). - -Canonical link - -<<<<<<< HEAD:notes/articles/medium/markdown/Understanding-Git--A-Beginners-Guide-Containing-Cheat-Sheets---Resources-.md -August 31, 2021. -======= - on September 23, 2021. ->>>>>>> master:src/pages/docs/git/git/index.md diff --git a/notes/articles/medium/markdown/VSCode-Extensions-Specifically-for-JavaScript-Development.md b/notes/articles/medium/markdown/VSCode-Extensions-Specifically-for-JavaScript-Development.md deleted file mode 100644 index 593b5a713a..0000000000 --- a/notes/articles/medium/markdown/VSCode-Extensions-Specifically-for-JavaScript-Development.md +++ /dev/null @@ -1,326 +0,0 @@ -# VSCode Extensions Specifically for JavaScript Development - -VSCode Extensions that are indispensable in JavaScript development - ---- - -#### CODEX - -### VSCode Extensions Specifically for JavaScript Development - -#### VSCode Extensions that are indispensable in JavaScript development - -### Back and Forth - -- Adds backwards and forwards buttons to the toolbar in VSCode -- https://marketplace.visualstudio.com/items?itemName=nick-rudenko.back-n-forth - -
            - ---- - -### Bracket Pair Colorizer 2 - -- Colors matching brackets so it's easier to tell which brackets match. -- https://marketplace.visualstudio.com/items?itemName=CoenraadS.bracket-pair-colorizer-2 - -
            - ---- - -### Babel Javascript - -- A better syntax highlighter for JavaScript code -- https://marketplace.visualstudio.com/items?itemName=mgmcdermott.vscode-language-babel - -
            - ---- - -### Code Runner - -- Puts a "Play" button in your toolbar and let's you run code files by pressing it. -- https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner - -### Code Runner - -> Run code snippet or code file for multiple languages: **C, C++, Java, JavaScript, PHP, Python, Perl, Perl 6, Ruby, Go, Lua, Groovy, PowerShell, BAT/CMD, BASH/SH, F\# Script, F\# (.NET Core), C\# Script, C\# (.NET Core), VBScript, TypeScript, CoffeeScript, Scala, Swift, Julia, Crystal, OCaml Script, R, AppleScript, Elixir, Visual Basic .NET, Clojure, Haxe, Objective-C, Rust, Racket, Scheme, AutoHotkey, AutoIt, Kotlin, Dart, Free Pascal, Haskell, Nim, D, Lisp, Kit, V, SCSS, Sass, CUDA, Less, Fortran**, and custom command - -### Features - -> Run code file of current active Text Editor - -> Run code file through context menu of file explorer - -> Run selected code snippet in Text Editor - -> Run code per Shebang - -> Run code per filename glob - -> Run custom command - -> Stop code running - -> View output in Output Window - -> Set default language to run - -> Select language to run - -> Support REPL by running code in Integrated Terminal - -### Usages - -#### To run code: - -- use shortcut `Ctrl+Alt+N` -- or press `F1` and then select/type `Run Code`, -- or right click the Text Editor and then click `Run Code` in editor context menu -- or click `Run Code` button in editor title menu -- or click `Run Code` button in context menu of file explorer -- To stop the running code: -- use shortcut `Ctrl+Alt+M` -- or press `F1` and then select/type `Stop Code Run` -- or right click the Output Channel and then click `Stop Code Run` in context menu - -
            - To select language to run, use shortcut `Ctrl+Alt+J`, or press `F1` and then select/type `Run By Language`, then type or select the language to run: e.g `php, javascript, bat, shellscript...` - -
            - To run custom command, then use shortcut `Ctrl+Alt+K`, or press `F1` and then select/type `Run Custom Command` - ---- - -### Color Highlight - -- Changes the background color of hex colors in your code to show you what color it actually is -- https://marketplace.visualstudio.com/items?itemName=naumovs.color-highlight - -
            ### Git Graph - -- Shows you a graphical representation of your git branches and commits -- https://marketplace.visualstudio.com/items?itemName=mhutchie.git-graph - -
            - ---- - -### GitLens - -- Adds tons of cool features to vscode, like viewing commits inline inside the editor -- https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens - -Here are just some of the **features** that GitLens provides, - -- effortless revision navigation (backwards and forwards) through the history of a file -- an unobtrusive current line blame annotation at the end of the line showing the commit and author who last modified the line, with more detailed blame information accessible on hover -- authorship code lens showing the most recent commit and number of authors at the top of files and/or on code blocks -- a status bar blame annotation showing the commit and author who last modified the current line -- on-demand **file annotations** in the editor gutter, including -- blame — shows the commit and author who last modified each line of a file -- changes — highlights any local (unpublished) changes or lines changed by the most recent commit -- heatmap — shows how recently lines were changed, relative to all the other changes in the file and to now (hot vs. cold) -- many rich **Side Bar views** -- a Commits view to visualize, explore, and manage Git commits -- a Repositories view to visualize, explore, and manage Git repositories -- a File History view to visualize, navigate, and explore the revision history of the current file or just the selected lines of the current file -- a Line History view to visualize, navigate, and explore the revision history of the selected lines of the current file -- a Branches view to visualize, explore, and manage Git branches -- a Remotes view to visualize, explore, and manage Git remotes and remote branches -- a Stashes view to visualize, explore, and manage Git stashes -- a Tags view to visualize, explore, and manage Git tags -- a Contributors view to visualize, navigate, and explore contributors -- a Search & Compare view to search and explore commit histories by message, author, files, id, etc, or visualize comparisons between branches, tags, commits, and more -- a Git Command Palette to provide guided (step-by-step) access to many common Git commands, as well as quick access to -- commits — history and search -- stashes -- status — current branch and working tree status -- a user-friendly interactive rebase editor to easily configure an interactive rebase session -- terminal links — `ctrl+click` on autolinks in the integrated terminal to quickly jump to more details for commits, branches, tags, and more -- rich remote provider integrations — GitHub, GitLab, Bitbucket, Azure DevOps -- issue and pull request auto-linking -- rich hover information provided for linked issues and pull requests (GitHub only) -- associates pull requests with branches and commits (GitHub only) -- many powerful commands for navigating and comparing revisions, and more -- user-defined modes for quickly toggling between sets of settings -- and so much more 😁 - -### Features - -#### Revision Navigation - -
            - ---- - -### Markdown All in One - -- Everything you need to help you write markdown files in VSCode -- https://marketplace.visualstudio.com/items?itemName=yzhang.markdown-all-in-one - -### Features - -### Keyboard shortcuts - -
            (Typo: multiple words) - -
            See full key binding list in the keyboard shortcuts section - -### Table of contents - -
            - Run command "**Create Table of Contents**" to insert a new table of contents. -- The TOC is **automatically updated** on file save by default. To disable, please change the `toc.updateOnSave` option. -- The **indentation type (tab or spaces)** of TOC can be configured per file. Find the setting in the right bottom corner of VS Code's status bar. -- ***Note***: Be sure to also check the `list.indentationSize` option. -- To make TOC **compatible with GitHub or GitLab**, set option `slugifyMode` accordingly -- Three ways to **control which headings are present** in the TOC: -- Click to expand -- Easily add/update/remove **section numbering** - -
            - *In case you are seeing* ***unexpected TOC recognition****, you can add a* `` *comment above the list*. - -### List editing - -
            ***Note***: By default, this extension tries to determine indentation size for different lists according to CommonMark Spec. If you prefer to use a fixed tab size, please change the `list.indentationSize` setting. - -### Print Markdown to HTML - -- Commands `Markdown: Print current document to HTML` and `Markdown: Print documents to HTML` (batch mode) -- **Compatible** with other installed Markdown plugins (e.g. Markdown Footnotes) The exported HTML should look the same as inside VSCode. -- Use comment `` to specify a title of the exported HTML. -- Plain links to `.md` files will be converted to `.html`. -- It's recommended to print the exported HTML to PDF with browser (e.g. Chrome) if you want to share your documents with others. - -### GitHub Flavored Markdown - -- Table formatter - -
            - ***Note***: The key binding is Ctrl + Shift + I on Linux. See Visual Studio Code Key Bindings. -- Task lists - -### Math - -
            Please use Markdown+Math for dedicated math support. Be sure to disable `math.enabled` option of this extension. - -### Auto completions - -Tip: also support the option `completion.root` - -- Images/Files (respects option `search.exclude`) - -
            - Math functions (including option `katex.macros`) - -
            - ---- - -### Mocah Test Explorer - -- Lets you run mocha tests in the VSCode sidebar -- https://marketplace.visualstudio.com/items?itemName=hbenl.vscode-mocha-test-adapter - -### Features - -### Import command - -
            { - "npm-intellisense.importES6": true, - "npm-intellisense.importQuotes": "'", - "npm-intellisense.importLinebreak": ";\r\n", - "npm-intellisense.importDeclarationType": "const", - } - -### Import command (ES5) - -
            { - "npm-intellisense.importES6": false, - "npm-intellisense.importQuotes": "'", - "npm-intellisense.importLinebreak": ";\r\n", - "npm-intellisense.importDeclarationType": "const", - } - ---- - -### NPM Intellisense - -- Autocomlpetes npm module names when you are typing require or import. -- https://marketplace.visualstudio.com/items?itemName=christian-kohler.npm-intellisense - -### Features - -### Import command - -
            { - "npm-intellisense.importES6": true, - "npm-intellisense.importQuotes": "'", - "npm-intellisense.importLinebreak": ";\r\n", - "npm-intellisense.importDeclarationType": "const", - } - -### Import command (ES5) - -
            { - "npm-intellisense.importES6": false, - "npm-intellisense.importQuotes": "'", - "npm-intellisense.importLinebreak": ";\r\n", - "npm-intellisense.importDeclarationType": "const", - } - -### Scan devDependencies - -Npm intellisense scans only dependencies by default. Set scanDevDependencies to true to enable it for devDependencies too. - - { - "npm-intellisense.scanDevDependencies": true, - } - ---- - -### Path Intellisense - -- Auto completes filesystem paths when you are typing them -- https://marketplace.visualstudio.com/items?itemName=christian-kohler.path-intellisense - -### Usage - -
            ### Commerical Extensions - -### Quokka.js - -- A paid extension that does amazing things by showing the results of your javascript inline inside the editor window -- https://marketplace.visualstudio.com/items?itemName=WallabyJs.quokka-vscode - -### Quokka.js Visual Studio Code Extension - -Quokka.js is a developer productivity tool for rapid JavaScript / TypeScript prototyping. Runtime values are updated and displayed in your IDE next to your code, as you type. - -
            ### If you found this guide helpful feel free to checkout my other articles: - -A list of all of my articles to link to future posts -
            - -You should probably skip this one… seriously it's just for internal use! - -### OR GitHub/gists where I host similar content: - -bgoonz's gists -
            - -Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…gist.github.com
            - -bgoonz — Overview -
            - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
            - -### Or Checkout my personal Resource Site: - -Web-Dev-Resource-Hub -
            - -Edit descriptionweb-dev-resource-hub.netlify.app
            - -By Bryan Guner on [March 23, 2021](https://medium.com/p/ea91305cbd4a). - -Canonical link - -August 31, 2021. diff --git a/notes/articles/medium/markdown/VSCode-Extensions-Specifically-for-JavaScript.md b/notes/articles/medium/markdown/VSCode-Extensions-Specifically-for-JavaScript.md deleted file mode 100644 index cb1755bad7..0000000000 --- a/notes/articles/medium/markdown/VSCode-Extensions-Specifically-for-JavaScript.md +++ /dev/null @@ -1,326 +0,0 @@ -# VSCode Extensions Specifically for JavaScript Development - -VSCode Extensions that are indispensable in JavaScript development - ---- - -#### CODEX - -### VSCode Extensions Specifically for JavaScript Development - -#### VSCode Extensions that are indispensable in JavaScript development - -### Back and Forth - -- Adds backwards and forwards buttons to the toolbar in VSCode -- https://marketplace.visualstudio.com/items?itemName=nick-rudenko.back-n-forth - -
            - ---- - -### Bracket Pair Colorizer 2 - -- Colors matching brackets so it's easier to tell which brackets match. -- https://marketplace.visualstudio.com/items?itemName=CoenraadS.bracket-pair-colorizer-2 - -
            - ---- - -### Babel Javascript - -- A better syntax highlighter for JavaScript code -- https://marketplace.visualstudio.com/items?itemName=mgmcdermott.vscode-language-babel - -
            - ---- - -### Code Runner - -- Puts a "Play" button in your toolbar and let's you run code files by pressing it. -- https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner - -### Code Runner - -> Run code snippet or code file for multiple languages: **C, C++, Java, JavaScript, PHP, Python, Perl, Perl 6, Ruby, Go, Lua, Groovy, PowerShell, BAT/CMD, BASH/SH, F\# Script, F\# (.NET Core), C\# Script, C\# (.NET Core), VBScript, TypeScript, CoffeeScript, Scala, Swift, Julia, Crystal, OCaml Script, R, AppleScript, Elixir, Visual Basic .NET, Clojure, Haxe, Objective-C, Rust, Racket, Scheme, AutoHotkey, AutoIt, Kotlin, Dart, Free Pascal, Haskell, Nim, D, Lisp, Kit, V, SCSS, Sass, CUDA, Less, Fortran**, and custom command - -### Features - -> Run code file of current active Text Editor - -> Run code file through context menu of file explorer - -> Run selected code snippet in Text Editor - -> Run code per Shebang - -> Run code per filename glob - -> Run custom command - -> Stop code running - -> View output in Output Window - -> Set default language to run - -> Select language to run - -> Support REPL by running code in Integrated Terminal - -### Usages - -#### To run code: - -- use shortcut `Ctrl+Alt+N` -- or press `F1` and then select/type `Run Code`, -- or right click the Text Editor and then click `Run Code` in editor context menu -- or click `Run Code` button in editor title menu -- or click `Run Code` button in context menu of file explorer -- To stop the running code: -- use shortcut `Ctrl+Alt+M` -- or press `F1` and then select/type `Stop Code Run` -- or right click the Output Channel and then click `Stop Code Run` in context menu - -
            - To select language to run, use shortcut `Ctrl+Alt+J`, or press `F1` and then select/type `Run By Language`, then type or select the language to run: e.g `php, javascript, bat, shellscript...` - -
            - To run custom command, then use shortcut `Ctrl+Alt+K`, or press `F1` and then select/type `Run Custom Command` - ---- - -### Color Highlight - -- Changes the background color of hex colors in your code to show you what color it actually is -- https://marketplace.visualstudio.com/items?itemName=naumovs.color-highlight - -
            ### Git Graph - -- Shows you a graphical representation of your git branches and commits -- https://marketplace.visualstudio.com/items?itemName=mhutchie.git-graph - -
            - ---- - -### GitLens - -- Adds tons of cool features to vscode, like viewing commits inline inside the editor -- https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens - -Here are just some of the **features** that GitLens provides, - -- effortless revision navigation (backwards and forwards) through the history of a file -- an unobtrusive current line blame annotation at the end of the line showing the commit and author who last modified the line, with more detailed blame information accessible on hover -- authorship code lens showing the most recent commit and number of authors at the top of files and/or on code blocks -- a status bar blame annotation showing the commit and author who last modified the current line -- on-demand **file annotations** in the editor gutter, including -- blame — shows the commit and author who last modified each line of a file -- changes — highlights any local (unpublished) changes or lines changed by the most recent commit -- heatmap — shows how recently lines were changed, relative to all the other changes in the file and to now (hot vs. cold) -- many rich **Side Bar views** -- a Commits view to visualize, explore, and manage Git commits -- a Repositories view to visualize, explore, and manage Git repositories -- a File History view to visualize, navigate, and explore the revision history of the current file or just the selected lines of the current file -- a Line History view to visualize, navigate, and explore the revision history of the selected lines of the current file -- a Branches view to visualize, explore, and manage Git branches -- a Remotes view to visualize, explore, and manage Git remotes and remote branches -- a Stashes view to visualize, explore, and manage Git stashes -- a Tags view to visualize, explore, and manage Git tags -- a Contributors view to visualize, navigate, and explore contributors -- a Search & Compare view to search and explore commit histories by message, author, files, id, etc, or visualize comparisons between branches, tags, commits, and more -- a Git Command Palette to provide guided (step-by-step) access to many common Git commands, as well as quick access to -- commits — history and search -- stashes -- status — current branch and working tree status -- a user-friendly interactive rebase editor to easily configure an interactive rebase session -- terminal links — `ctrl+click` on autolinks in the integrated terminal to quickly jump to more details for commits, branches, tags, and more -- rich remote provider integrations — GitHub, GitLab, Bitbucket, Azure DevOps -- issue and pull request auto-linking -- rich hover information provided for linked issues and pull requests (GitHub only) -- associates pull requests with branches and commits (GitHub only) -- many powerful commands for navigating and comparing revisions, and more -- user-defined modes for quickly toggling between sets of settings -- and so much more 😁 - -### Features - -#### Revision Navigation - -
            - ---- - -### Markdown All in One - -- Everything you need to help you write markdown files in VSCode -- https://marketplace.visualstudio.com/items?itemName=yzhang.markdown-all-in-one - -### Features - -### Keyboard shortcuts - -
            (Typo: multiple words) - -
            See full key binding list in the keyboard shortcuts section - -### Table of contents - -
            - Run command "**Create Table of Contents**" to insert a new table of contents. -- The TOC is **automatically updated** on file save by default. To disable, please change the `toc.updateOnSave` option. -- The **indentation type (tab or spaces)** of TOC can be configured per file. Find the setting in the right bottom corner of VS Code's status bar. -- ***Note***: Be sure to also check the `list.indentationSize` option. -- To make TOC **compatible with GitHub or GitLab**, set option `slugifyMode` accordingly -- Three ways to **control which headings are present** in the TOC: -- Click to expand -- Easily add/update/remove **section numbering** - -
            - *In case you are seeing* ***unexpected TOC recognition****, you can add a* `` *comment above the list*. - -### List editing - -
            ***Note***: By default, this extension tries to determine indentation size for different lists according to CommonMark Spec. If you prefer to use a fixed tab size, please change the `list.indentationSize` setting. - -### Print Markdown to HTML - -- Commands `Markdown: Print current document to HTML` and `Markdown: Print documents to HTML` (batch mode) -- **Compatible** with other installed Markdown plugins (e.g. Markdown Footnotes) The exported HTML should look the same as inside VSCode. -- Use comment `` to specify a title of the exported HTML. -- Plain links to `.md` files will be converted to `.html`. -- It's recommended to print the exported HTML to PDF with browser (e.g. Chrome) if you want to share your documents with others. - -### GitHub Flavored Markdown - -- Table formatter - -
            - ***Note***: The key binding is Ctrl + Shift + I on Linux. See Visual Studio Code Key Bindings. -- Task lists - -### Math - -
            Please use Markdown+Math for dedicated math support. Be sure to disable `math.enabled` option of this extension. - -### Auto completions - -Tip: also support the option `completion.root` - -- Images/Files (respects option `search.exclude`) - -
            - Math functions (including option `katex.macros`) - -
            - ---- - -### Mocah Test Explorer - -- Lets you run mocha tests in the VSCode sidebar -- https://marketplace.visualstudio.com/items?itemName=hbenl.vscode-mocha-test-adapter - -### Features - -### Import command - -
            { - "npm-intellisense.importES6": true, - "npm-intellisense.importQuotes": "'", - "npm-intellisense.importLinebreak": ";\r\n", - "npm-intellisense.importDeclarationType": "const", - } - -### Import command (ES5) - -
            { - "npm-intellisense.importES6": false, - "npm-intellisense.importQuotes": "'", - "npm-intellisense.importLinebreak": ";\r\n", - "npm-intellisense.importDeclarationType": "const", - } - ---- - -### NPM Intellisense - -- Autocomlpetes npm module names when you are typing require or import. -- https://marketplace.visualstudio.com/items?itemName=christian-kohler.npm-intellisense - -### Features - -### Import command - -
            { - "npm-intellisense.importES6": true, - "npm-intellisense.importQuotes": "'", - "npm-intellisense.importLinebreak": ";\r\n", - "npm-intellisense.importDeclarationType": "const", - } - -### Import command (ES5) - -
            { - "npm-intellisense.importES6": false, - "npm-intellisense.importQuotes": "'", - "npm-intellisense.importLinebreak": ";\r\n", - "npm-intellisense.importDeclarationType": "const", - } - -### Scan devDependencies - -Npm intellisense scans only dependencies by default. Set scanDevDependencies to true to enable it for devDependencies too. - - { - "npm-intellisense.scanDevDependencies": true, - } - ---- - -### Path Intellisense - -- Auto completes filesystem paths when you are typing them -- https://marketplace.visualstudio.com/items?itemName=christian-kohler.path-intellisense - -### Usage - -
            ### Commerical Extensions - -### Quokka.js - -- A paid extension that does amazing things by showing the results of your javascript inline inside the editor window -- https://marketplace.visualstudio.com/items?itemName=WallabyJs.quokka-vscode - -### Quokka.js Visual Studio Code Extension - -Quokka.js is a developer productivity tool for rapid JavaScript / TypeScript prototyping. Runtime values are updated and displayed in your IDE next to your code, as you type. - -
            ### If you found this guide helpful feel free to checkout my other articles: - -A list of all of my articles to link to future posts -
            - -You should probably skip this one… seriously it's just for internal use! - -### OR GitHub/gists where I host similar content: - -bgoonz's gists -
            - -Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…gist.github.com
            - -bgoonz — Overview -
            - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
            - -### Or Checkout my personal Resource Site: - -Web-Dev-Resource-Hub -
            - -Edit descriptionweb-dev-resource-hub.netlify.app
            - -By Bryan Guner on [March 23, 2021](https://medium.com/p/ea91305cbd4a). - -Canonical link - -August 6, 2021. diff --git a/notes/articles/medium/markdown/Web-Dev-Resources.md b/notes/articles/medium/markdown/Web-Dev-Resources.md deleted file mode 100644 index 0bfb0d7ed6..0000000000 --- a/notes/articles/medium/markdown/Web-Dev-Resources.md +++ /dev/null @@ -1,124 +0,0 @@ -# Web Dev Resources - -Web Development - ---- - -### Web Dev Resources - -
            Photo by Roman Synkevych on Unsplash
            Photo by Roman Synkevych on Unsplash
            ### Web Development - -- Check cross-browser compatibility for CSS, JavaScript and HTML -- Modern front-end Cheatsheets -- Check out what your favorite company's stack is -- A Guide to Becoming a Full-Stack Developer in 2017 -- What happens when you type a URL into a web browser - -### JavaScript - -- Airbnb JavaScript Style Guide -- Regular Expressions Demystified -- ECMAScript compatibility table - -### GIT - -- HubSpot's Intro to Git/GitHub including Pull Requests & Merging - -### Express - -- Express Starter - -### Node.js - -- Fetch vs. Axios.js for making http requests \#\# Sequelize -- Sequelize: Getting Started -- \[Sequelize reference by @tmkelly28\](https://github.com/tmkelly28/sequelize-reference) -- Short but useful Sequelize querying cheatsheet - -### Study Guides - -- Express & Sequelize Boilerplate/Study Guide - -### React - -- React Casts — Series of React tutorials by Cassio -- React Dev Tool Google Chrome Extension -- create-react-app: Create React apps with no build configuration. -- Find the perfect React starter template -- Formik — Build forms in React, without the tears 😭 - -### Redux - -- Getting Started with Redux (free course by Dan Abramov) -- Building React Applications with Idiomatic Redux (free course by Dan Abramov) -- Redux Dev Tool Chrome Extension - -### Redux Middleware - -- redux-freeze: avoid accidental in-place mutations of state -- redux-saga: manage redux side-effects with es6 generators -- redux-promise-middleware: A thunk alternative with more bells and whistles \#\# CSS -- Specificity Calculator -- Tool for making clip-paths quickly with CSS - -### Command Line - -- Useful commands -- Get your IP address in Mac OSX/Unix: `ifconfig | grep 'inet '` - -### Atom - -- Atom command cheat sheet - -### VS Code - -- Keystroke cheat sheet -- Daniel's Config - -### Sublime - -- Keystroke cheat sheet -- Configuring Sublime Text 3 for Modern ES6 JS Projects - -### Whiteboard Interviews - -- algoexpert.io (Made by FSA alumni) -- JavaScript implementation of popular algorithms and data structures -- Code Wars -- Geeks for Geeks -- Interview Cake -- Leet Code -- Coder Byte -- Hacker Rank -- Cracking the Coding Interview - -Here's a repo where I hoard resource lists! - -bgoonz/Cumulative-Resource-List -
            - -Inspired by Awesome Lists. Contribute to bgoonz/Cumulative-Resource-List development by creating an account on GitHub.github.com
            - ---- - -#### If you found this guide helpful feel free to checkout my GitHub/gist's where I host similar content: - -> bgoonz's gists · GitHub - -bgoonz — Overview -
            - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
            - -Or Checkout my personal Resource Site: - -a/A-Student-Resources -
            - -Edit descriptiongoofy-euclid-1cd736.netlify.app
            - -By Bryan Guner on [March 7, 2021](https://medium.com/p/ec1975773d7d). - -Canonical link - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Web-Dev.md b/notes/articles/medium/markdown/Web-Dev.md deleted file mode 100644 index 125a3733ba..0000000000 --- a/notes/articles/medium/markdown/Web-Dev.md +++ /dev/null @@ -1,124 +0,0 @@ -# Web Dev Resources - -Web Development - ---- - -### Web Dev Resources - -
            Photo by Roman Synkevych on Unsplash
            Photo by Roman Synkevych on Unsplash
            ### Web Development - -- Check cross-browser compatibility for CSS, JavaScript and HTML -- Modern front-end Cheatsheets -- Check out what your favorite company's stack is -- A Guide to Becoming a Full-Stack Developer in 2017 -- What happens when you type a URL into a web browser - -### JavaScript - -- Airbnb JavaScript Style Guide -- Regular Expressions Demystified -- ECMAScript compatibility table - -### GIT - -- HubSpot's Intro to Git/GitHub including Pull Requests & Merging - -### Express - -- Express Starter - -### Node.js - -- Fetch vs. Axios.js for making http requests \#\# Sequelize -- Sequelize: Getting Started -- \[Sequelize reference by @tmkelly28\](https://github.com/tmkelly28/sequelize-reference) -- Short but useful Sequelize querying cheatsheet - -### Study Guides - -- Express & Sequelize Boilerplate/Study Guide - -### React - -- React Casts — Series of React tutorials by Cassio -- React Dev Tool Google Chrome Extension -- create-react-app: Create React apps with no build configuration. -- Find the perfect React starter template -- Formik — Build forms in React, without the tears 😭 - -### Redux - -- Getting Started with Redux (free course by Dan Abramov) -- Building React Applications with Idiomatic Redux (free course by Dan Abramov) -- Redux Dev Tool Chrome Extension - -### Redux Middleware - -- redux-freeze: avoid accidental in-place mutations of state -- redux-saga: manage redux side-effects with es6 generators -- redux-promise-middleware: A thunk alternative with more bells and whistles \#\# CSS -- Specificity Calculator -- Tool for making clip-paths quickly with CSS - -### Command Line - -- Useful commands -- Get your IP address in Mac OSX/Unix: `ifconfig | grep 'inet '` - -### Atom - -- Atom command cheat sheet - -### VS Code - -- Keystroke cheat sheet -- Daniel's Config - -### Sublime - -- Keystroke cheat sheet -- Configuring Sublime Text 3 for Modern ES6 JS Projects - -### Whiteboard Interviews - -- algoexpert.io (Made by FSA alumni) -- JavaScript implementation of popular algorithms and data structures -- Code Wars -- Geeks for Geeks -- Interview Cake -- Leet Code -- Coder Byte -- Hacker Rank -- Cracking the Coding Interview - -Here's a repo where I hoard resource lists! - -bgoonz/Cumulative-Resource-List -
            - -Inspired by Awesome Lists. Contribute to bgoonz/Cumulative-Resource-List development by creating an account on GitHub.github.com
            - ---- - -#### If you found this guide helpful feel free to checkout my GitHub/gist's where I host similar content: - -> bgoonz's gists · GitHub - -bgoonz — Overview -
            - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
            - -Or Checkout my personal Resource Site: - -a/A-Student-Resources -
            - -Edit descriptiongoofy-euclid-1cd736.netlify.app
            - -By Bryan Guner on [March 7, 2021](https://medium.com/p/ec1975773d7d). - -Canonical link - -August 6, 2021. diff --git a/notes/articles/medium/markdown/Web-Developer-Resource-List-Part-2.md b/notes/articles/medium/markdown/Web-Developer-Resource-List-Part-2.md deleted file mode 100644 index f109cb684b..0000000000 --- a/notes/articles/medium/markdown/Web-Developer-Resource-List-Part-2.md +++ /dev/null @@ -1,469 +0,0 @@ -# Web Developer Resource List Part 2 - -Because I compile these things compulsively anyway… - ---- - -### Web Developer Resource List Part 2 - -#### Because I compile these things compulsively anyway… - -
            - Ansible -- Awesome Lists -- CI/CD -- Data Science -- Docker -- DynamoDB -- Elasticsearch -- Environment Setups -- Epic Github Repos -- Golang -- Grafana -- Great Blogs -- Knowledge Base -- Kubernetes -- Kubernetes Storage -- Machine Learning -- Monitoring -- MongoDB -- Programming -- Queues -- Self Hosting -- Email Server Setups -- Mailscanner Server Setups -- Serverless -- Sysadmin References -- VPN -- Web Frameworks - -### Ansible - -- Kubernetes on LXC with Ansible - -### Awesome Lists - -- Awesome ChatOps -- Awesome Scalability -- Awesome Drone - -### Epic Github Repos - -- mlabouardy - -### Authentication - -- Nginx ES and Kibana Proxy with LDAP - -### Data Science - -- bulutyazilim — datascience awesome list - -### Grafana - -- Grafana Dashboards @mlabouardy - -### Docker - -#### Deploy Stacks to your Swarm: 🐳 ❤️ - -Logging: - -- shazChaudhry Swarm GELF Stack - -Metrics: - -- StefanProdan — Prometheus, Grafana, cAdvisor, Node Exporter and Alert Manager -- Mlabouardy — Telegraf, InfluxDB, Chronograf, Kapacitor & Slack - -#### Awesome Docker Repos - -- Jess's Dockerfiles -- Firecat53's Dockerfiles - -#### RaspberryPi ARM Images: - -- arm32v6/alpine:edge -- arm32v6/golang:alpine -- arm32v6/haproxy:alpine -- arm32v6/node:alpine -- arm32v6/openjdk:alpine -- arm32v6/postgres:alpine -- arm32v6/python:2.7-alpine3.6 -- arm32v6/python:3.6-alpine3.6 -- arm32v6/rabbitmq:alpine -- arm32v6/redis:alpine -- arm32v6/ruby:alpine3.6 -- arm32v6/tomcat:alpine -- arm32v6/traefik:latest -- arm32v7/debian:lates -- hypriot/rpi-redis -- jixer/rpi-mongo -- alexellis/armhf -- zeiot: rpi-prometheus stack -- larmog -- Rpi MongoDB -- ARM Swarm - -#### Docker Image Repositories - -- Docker Hub: arm32v6 -- Docker Hub: armv7 -- Github: Luvres Armhf -- Apache/PHP7 on Alpine -- Tomcat on Alpine -- Nginx (jwilder) -- Alpine Images (smebberson) -- SameerSbn -- Linuxserver.io -- Apache-PHP5 -- Apache-PHP-Email - -#### Docker-Awesome-Lists - -- Java Docker Services -- shouse Docker Awesome List - -#### Docker Blogs: - -- Whoami used in Traefik Docs -- Sqlite with Docker -- Rails with Postgres and Redis -- Async Tasks with Flask and Redis -- Flask and Postgres -- Elastic Beats on RaspberryPi - -#### Docker Storage - -- Rancher Convoy -- Flocker -- EMC ScaleIO -- RexRay Ceph with Ansible -- ContainX - -#### OpenFaas: - -- FaaS Releases -- FaaS Workshop - -#### Prometheus / Grafana on Swarm: - -- StefanProdan — SwarmProm -- Monitoring with Prometheus -- UschtWill — Prometheus Grafana Elastalert -- Chmod-Org Promethus with Blackbox -- Finestructure: Prometheus Tutorial - -### Logging / Kibana / Beats - -### Libraries - -- Loguru | Flask Example with Loguru - -### Frameworks - -- shazChaudhry Swarm GELF Stack - -### Continious Integration: - -#### Circle-CI - -- PHP with Circle-CI - -#### Concourse - -- Setup Concourse Environment with Docker -- Getting Started with Concourse and Docker -- Concourse Gated Pipelines -- Concourse Boilerplate - -#### Jenkins - -- Modess — PHP with Jenkins -- CI/CD Nodejs Tutorial with Jenkins -- CI/CD Nodejs Tutorial with Jenkins @medium -- Epic CICD workflow with Jenkins, Gitlab, Sonar, Nexus - -#### SwarmCi - -- SwarmCI - -#### Travis-CI - -- Getting Started with Travis-CI (Original Docs) -- Getting Started with Travis-CI (dwyl — nodejs) -- Blog Site with Travis-CI (Python) -- Build Tests with Python on Travis-CI -- Moving app with Travis-CI - -#### LambCI - -- LambCI - -### DynamoDB - -#### DynamoDB Docs - -- AWS DynamoDB: SQL to NoSQL - -#### DynamoDB Best Practices - -- Choosing the Right Partition Key -- 10 Things you should know - -#### DynamoDB General Info - -- Understanding DynamoDB - -### Elasticsearch - -#### Elasticsearch Documentation - -- General Recommendation -- How Many Shards in my Cluster -- Managing Time-Based Indices Efficiently -- Elasticsearch Best Practices (Bonsai.io) -- AWS ES — Scaling up my Domain - -#### Elasticsearch Cheetsheets: - -- My ES Cheatsheet - -#### Elasticsearch Blogs - -- Maximize Elasticsearch Indexing Performance -- Autoritative Guide to ES Performance Tuning -- Full text Search Queries -- Query Elasticsearch - -#### Elasticsearch Tools - -- Export Data from ES to ES - -### Environment Setups: - -- Golang - -### Knowledge Base - -### KB HTTPS - -- How does HTTPS work (Miguel Grinberg) - -### Kubernetes - -- Awesome Kubernetes -- Kubernetes Cheatsheet -- Getting Started: Python application on Kubernetes -- Kubernetes Deployments: The Ultimate Guide -- Prometheus Monitoring Stack with Kubernetes on DO -- Traefik as an Ingress Controller on Minikube -- Traefik Ingress with Kubernetes -- Manual Connect your Kubernetes from Outside -- HTTPS Letsencrypt on k3s -- Kubernetes: Nodeport vs Loadbalancer -- Prometheus Monitoring Pipeline on Kubernetes -- Building a Kubernetes CI/CD Pipeline with Rancher -- Building a Kubernetes CI/CD Pipeline with AWS -- Gitea and Drone CI/CD on k3s -- Serverless with Kubernetes using OpenFaaS and Linkerd2 -- Managing Kubernetes with kubectl -- OpenFaas Workshop on k3s -- Kubernetes Hands-On Lab with collabnix -- Create ReadWrite Persistent Volumes on Kubernetes -- Kubernetes Clusters with k3s and multipass - -### Kubernetes Storage - -- Kadalu -- Rancher: Longhorn Storage - -### Golang - -- Generate Fake Random Data with Golang -- Ultimate Golang Study Guide - -### Great Blogs - -- Exratione.com -- Joelabrahamsson.com -- Benjamin Cane -- Michael Herman -- Charles Leifer -- Labouardy -- Mark's Tech Blog - -### Linuxkit: - -- Getting Started with Linuxkit - -### Logging Stacks - -- shazChaudhry Swarm GELF Stack - -### Machine Learning: - -- PracticalAI - -### Metrics: - -- AppMetrics with Flask -- Scales: Metrics for Python -- Graphite: Python Flask Metrics - -### MongoDB: - -- Setup MongoDB Cluster -- MongoDB Scripts -- MongoDB Monitoring Tools -- Roles with MongoDB -- Queries: Guru99 -- Queries: Exploratory -- Queries: Tutorialspoint -- Queries: MongoDB Cheatsheet - -### Monitoring - -- Docker Swarm Monitoring Stack: Telegraf, InfluxDB, Chronograf, Kapacitor github source -- Docker Swarm Monitoring Stack: Prometheus, Grafana, cAdvisor, Node Exporter github source -- Prometheus Grafana Docker -- Prometheus Blog Seros -- Memcached Monitoring -- Nagios with Nagios Graph -- Slack Alerts with Prometheus -- Local Prometheus Stack -- Docker Swarm Promethus Setup #1 -- Docker Swarm Prometheus Setup #1: Blog -- Docker Swarm Promethus Setup #2 -- Docker Swarm Promethus Setup #3 (Blackbox) -- Uptime (fzaninotto) - -### Monitoring and Alerting - -- Cabot (Lightweight Pagerduty) -- Nagios - -### Monitoring as Statuspages - -- Statuspage (darkpixel -- Cachet - -### Programming - -#### Golang: - -- Golang Tutorials -- Golang Wiki - -#### Java: - -- Java Spring Boot Examples - -#### Python - -#### Ruby: - -- Learn Ruby: Learn Ruby the Hard Way -- Learn Ruby: Ruby for Beginners -- Learn Ruby: Launch School -- Learn Ruby: Arrays -- Install Ruby Environment on Mac - -#### Ruby on Rails: - -- Tutorial: Ruby On Rails -- Tutorial: ROR on Docker - -### Queues - -- Alpine SQS -- Kombu: Messaging library for Python -- Python Job Queues with Redis - -### Sysadmin References: - -- Sysadmin Command References -- Linux Performance Observability Tools -- Troubleshooting High IO Wait -- IO Monitoring in Linux -- IOStat and VMStat for Performance Monitoring -- Debugging Heavy Load - -### Self Hosting - -#### Email Server Setups - -- Extratione: Postfix Dovecot MySQL Virtual Users Postfixadmin -- Extratione: Postfix Dovecot MySQL Virtual Users Postfixadmin (Ubuntu 18) -- Linuxsize: Postfix Dovecot MySQL Virtual Users Postfixadmin -- Howtoforge: Postfix, MySQL, Dovecto, Dspam -- Linuxsize: VirtualUsers, MySQL, Postfix, Dovecot - -#### Mailscanner Server Setups - -- Spamassassin with Debian 8 - -#### Financial - -- SelfHosted Firefly - -#### Self Hosting Frameworks: - -- Sandstorm - -### Serverless - -- Serverless Zappa -- Serverless Contact Form -- Serverless Authentication on AWS (danilop) - -### VPN: - -#### VPN-Howto: - -- Ubuntu OpenVPN Script -- Ubuntu IPSec Script -- DO — Setup OpenVPN on Ubuntu -- Elasticshosts — IPSec VPN -- PPTP/IPSec/OpenVPN Auto Install - -### Website Templates - -#### Resume Templates - -- johnmarcampbell resume-site - -### Web Frameworks - -#### Python Flask: - -- Python Flask Upload Example -- Awesome Flask — humiaozuzu -- Awesome Flask Apps — Greyli -- Flask over HTTPS (MG) -- Flask Advanced Patterns -- Flask MVC Boilerplate - -### If you found this guide helpful feel free to checkout my GitHub/gists where I host similar content: - -bgoonz's gists -
            - -Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…gist.github.com
            - -bgoonz — Overview -
            - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
            - -### Discover More: - -Web-Dev-Hub -
            - -Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…bgoonz-blog.netlify.app
            - -By Bryan Guner on [March 19, 2021](https://medium.com/p/9c5cb56ab263). - -Canonical link - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Web-Developer-Resource-List-Part-4.md b/notes/articles/medium/markdown/Web-Developer-Resource-List-Part-4.md deleted file mode 100644 index 75f2ebc085..0000000000 --- a/notes/articles/medium/markdown/Web-Developer-Resource-List-Part-4.md +++ /dev/null @@ -1,603 +0,0 @@ -# Web Developer Resource List Part 4 - -A all encompassing list of tools and resources for web developers - ---- - -### Web Developer Resource List Part 4 - -A all encompassing list of tools and resources for web developers - -
            - -### General resources - -- Devdocs.io: Fast, offline, and free documentation browser for developers. Search 100+ docs in one web app: HTML, CSS, JavaScript, PHP, Ruby, Python, Go, C, C++… -- DevHints: cheatsheets for many web technologies -- Carbon: use this to share images of your code in presentations etc -- Badgen: -- Shields.io: -- to your documentation/readmes -- Git Flight Rules: A guide for astronauts (now, programmers using Git) about what to do when things go wrong. -- browser-2020: Things you can do with a browser in 2020 ☕️ - -### 📦 Finding and vetting npm packages - -- pika: A searchable catalog of modern "module" packages on npm -- npms: A better and open source search for node packages -- emma: 📦 Terminal assistant to find and install node packages -- npmvet: A simple CLI tool for vetting npm package versions -- Bundlephobia: See the "cost" of any npm package -- Snyk: Find any security vulnerabilities for any npm package. Search their database here: `https://snyk.io/vuln/npm:{package}` e.g. https://snyk.io/vuln/npm:react -- runpkg: Explore, learn about and perform static analysis on npm packages in the browser - -### 🎨 CSS - -- CSS Tricks "Complete Guide to Flexbox" -- CSS Tricks "Complete Guide to Grid" -- Cubic bezier curve creator -- Ceaser: Cubic bezier curve generator -- CSS Triggers: find out what CSS properties trigger Paint/Layout/Composite renders -- Fluid-responsive font-size calculator: To scale typography smoothly across viewport widths. -- Browserhacks: Browserhacks is an extensive list of browser specific CSS and JavaScript hacks from all over the interwebs -- Absolute centering: useful techniques for absolute centering in CSS -- modern-css-reset: A bare-bones CSS reset for modern web development -- CSSFX: Beautifully simple click-to-copy CSS effects -- Shape Divider App - -### CSS-in-JS - -- CSS-in-JS libraries -- Styled Components: CSS-in-JS for React -- Emotion: CSS-in-JS library -- linaria: Zero-runtime CSS in JS library -- Design System Utils: Design system framework for modern front-end projects (made by me!) -- Polished: A lightweight toolset for writing styles in JavaScript -- styled-by: Simple and powerful lib to handle styled props in your components -- xstyled: Consistent theme based CSS for styled-components 💅 -- Theme UI: Build consistent, themeable React apps based on constraint-based design principles - -### JavaScript - -### Useful JS links - -- JS module import/export syntax -- JavaScript Event KeyCodes -- JavaScript Visualizer -- Does it mutate? -- jsPerf: JavaScript performance playground -- modern-js-cheatsheet -- HTML DOM: Common tasks of managing HTML DOM with vanilla JavaScript - -### Framework agnostic packages - -### General utilities - -- Lodash: A modern JavaScript utility library delivering modularity, performance & extras. -- Just: A library of dependency-free utilities that do just do one thing (like Lodash but smaller) -- Install each util independently -- Read the tradeoffs document to see if Lodash is better -- tiny-get: A minimal-weight lodash.get equivalent utility -- evt: A type safe replacement for node's EventEmitter -- liteready: A lightweight DOM ready. -- passport: Simple, unobtrusive authentication for Node.js -- get-size: Get the size of elements -- length.js: Library for length units conversion -- action-outside: Invoke a callback function when clicked or tabbed outside one or multiple DOM elements -- select-dom: Lightweight `querySelector`/`All` wrapper that outputs an Array -- memoizee: Complete memoize/cache solution for JavaScript -- memoize-one: A memoization library which only remembers the latest invocation -- kind-of: Get the native JavaScript type of a value, fast. -- iterare: Array methods + ES6 Iterators = -- eases-jsnext: A grab-bag of modular easing equations -- normalizr: Normalizes nested JSON according to a schema -- lazy-value: Create a lazily evaluated value -- fast-equals: A blazing fast equality comparison, either shallow or deep -- fast-copy: A blazing fast deep object copier -- compute-scroll-into-view: Utility for calculating what should be scrolled, how it's scrolled is up to you -- arr: A collection of tiny, highly performant Array.prototype alternatives -- timedstorage: A library for storing and expiring objects in window.localstorage -- left-pad: String left pad -- dont-go: A small client-side library with zero dependencies to change the title and/or favicon of the page when it is inactive -- always-done: Handle completion and errors with elegance! Support for async/await, promises, callbacks, streams and observables. A drop-in replacement for async-done — pass 100% of its tests plus more -- words: Linguistic javascript modules -- no-scroll: Disable scrolling on an element that would otherwise scroll -- libphonenumber-js: A simpler (and smaller) rewrite of Google Android's libphonenumber library -- text-mask: Input mask for React, Angular, Ember, Vue, & plain JavaScript -- msk: Small library to mask strings -- focus-trap: Trap focus within a DOM node -- tinykeys: A tiny (~400 B) & modern library for keybindings -- clack: A modern keyboard shortcut library written in Typescript -- clack-react: React support for @reasonink/clack -- js-humanize: Humanize large numbers -- sub-in: 🥙 A tiny (115B) find-and-replace utility for strings in Javascript -- color-hash: Generate color based on the given string (using HSL color space and BKDRHash) -- title: A service for capitalizing your title properly -- string-similarity: Finds degree of similarity between two strings, based on Dice's Coefficient, which is mostly better than Levenshtein distance -- cuid: Collision-resistant ids optimized for horizontal scaling and performance -- obj-str: A tiny (96B) library for serializing Object values to Strings. Also serves as a faster & smaller drop-in replacement for the classnames module -- clsx: A tiny (223B) utility for constructing className strings conditionally. Also serves as a faster & smaller drop-in replacement for the classnames module -- xstate: State machines and statecharts for the modern web -- tasktimer: An accurate timer utility for running periodic tasks on the given interval ticks or dates. (Node and Browser) -- rough-notation: Create and animate hand-drawn annotations on a web page - -### Async - -- axios: Promise based HTTP client for the browser and node.js -- axios-retry: Axios plugin that intercepts failed requests and retries them whenever possible -- redaxios: The Axios API, as an 800 byte Fetch wrapper -- cross-fetch: Universal WHATWG Fetch API for Node, Browsers and React Native -- awaity: A functional, lightweight alternative to bluebird.js, built with `async` / `await` in mind -- loadjs: A tiny async loader / dependency manager for modern browsers (789 bytes) -- await-to-js: Async await wrapper for easy error handling without try-catch - -### Node - -- Fastify: Fast and low overhead web framework, for Node.js -- Express -- helmet: Help secure Express apps with various HTTP headers -- reqresnext: Tiny helper for express middleware testing -- lusca: Application security for express apps -- cookie-session: Simple cookie-based session middleware -- nodebestpractices: The largest Node.JS best practices list. Curated from the top ranked articles and always updated -- dumper.js: A better and pretty variable inspector for your Node.js applications -- http-terminator: Gracefully terminates HTTP(S) server -- uuid: Generate RFC-compliant UUIDs in JavaScript -- http-errors: Create HTTP Errors -- boom: HTTP-friendly error objects -- deno: A secure JavaScript and TypeScript runtime -- nanomatch: Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but without support for extended globs (extglobs), posix brackets or braces, and with complete Bash 4.3 wildcard support: ("\*", "\*\*", and "?") -- yn: Parse yes/no like values -- ncp: Asynchronous recursive file copying with Node.js - -#### Logging - -- pino: 🌲 super fast, all natural json logger 🌲 -- caterpillar: Caterpillar is the ultimate logging system for Deno, Node.js, and Web Browsers -- cabin: Cabin is the best JavaScript and Node.js logging service and logging npm package - -### Responsive - -- responsive-watch: Watch some media queries and react when they change -- tornis: Tornis helps you watch and respond to changes in your browser's viewport 🌲 -- actual: Determine actual CSS media query breakpoints via JavaScript - -### Media and Images - -- images-loaded: Wait for images to load using promises. No dependencies. -- lazysizes: High performance and SEO friendly lazy loader for images (responsive and normal), iframes and more, that detects any visibility changes triggered through user interaction, CSS or JavaScript without configuration. - -#### Image services - -- sharp: High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP and TIFF images. Uses the libvips library. -- IMGIX: Real-time image processing and image CDN - -### Date - -- date-fns: Modern JavaScript date utility library -- tinydate: A tiny (337B) reusable date formatter. Extremely fast! -- tinytime: ⏰ A straightforward date and time formatter in <1kb - -### Scrolling - -- scroll-watcher -- scrolldir: Leverage Vertical Scroll Direction with CSS - -### Carousels - -- Flickity -- Swiper - -### Animation - -- ramjet: Morph DOM elements from one state to another with smooth animations and transitions -- anime: JavaScript Animation Engine -- GSAP:the standard for JavaScript HTML5 animation | GreenSock -- Vanilla-tilt.js: A smooth 3D tilt javascript library forked from Tilt.js - -### Web workers - -- workerize: Run a module in a Web Worker -- greenlet: Move an async function into its own thread. A simplified single-function version of workerize. - -### Immutable - -- immer: Create the next immutable state tree by simply modifying the current tree -- use-immer: Use immer to drive state with a React hooks -- unchanged: A tiny, fast, unopinionated handler for updating JS objects and arrays immutably -- seamless-immutable: Immutable data structures for JavaScript which are backwards-compatible with normal JS Arrays and Objectsseamless-immutable\` -- mutik: A tiny (495B) immutable state management library based on Immer - -### Typography - -- fitty: Makes text fit perfectly - -### Polyfills - -- resize-observer-polyfill:A polyfill for the Resize Observer API - -### ⚛️ React - -reactjs.org - -- create-react-app: Create React apps with no build configuration -- react-app-rewired: Override create-react-app webpack configs without ejecting -- react-bits: ✨ React patterns, techniques, tips and tricks ✨ - -### React-specific libs: - -- react-powerplug: Renderless Containers -- formik: Build forms in React, without the tears 😭 -- react-router: Declarative routing for React -- Reach Router -- react-fns: React Components for common Web APIs -- react-portal: React component for transportation of modals, lightboxes, loading bars… to document.body -- react-ideal-image: 🖼️ An Almost Ideal React Image Component -- react-adopt: Compose render props components like a pro -- downshift -- react-loadable: A higher order component for loading components with promises -- react-portal: React component for transportation of modals, lightboxes, loading bars… to document.body -- js-lingui: 🌍📖: A readable, automated, and optimized (5 kb) internationalization (Intl / i18n) for JavaScript -- react-mq: Barebones CSS media query component for React, ~560 bytes -- react-media: CSS media queries for React. This is SSR compatible as well. -- merge-props: Merges className, style, and event handler props for React elements -- react-uid: Render-less container for generating UID for a11y, consistent react key, and any other good reason 🦄 -- clsx: A tiny (229B) utility for constructing `className` strings conditionally -- Framer Motion: An open source React library to power production-ready animations. Design fluid animations for the web, across desktop and mobile -- react-axe: Accessibility auditing for React.js applications -- use-click-away: React hook to detect click or touch events outside an element -- react-tiny-virtual-list: A tiny but mighty 3kb list virtualization library, with zero dependencies 💪 Supports variable heights/widths, sticky items, scrolling to index, and more! -- react-laag: Primitives to build things like tooltips, dropdown menu's and popovers in React -- react-dnd: Drag and Drop for React - -#### React Hooks - -- swr: React Hooks library for remote data fetching -- Hooks.Guide: Collection of React hooks curated by the community -- useHooks: Easy to understand React Hook recipes -- beautiful-react-hooks: 🔥A collection of beautiful and (hopefully) useful React hooks to speed-up your components and hooks development 🔥 -- react-adaptive-hooks: Deliver experiences best suited to a user's device and network constraints - -### State management - -- zustand: 🐻 Bear necessities for state management in React -- redux: Predictable state container for JavaScript apps -- reselect: Selector library for Redux -- redux-saga: An alternative side effect model for Redux apps -- redux-saga-routines: Routines for redux-saga -- redux-thunk: Thunk middleware for Redux -- awesome-redux: Catalog of Redux Libraries & Learning Material -- parket: A library to manage application state, heavily inspired by mobx-state-tree -- unstated: State so simple, it goes without saying -- mergeState: How to Stop Worrying and Use Nested Object/Array in React/Redux States -- effector: The state manager ☄️ -- Recoil: Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React. - -### Server-rendered React - -- Next.js (repo): — Framework for server-rendered or statically-exported React apps -- next-plugins - -### Static site generators - -- Gatsby: Blazing fast static site generator for React - -### Microservices/Serverless - -- micro -- awesome-micro - -### TypeScript - -typescriptlang.org - -- What's new in TypeScript: Microsoft/TypeScript Wiki -- TypeScript Deep Dive -- TypeScript Evolution -- JSON to Typescript Interface -- react-typescript-cheatsheet: a cheatsheet for react users using typescript with react for the first (or nth!) time -- clean-code-typescript: Clean Code concepts adapted for TypeScript - -### Command Line, Terminal and shells - -Fish shell: The user-friendly command line shell - -- My fish_config -- awesome-fish: A curated list of packages, prompts, and resources for the amazing fish shell -- Starship: Cross-Shell Prompt -- tide: 🌊 A modern prompt manager for the Fish shell - -### Creating CLI apps - -- gluegun: A delightful toolkit for building Node-powered CLIs -- inquirer: A collection of common interactive command line user interfaces -- commander: node.js command-line interfaces made easy -- sade: Sade is a small but powerful tool for building command-line interface (CLI) applications for Node.js that are fast, responsive, and helpful! - -### CLI apps - -- hub: hub is an extension to command-line git that helps you do everyday GitHub tasks without ever leaving the terminal -- serve: Static file serving and directory listing -- awesome-cli-apps: A curated list of command line apps -- SpaceVim: A community-driven modular vim distribution — The ultimate vim configuration - -### Tooling - -### Code bundlers - -- preconstruct: 🎁 Dev and build your code painlessly in monorepos -- Webpack: script/asset bundler -- Webpack recipes -- ifdef-loader: Webpack loader for JavaScript/TypeScript conditional compilation -- Parcel: Blazing fast, zero configuration web application bundler -- microbundle: Zero-configuration bundler for tiny modules -- rollup.js: Rollup is a module bundler for JavaScript -- ncc: Node.js Compiler Collection. Simple CLI for compiling a Node.js module into a single file, together with all its dependencies, gcc-style. -- fastpack: Pack JS code into a single bundle fast & easy - -### Package management and publishing - -- np: A better `npm publish` -- size-limit: Prevent JS libraries bloat. If you accidentally add a massive dependency, Size Limit will throw an error -- bundlesize: Keep your bundle size in check -- nps: All the benefits of npm scripts without the cost of a bloated package.json and limits of json -- Dependabot: Dependabot creates pull requests to keep your dependencies secure and up-to-date -- npm-config (docs): More than you probably want to know about npm configuration -- patch-package: Fix broken node modules with no fuss 📦👌 -- madge: Create graphs from your CommonJS, AMD or ES6 module dependencies - -### Commit hooks - -- lefthook: Fast and powerful Git hooks manager for any type of projects -- husky: Git hooks made easy -- lint-staged: 🚫💩: Run linters on git staged files -- lefthook: Fast and powerful Git hooks manager for any type of projects - -### Testing - -- Jest: Delightful JavaScript Testing -- majestic: Zero config UI for Jest -- jest-chain: Chain Jest matchers together to create one powerful assertion 🃏⛓ -- jest-extended: — Additional Jest matchers 🃏💪 -- snapshot-diff: Diffing snapshot utility for Jest -- jest-date-mock: 🌗 Mock `Date` when run unit test cases with jest. Make tests of Date easier -- Cypress: end-to-end testing -- cypress-testing-library: 🐅 Simple and complete custom Cypress commands and utilities that encourage good testing practices -- cypress-axe: Custom commands for Cypress to run a11y checks with axe-core -- start-server-and-test: — Starts server, waits for URL, then runs test command; when the tests end, shuts down server -- dom-testing-library: 🐙 Simple and complete DOM testing utilities that encourage good testing practices -- react-testing-library 🐐: Simple and complete React DOM testing utilities that encourage good testing practices -- react-testing-library: React Testing Examples -- react-hooks-testing-library: 🐏 Simple and complete React hooks testing utilities that encourage good testing practices -- Chance: Random generator helper for JavaScript -- faker.js: generate massive amounts of fake data in Node.js and the browser -- nock: HTTP server mocking and expectations library for Node.js -- Stryker Mutator -- given2: Lazy variable evaluation for Jasmine, Mocha, Jest specs, inspired by Ruby and Rspec 💎 -- benny: A dead simple benchmarking framework for JS/TS libs -- benchmark.js: A benchmarking library. As used on jsPerf.com -- ui-testing-best-practices: The largest UI testing best practices list (lat update: April 2020) (work in progress) - -### Code formatting and linting - -- Prettier -- precise-commits: Painlessly apply Prettier by only formatting lines you have modified anyway! -- pretty-quick: Runs Prettier on your changed files -- Eslint -- eslint-plugin-prettier: ESLint plugin for prettier formatting -- eslint-config-prettier: Turns off all rules that are unnecessary or might conflict with Prettier -- eslint-plugin-react: — React specific linting rules for ESLint - -### Miscellaneous - -- npm-run-all: A CLI tool to run multiple npm-scripts in parallel or sequential -- cross-port-killer: Kill the process running on a given TCP port on Windows, Linux and Mac -- envinfo: Generate a report about your development environment for debugging and issue reporting -- mkcert: A simple zero-config tool to make locally trusted development certificates with any names you'd like - -### Progressive Web Apps - -- Workbox & (repo): JavaScript libraries for Progressive Web Apps - -### Code Sandboxes - -- CodeSandbox: CodeSandbox is perfect for React demo apps -- Codepen: Codepen is perfect for non-React front-end demos and prototypes -- CodeShare: Codeshare is useful for collaborating on a single file if devs are not in the same room -- Glitch - -### APIs - -- Postman: used to develop, test and monitor APIs -- MockAPI: create a mock API -- jsonbin: A personal JSON store as a RESTful service -- test-cors.org -- Reqres: A hosted REST-API ready to respond to your AJAX requests -- Mirage JS: An API mocking library for frontend developers -- Postwoman: API request builder - -### GraphQL - -- GraphQL Playground -- Apollo GraphQL: Apollo Data Graph Platform — unify APIs, microservices, and databases into a data graph that you can query with GraphQL -- Apollo Client (React): Apollo React GraphQL Docs -- graphql-directives: 🧭 A collection of custom GraphQL Schema Directives for use with Apollo Server -- urql: The highly customizable and versatile GraphQL client -- graphql-lodash: 🛠 Data manipulation for GraphQL queries with lodash syntax - -### JSON - -- JSON generator: generate a lot of custom JSON for your app/site -- JSON Editor Online: view/edit JSON in a better format -- fx: Command-line tool and terminal JSON viewer 🔥 - -### HTML - -- github.com/joshbuchea/HEAD: the definitive resource for everything that _could_ go in the head of your document -- MetaTags.io: Preview, Edit and Generate -- HEY META: Website Meta Tag Check -- Rich Link Preview - -### SVG - -- A Practical Guide to SVGs on the web -- Get Waves: Create SVG waves for your next design -- Blobmaker: Make organic SVG shapes for your next design -- flubber: Tools for smoother shape animations -- Hero Patterns: Free repeatable SVG background patterns for your web projects - -### Icons - -- ICONSVG: Quick customizable SVG icons for your project -- Simple Icons -- React Icons -- Evil Icons -- Icon Font & SVG Icon Sets ❍ IcoMoon -- SVG PORN -- Feather: Simply beautiful open source icons -- react-feather: React component for Feather icons -- System UIcons - -### SVG/Image Media compression - -- Squoosh -- SVGOMG: SVGO's Missing GUI - -### Conversions and unicode - -- Transform: All important transforms at one place ⭐️⭐️⭐️ this is so useful -- SVGR: The SVG to JSX transformer -- svg2jsx -- JSON to JavaScript object literal -- Unminify JS, CSS and HTML Code -- Multi-Encoder -- Unicode code converter - -### Features and feature detection - -- Can I Use…: Browser support tables for modern web technologies (HTML5, CSS3, JavaScript etc) -- Kangax JavaScript compatibility table - -### Performance - -- Bundlephobia: find the cost of adding a npm package to your bundle - -### Performance testing and monitoring - -- WebPageTest -- Lighthouse -- Calibre -- Website Speed Test Image Analysis Tool by Cloudinary - -### Design - -- Subtract Guides: Simple Rules for Designing Web & Mobile Forms - -### Design Systems and documentation - -- Storybook: UI dev environment you'll love to use -- react-styleguidist: — Isolated React component development environment with a living style guide -- Docusaurus: Easy to Maintain Open Source Documentation Websites -- Docz -- design-system-utils: — Design system framework for modern front-end projects -- Docute: The fastest way to create a documentation site for your project -- playroom: Design with JSX, powered by your own component library - -### Accessibility (A11y) - -Accessibility is an extremely important part of any web project. While the SOW, functional spec or user-stories might not directly mention a11y, it is up to each developer to ensure that best efforts are made to make our websites as accessible as possible. - -### DevOps - -HTTP Status Codes - -### Continuous integration - -- CircleCI: Paid. -- Bitrise: Paid. For iOS/Android apps -- Travis CI: Free for open-source - -### Docker - -- dockle: Container Image Linter for Security, Helping build the Best-Practice Docker Image, Easy to start - -### Hosting - -- Vercel -- Netlify - -### Domains - -- iwantmyname - -### Design - -### Typography - -- Modular Scale -- Adaptive Modular Scale -- Type Scale — A Visual Calculator - -### IDEs and Text Editors - -### VS Code - -- My VS Code extensions -- My preferences -- awesome-vscode: 🎨 A curated list of delightful VS Code packages and resources - -### Programming fonts - -- IBM Plex Mono -- iA-Fonts -- Input: Fonts for Code -- FiraCode -- fantasque-sans -- Jet Brains Mono - -### Code colour schemes - -- Monokai Pro -- Ayu (Mirage) -- Dracula: A dark theme for Visual Studio Code and 50+ apps -- Oceanic Next Theme -- 🌌 Night Owl: A VS Code dark theme for contrast for nighttime coding -- Nord -- VSCodeThemes -- themer: 🎨 themer takes a set of colors and generates themes for your apps (editors, terminals, wallpapers, and more) - -### Regular expressions - -- Regex101: Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript - -### If you found this guide helpful feel free to checkout my other articles: - -A list of all of my articles to link to future posts -
            - -You should probably skip this one… seriously it's just for internal use! - -### OR GitHub/gists where I host similar content: - -bgoonz's gists -
            - -Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…gist.github.com
            - -bgoonz — Overview -
            - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
            - -### Or Checkout my personal Resource Site: - -Web-Dev-Resource-Hub -
            - -Edit descriptionweb-dev-resource-hub.netlify.app
            - -By Bryan Guner on [March 28, 2021](https://medium.com/p/fd686892b9eb). - -Canonical link - -August 31, 2021. diff --git a/notes/articles/medium/markdown/Web-Developer-Resource-List-Part.md b/notes/articles/medium/markdown/Web-Developer-Resource-List-Part.md deleted file mode 100644 index 05a469a58d..0000000000 --- a/notes/articles/medium/markdown/Web-Developer-Resource-List-Part.md +++ /dev/null @@ -1,603 +0,0 @@ -# Web Developer Resource List Part 4 - -A all encompassing list of tools and resources for web developers - ---- - -### Web Developer Resource List Part 4 - -A all encompassing list of tools and resources for web developers - -
            - -### General resources - -- Devdocs.io: Fast, offline, and free documentation browser for developers. Search 100+ docs in one web app: HTML, CSS, JavaScript, PHP, Ruby, Python, Go, C, C++… -- DevHints: cheatsheets for many web technologies -- Carbon: use this to share images of your code in presentations etc -- Badgen: -- Shields.io: -- to your documentation/readmes -- Git Flight Rules: A guide for astronauts (now, programmers using Git) about what to do when things go wrong. -- browser-2020: Things you can do with a browser in 2020 ☕️ - -### 📦 Finding and vetting npm packages - -- pika: A searchable catalog of modern "module" packages on npm -- npms: A better and open source search for node packages -- emma: 📦 Terminal assistant to find and install node packages -- npmvet: A simple CLI tool for vetting npm package versions -- Bundlephobia: See the "cost" of any npm package -- Snyk: Find any security vulnerabilities for any npm package. Search their database here: `https://snyk.io/vuln/npm:{package}` e.g. https://snyk.io/vuln/npm:react -- runpkg: Explore, learn about and perform static analysis on npm packages in the browser - -### 🎨 CSS - -- CSS Tricks "Complete Guide to Flexbox" -- CSS Tricks "Complete Guide to Grid" -- Cubic bezier curve creator -- Ceaser: Cubic bezier curve generator -- CSS Triggers: find out what CSS properties trigger Paint/Layout/Composite renders -- Fluid-responsive font-size calculator: To scale typography smoothly across viewport widths. -- Browserhacks: Browserhacks is an extensive list of browser specific CSS and JavaScript hacks from all over the interwebs -- Absolute centering: useful techniques for absolute centering in CSS -- modern-css-reset: A bare-bones CSS reset for modern web development -- CSSFX: Beautifully simple click-to-copy CSS effects -- Shape Divider App - -### CSS-in-JS - -- CSS-in-JS libraries -- Styled Components: CSS-in-JS for React -- Emotion: CSS-in-JS library -- linaria: Zero-runtime CSS in JS library -- Design System Utils: Design system framework for modern front-end projects (made by me!) -- Polished: A lightweight toolset for writing styles in JavaScript -- styled-by: Simple and powerful lib to handle styled props in your components -- xstyled: Consistent theme based CSS for styled-components 💅 -- Theme UI: Build consistent, themeable React apps based on constraint-based design principles - -### JavaScript - -### Useful JS links - -- JS module import/export syntax -- JavaScript Event KeyCodes -- JavaScript Visualizer -- Does it mutate? -- jsPerf: JavaScript performance playground -- modern-js-cheatsheet -- HTML DOM: Common tasks of managing HTML DOM with vanilla JavaScript - -### Framework agnostic packages - -### General utilities - -- Lodash: A modern JavaScript utility library delivering modularity, performance & extras. -- Just: A library of dependency-free utilities that do just do one thing (like Lodash but smaller) -- Install each util independently -- Read the tradeoffs document to see if Lodash is better -- tiny-get: A minimal-weight lodash.get equivalent utility -- evt: A type safe replacement for node's EventEmitter -- liteready: A lightweight DOM ready. -- passport: Simple, unobtrusive authentication for Node.js -- get-size: Get the size of elements -- length.js: Library for length units conversion -- action-outside: Invoke a callback function when clicked or tabbed outside one or multiple DOM elements -- select-dom: Lightweight `querySelector`/`All` wrapper that outputs an Array -- memoizee: Complete memoize/cache solution for JavaScript -- memoize-one: A memoization library which only remembers the latest invocation -- kind-of: Get the native JavaScript type of a value, fast. -- iterare: Array methods + ES6 Iterators = -- eases-jsnext: A grab-bag of modular easing equations -- normalizr: Normalizes nested JSON according to a schema -- lazy-value: Create a lazily evaluated value -- fast-equals: A blazing fast equality comparison, either shallow or deep -- fast-copy: A blazing fast deep object copier -- compute-scroll-into-view: Utility for calculating what should be scrolled, how it's scrolled is up to you -- arr: A collection of tiny, highly performant Array.prototype alternatives -- timedstorage: A library for storing and expiring objects in window.localstorage -- left-pad: String left pad -- dont-go: A small client-side library with zero dependencies to change the title and/or favicon of the page when it is inactive -- always-done: Handle completion and errors with elegance! Support for async/await, promises, callbacks, streams and observables. A drop-in replacement for async-done — pass 100% of its tests plus more -- words: Linguistic javascript modules -- no-scroll: Disable scrolling on an element that would otherwise scroll -- libphonenumber-js: A simpler (and smaller) rewrite of Google Android's libphonenumber library -- text-mask: Input mask for React, Angular, Ember, Vue, & plain JavaScript -- msk: Small library to mask strings -- focus-trap: Trap focus within a DOM node -- tinykeys: A tiny (~400 B) & modern library for keybindings -- clack: A modern keyboard shortcut library written in Typescript -- clack-react: React support for @reasonink/clack -- js-humanize: Humanize large numbers -- sub-in: 🥙 A tiny (115B) find-and-replace utility for strings in Javascript -- color-hash: Generate color based on the given string (using HSL color space and BKDRHash) -- title: A service for capitalizing your title properly -- string-similarity: Finds degree of similarity between two strings, based on Dice's Coefficient, which is mostly better than Levenshtein distance -- cuid: Collision-resistant ids optimized for horizontal scaling and performance -- obj-str: A tiny (96B) library for serializing Object values to Strings. Also serves as a faster & smaller drop-in replacement for the classnames module -- clsx: A tiny (223B) utility for constructing className strings conditionally. Also serves as a faster & smaller drop-in replacement for the classnames module -- xstate: State machines and statecharts for the modern web -- tasktimer: An accurate timer utility for running periodic tasks on the given interval ticks or dates. (Node and Browser) -- rough-notation: Create and animate hand-drawn annotations on a web page - -### Async - -- axios: Promise based HTTP client for the browser and node.js -- axios-retry: Axios plugin that intercepts failed requests and retries them whenever possible -- redaxios: The Axios API, as an 800 byte Fetch wrapper -- cross-fetch: Universal WHATWG Fetch API for Node, Browsers and React Native -- awaity: A functional, lightweight alternative to bluebird.js, built with `async` / `await` in mind -- loadjs: A tiny async loader / dependency manager for modern browsers (789 bytes) -- await-to-js: Async await wrapper for easy error handling without try-catch - -### Node - -- Fastify: Fast and low overhead web framework, for Node.js -- Express -- helmet: Help secure Express apps with various HTTP headers -- reqresnext: Tiny helper for express middleware testing -- lusca: Application security for express apps -- cookie-session: Simple cookie-based session middleware -- nodebestpractices: The largest Node.JS best practices list. Curated from the top ranked articles and always updated -- dumper.js: A better and pretty variable inspector for your Node.js applications -- http-terminator: Gracefully terminates HTTP(S) server -- uuid: Generate RFC-compliant UUIDs in JavaScript -- http-errors: Create HTTP Errors -- boom: HTTP-friendly error objects -- deno: A secure JavaScript and TypeScript runtime -- nanomatch: Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but without support for extended globs (extglobs), posix brackets or braces, and with complete Bash 4.3 wildcard support: ("\*", "\*\*", and "?") -- yn: Parse yes/no like values -- ncp: Asynchronous recursive file copying with Node.js - -#### Logging - -- pino: 🌲 super fast, all natural json logger 🌲 -- caterpillar: Caterpillar is the ultimate logging system for Deno, Node.js, and Web Browsers -- cabin: Cabin is the best JavaScript and Node.js logging service and logging npm package - -### Responsive - -- responsive-watch: Watch some media queries and react when they change -- tornis: Tornis helps you watch and respond to changes in your browser's viewport 🌲 -- actual: Determine actual CSS media query breakpoints via JavaScript - -### Media and Images - -- images-loaded: Wait for images to load using promises. No dependencies. -- lazysizes: High performance and SEO friendly lazy loader for images (responsive and normal), iframes and more, that detects any visibility changes triggered through user interaction, CSS or JavaScript without configuration. - -#### Image services - -- sharp: High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP and TIFF images. Uses the libvips library. -- IMGIX: Real-time image processing and image CDN - -### Date - -- date-fns: Modern JavaScript date utility library -- tinydate: A tiny (337B) reusable date formatter. Extremely fast! -- tinytime: ⏰ A straightforward date and time formatter in <1kb - -### Scrolling - -- scroll-watcher -- scrolldir: Leverage Vertical Scroll Direction with CSS - -### Carousels - -- Flickity -- Swiper - -### Animation - -- ramjet: Morph DOM elements from one state to another with smooth animations and transitions -- anime: JavaScript Animation Engine -- GSAP:the standard for JavaScript HTML5 animation | GreenSock -- Vanilla-tilt.js: A smooth 3D tilt javascript library forked from Tilt.js - -### Web workers - -- workerize: Run a module in a Web Worker -- greenlet: Move an async function into its own thread. A simplified single-function version of workerize. - -### Immutable - -- immer: Create the next immutable state tree by simply modifying the current tree -- use-immer: Use immer to drive state with a React hooks -- unchanged: A tiny, fast, unopinionated handler for updating JS objects and arrays immutably -- seamless-immutable: Immutable data structures for JavaScript which are backwards-compatible with normal JS Arrays and Objectsseamless-immutable\` -- mutik: A tiny (495B) immutable state management library based on Immer - -### Typography - -- fitty: Makes text fit perfectly - -### Polyfills - -- resize-observer-polyfill:A polyfill for the Resize Observer API - -### ⚛️ React - -reactjs.org - -- create-react-app: Create React apps with no build configuration -- react-app-rewired: Override create-react-app webpack configs without ejecting -- react-bits: ✨ React patterns, techniques, tips and tricks ✨ - -### React-specific libs: - -- react-powerplug: Renderless Containers -- formik: Build forms in React, without the tears 😭 -- react-router: Declarative routing for React -- Reach Router -- react-fns: React Components for common Web APIs -- react-portal: React component for transportation of modals, lightboxes, loading bars… to document.body -- react-ideal-image: 🖼️ An Almost Ideal React Image Component -- react-adopt: Compose render props components like a pro -- downshift -- react-loadable: A higher order component for loading components with promises -- react-portal: React component for transportation of modals, lightboxes, loading bars… to document.body -- js-lingui: 🌍📖: A readable, automated, and optimized (5 kb) internationalization (Intl / i18n) for JavaScript -- react-mq: Barebones CSS media query component for React, ~560 bytes -- react-media: CSS media queries for React. This is SSR compatible as well. -- merge-props: Merges className, style, and event handler props for React elements -- react-uid: Render-less container for generating UID for a11y, consistent react key, and any other good reason 🦄 -- clsx: A tiny (229B) utility for constructing `className` strings conditionally -- Framer Motion: An open source React library to power production-ready animations. Design fluid animations for the web, across desktop and mobile -- react-axe: Accessibility auditing for React.js applications -- use-click-away: React hook to detect click or touch events outside an element -- react-tiny-virtual-list: A tiny but mighty 3kb list virtualization library, with zero dependencies 💪 Supports variable heights/widths, sticky items, scrolling to index, and more! -- react-laag: Primitives to build things like tooltips, dropdown menu's and popovers in React -- react-dnd: Drag and Drop for React - -#### React Hooks - -- swr: React Hooks library for remote data fetching -- Hooks.Guide: Collection of React hooks curated by the community -- useHooks: Easy to understand React Hook recipes -- beautiful-react-hooks: 🔥A collection of beautiful and (hopefully) useful React hooks to speed-up your components and hooks development 🔥 -- react-adaptive-hooks: Deliver experiences best suited to a user's device and network constraints - -### State management - -- zustand: 🐻 Bear necessities for state management in React -- redux: Predictable state container for JavaScript apps -- reselect: Selector library for Redux -- redux-saga: An alternative side effect model for Redux apps -- redux-saga-routines: Routines for redux-saga -- redux-thunk: Thunk middleware for Redux -- awesome-redux: Catalog of Redux Libraries & Learning Material -- parket: A library to manage application state, heavily inspired by mobx-state-tree -- unstated: State so simple, it goes without saying -- mergeState: How to Stop Worrying and Use Nested Object/Array in React/Redux States -- effector: The state manager ☄️ -- Recoil: Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React. - -### Server-rendered React - -- Next.js (repo): — Framework for server-rendered or statically-exported React apps -- next-plugins - -### Static site generators - -- Gatsby: Blazing fast static site generator for React - -### Microservices/Serverless - -- micro -- awesome-micro - -### TypeScript - -typescriptlang.org - -- What's new in TypeScript: Microsoft/TypeScript Wiki -- TypeScript Deep Dive -- TypeScript Evolution -- JSON to Typescript Interface -- react-typescript-cheatsheet: a cheatsheet for react users using typescript with react for the first (or nth!) time -- clean-code-typescript: Clean Code concepts adapted for TypeScript - -### Command Line, Terminal and shells - -Fish shell: The user-friendly command line shell - -- My fish_config -- awesome-fish: A curated list of packages, prompts, and resources for the amazing fish shell -- Starship: Cross-Shell Prompt -- tide: 🌊 A modern prompt manager for the Fish shell - -### Creating CLI apps - -- gluegun: A delightful toolkit for building Node-powered CLIs -- inquirer: A collection of common interactive command line user interfaces -- commander: node.js command-line interfaces made easy -- sade: Sade is a small but powerful tool for building command-line interface (CLI) applications for Node.js that are fast, responsive, and helpful! - -### CLI apps - -- hub: hub is an extension to command-line git that helps you do everyday GitHub tasks without ever leaving the terminal -- serve: Static file serving and directory listing -- awesome-cli-apps: A curated list of command line apps -- SpaceVim: A community-driven modular vim distribution — The ultimate vim configuration - -### Tooling - -### Code bundlers - -- preconstruct: 🎁 Dev and build your code painlessly in monorepos -- Webpack: script/asset bundler -- Webpack recipes -- ifdef-loader: Webpack loader for JavaScript/TypeScript conditional compilation -- Parcel: Blazing fast, zero configuration web application bundler -- microbundle: Zero-configuration bundler for tiny modules -- rollup.js: Rollup is a module bundler for JavaScript -- ncc: Node.js Compiler Collection. Simple CLI for compiling a Node.js module into a single file, together with all its dependencies, gcc-style. -- fastpack: Pack JS code into a single bundle fast & easy - -### Package management and publishing - -- np: A better `npm publish` -- size-limit: Prevent JS libraries bloat. If you accidentally add a massive dependency, Size Limit will throw an error -- bundlesize: Keep your bundle size in check -- nps: All the benefits of npm scripts without the cost of a bloated package.json and limits of json -- Dependabot: Dependabot creates pull requests to keep your dependencies secure and up-to-date -- npm-config (docs): More than you probably want to know about npm configuration -- patch-package: Fix broken node modules with no fuss 📦👌 -- madge: Create graphs from your CommonJS, AMD or ES6 module dependencies - -### Commit hooks - -- lefthook: Fast and powerful Git hooks manager for any type of projects -- husky: Git hooks made easy -- lint-staged: 🚫💩: Run linters on git staged files -- lefthook: Fast and powerful Git hooks manager for any type of projects - -### Testing - -- Jest: Delightful JavaScript Testing -- majestic: Zero config UI for Jest -- jest-chain: Chain Jest matchers together to create one powerful assertion 🃏⛓ -- jest-extended: — Additional Jest matchers 🃏💪 -- snapshot-diff: Diffing snapshot utility for Jest -- jest-date-mock: 🌗 Mock `Date` when run unit test cases with jest. Make tests of Date easier -- Cypress: end-to-end testing -- cypress-testing-library: 🐅 Simple and complete custom Cypress commands and utilities that encourage good testing practices -- cypress-axe: Custom commands for Cypress to run a11y checks with axe-core -- start-server-and-test: — Starts server, waits for URL, then runs test command; when the tests end, shuts down server -- dom-testing-library: 🐙 Simple and complete DOM testing utilities that encourage good testing practices -- react-testing-library 🐐: Simple and complete React DOM testing utilities that encourage good testing practices -- react-testing-library: React Testing Examples -- react-hooks-testing-library: 🐏 Simple and complete React hooks testing utilities that encourage good testing practices -- Chance: Random generator helper for JavaScript -- faker.js: generate massive amounts of fake data in Node.js and the browser -- nock: HTTP server mocking and expectations library for Node.js -- Stryker Mutator -- given2: Lazy variable evaluation for Jasmine, Mocha, Jest specs, inspired by Ruby and Rspec 💎 -- benny: A dead simple benchmarking framework for JS/TS libs -- benchmark.js: A benchmarking library. As used on jsPerf.com -- ui-testing-best-practices: The largest UI testing best practices list (lat update: April 2020) (work in progress) - -### Code formatting and linting - -- Prettier -- precise-commits: Painlessly apply Prettier by only formatting lines you have modified anyway! -- pretty-quick: Runs Prettier on your changed files -- Eslint -- eslint-plugin-prettier: ESLint plugin for prettier formatting -- eslint-config-prettier: Turns off all rules that are unnecessary or might conflict with Prettier -- eslint-plugin-react: — React specific linting rules for ESLint - -### Miscellaneous - -- npm-run-all: A CLI tool to run multiple npm-scripts in parallel or sequential -- cross-port-killer: Kill the process running on a given TCP port on Windows, Linux and Mac -- envinfo: Generate a report about your development environment for debugging and issue reporting -- mkcert: A simple zero-config tool to make locally trusted development certificates with any names you'd like - -### Progressive Web Apps - -- Workbox & (repo): JavaScript libraries for Progressive Web Apps - -### Code Sandboxes - -- CodeSandbox: CodeSandbox is perfect for React demo apps -- Codepen: Codepen is perfect for non-React front-end demos and prototypes -- CodeShare: Codeshare is useful for collaborating on a single file if devs are not in the same room -- Glitch - -### APIs - -- Postman: used to develop, test and monitor APIs -- MockAPI: create a mock API -- jsonbin: A personal JSON store as a RESTful service -- test-cors.org -- Reqres: A hosted REST-API ready to respond to your AJAX requests -- Mirage JS: An API mocking library for frontend developers -- Postwoman: API request builder - -### GraphQL - -- GraphQL Playground -- Apollo GraphQL: Apollo Data Graph Platform — unify APIs, microservices, and databases into a data graph that you can query with GraphQL -- Apollo Client (React): Apollo React GraphQL Docs -- graphql-directives: 🧭 A collection of custom GraphQL Schema Directives for use with Apollo Server -- urql: The highly customizable and versatile GraphQL client -- graphql-lodash: 🛠 Data manipulation for GraphQL queries with lodash syntax - -### JSON - -- JSON generator: generate a lot of custom JSON for your app/site -- JSON Editor Online: view/edit JSON in a better format -- fx: Command-line tool and terminal JSON viewer 🔥 - -### HTML - -- github.com/joshbuchea/HEAD: the definitive resource for everything that _could_ go in the head of your document -- MetaTags.io: Preview, Edit and Generate -- HEY META: Website Meta Tag Check -- Rich Link Preview - -### SVG - -- A Practical Guide to SVGs on the web -- Get Waves: Create SVG waves for your next design -- Blobmaker: Make organic SVG shapes for your next design -- flubber: Tools for smoother shape animations -- Hero Patterns: Free repeatable SVG background patterns for your web projects - -### Icons - -- ICONSVG: Quick customizable SVG icons for your project -- Simple Icons -- React Icons -- Evil Icons -- Icon Font & SVG Icon Sets ❍ IcoMoon -- SVG PORN -- Feather: Simply beautiful open source icons -- react-feather: React component for Feather icons -- System UIcons - -### SVG/Image Media compression - -- Squoosh -- SVGOMG: SVGO's Missing GUI - -### Conversions and unicode - -- Transform: All important transforms at one place ⭐️⭐️⭐️ this is so useful -- SVGR: The SVG to JSX transformer -- svg2jsx -- JSON to JavaScript object literal -- Unminify JS, CSS and HTML Code -- Multi-Encoder -- Unicode code converter - -### Features and feature detection - -- Can I Use…: Browser support tables for modern web technologies (HTML5, CSS3, JavaScript etc) -- Kangax JavaScript compatibility table - -### Performance - -- Bundlephobia: find the cost of adding a npm package to your bundle - -### Performance testing and monitoring - -- WebPageTest -- Lighthouse -- Calibre -- Website Speed Test Image Analysis Tool by Cloudinary - -### Design - -- Subtract Guides: Simple Rules for Designing Web & Mobile Forms - -### Design Systems and documentation - -- Storybook: UI dev environment you'll love to use -- react-styleguidist: — Isolated React component development environment with a living style guide -- Docusaurus: Easy to Maintain Open Source Documentation Websites -- Docz -- design-system-utils: — Design system framework for modern front-end projects -- Docute: The fastest way to create a documentation site for your project -- playroom: Design with JSX, powered by your own component library - -### Accessibility (A11y) - -Accessibility is an extremely important part of any web project. While the SOW, functional spec or user-stories might not directly mention a11y, it is up to each developer to ensure that best efforts are made to make our websites as accessible as possible. - -### DevOps - -HTTP Status Codes - -### Continuous integration - -- CircleCI: Paid. -- Bitrise: Paid. For iOS/Android apps -- Travis CI: Free for open-source - -### Docker - -- dockle: Container Image Linter for Security, Helping build the Best-Practice Docker Image, Easy to start - -### Hosting - -- Vercel -- Netlify - -### Domains - -- iwantmyname - -### Design - -### Typography - -- Modular Scale -- Adaptive Modular Scale -- Type Scale — A Visual Calculator - -### IDEs and Text Editors - -### VS Code - -- My VS Code extensions -- My preferences -- awesome-vscode: 🎨 A curated list of delightful VS Code packages and resources - -### Programming fonts - -- IBM Plex Mono -- iA-Fonts -- Input: Fonts for Code -- FiraCode -- fantasque-sans -- Jet Brains Mono - -### Code colour schemes - -- Monokai Pro -- Ayu (Mirage) -- Dracula: A dark theme for Visual Studio Code and 50+ apps -- Oceanic Next Theme -- 🌌 Night Owl: A VS Code dark theme for contrast for nighttime coding -- Nord -- VSCodeThemes -- themer: 🎨 themer takes a set of colors and generates themes for your apps (editors, terminals, wallpapers, and more) - -### Regular expressions - -- Regex101: Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript - -### If you found this guide helpful feel free to checkout my other articles: - -A list of all of my articles to link to future posts -
            - -You should probably skip this one… seriously it's just for internal use! - -### OR GitHub/gists where I host similar content: - -bgoonz's gists -
            - -Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…gist.github.com
            - -bgoonz — Overview -
            - -Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com
            - -### Or Checkout my personal Resource Site: - -Web-Dev-Resource-Hub -
            - -Edit descriptionweb-dev-resource-hub.netlify.app
            - -By Bryan Guner on [March 28, 2021](https://medium.com/p/fd686892b9eb). - -Canonical link - -August 6, 2021. diff --git a/notes/articles/medium/markdown/Web-Developer-s-Technical-Glossary.md b/notes/articles/medium/markdown/Web-Developer-s-Technical-Glossary.md deleted file mode 100644 index dfdfbbd6cb..0000000000 --- a/notes/articles/medium/markdown/Web-Developer-s-Technical-Glossary.md +++ /dev/null @@ -1,1543 +0,0 @@ -# Web Developer's Technical Glossary - -This will be a running list as I make updates! - ---- - -### Web Developer's Technical Glossary - -This will be a running list as I make updates! - -
            - ---- - ---- - -### Update Terms: - -### Access (Microsoft Access) - -A Relational Database Management System developed by Microsoft that is part of the Microsoft Office Professional suite. Microsoft Access is often used on websites running on the Windows platform with low traffic. - -### ActiveMovie - -A web technology originally developed by Microsoft for the purpose of streaming video from a webserver to a client. ActiveMovie is now known as DirectShow. - -### ActiveX - -A set of technologies developed by Microsoft for the purpose of sharing information between different applications. ActiveX grew out of two other Microsoft technologies, specifically OLE (Object Linking and Embedding) and COM (Component Object Model). ActiveX also makes it possible for web browsers to download and execute various Windows programs. - -### Algorithm - -A specific set of steps for carrying out certain tasks. Algorithms are used extensively in computer programming to arrive at a solution for a specific problem. The process of creating an algorithm involves documenting all the necessary steps needed to arrive at a solution and how to go about each step. A real world example of an algorithm would be a recipe. The collective instructions of a typical recipe (add ingredients, mix, stir, etc.) constitute an algorithm. - -### Anchor - -The part of a webpage where a link begins or ends. Learn more about links in our HTML links tutorial. - -### ANSI - -Stands for American National Standards Institute. ANSI is an organization responsible for such standards in the computer industry as the ANSI C Standard and FDDI (Fiber Distributed Data Interface) — the main set of protocols used to send data through fiber optic cables. - -### ANSI C - -An international standard developed for the C language by ANSI (American National Standards Institute). - -### ADO - -Stands for ActiveX Data Object. ADO is a technology developed by Microsoft that provides access to any kind of data source. - -### ADSL - -Stands for Asymmetrical Digital Subscriber Line. In this type of DSL connection, the upload speed is different from the download speed. - -### Allaire - -A company started by Jeremy and JJ Allaire which released the first version of ColdFusion in 1995. Allaire was purchased in 2001 by Macromedia. - -### Amaya - -An open source web browser and web editor in one! Developed by the W3C. Download Amaya. - -### Analog - -The opposite of digital. Analog refers to the transmission of continuous electronic signals that represent an infinite amount of values. - -### Animation - -The process by which a set of images simulate movement when they are shown in a specific order. - -### Anti-Virus Program - -Software whose purpose is to discover and eliminate computer viruses. - -### Apache - -A web server developed by the Apache Software Foundation. Apache Web Server is open source. It works with a range of operating systems including Linux, Unix, Solaris, and Windows. Download Apache. - -### Applet - -A program that is executed from within another program. - -### Archie - -A program used to search FTP sites for certain programs. - -### API - -Stands for Application Programming Interface. An API contains various routines, protocols, algorithms, and tools used for software development. An API also lets programs communicate with each other, or in the case of the web, web browsers or web servers can communicate with other programs through the use of an API. - -### ARPAnet - -Stands for Advanced Research Project Agency network. ARPAnet is the network that the internet was borne out of. Originally established in 1969, ARPAnet was used to test new technologies, and it linked together many universities and research centers. - -### Authentication - -The process by which a user, program, or computer is verified to be legitimate in various situations such as checking a password. - -### ASCII - -Stands for American Standard Code for Information Interchange. ASCII is a set of codes used to represent various characters including letters, numbers, and special control characters as numbers. Each character is assigned a number from 0 to 127. For example, capital E is assigned the value 45. HTML uses ASCII to transmit data over the web. - -### ASF - -Stands for Advanced Streaming Format. ASF is a technology developed by Microsoft for the purpose of streaming multimedia. - -### ASP - -Stands for Active Server Pages. ASP is a technology developed by Microsoft for the purpose of creating dynamic pages that have a.asp extension. Such pages utilize VBScript or JScript code. - -### ASX - -Stands for ASF Streaming Redirector. ASX is a technology developed by Microsft for Windows media for the purpose of storing information about ASF files in an XML format. - -### AVI - -Stands for Audi Video Interleave. AVI is a file format for compressed video files developed by Microsoft that is part of the Video for Windows technology. - -### Banner Ad - -An advertisement placed on a webpage which links to the advertiser's website. Banner ads can contain text, graphical images, animation, and sound. - -### Bandwidth - -The amount of data that can be transmitted over an internet connection in a specific period of time. Bandwidth is expressed in bits per second(bps) or bytes per second for digital devices, and as cycles per second or Hertz(Hz) for analong devices. - -### Baud - -The number of signals that can be sent over a data channel per second. The term 'baud' is named after the inventor of the Baudot telegraph code, J.M.E. Baudot. - -### BBS - -Stands for Bulletin Board System. A BBS is a web based public electronic system that allow users to dial in with a modem and share discussions, review messages left by other users, and share files. - -### Binary Data - -Data expressed in a number system that has only the digits 0 and 1. Such data is expressed in bits (binary digits), and is in machine readable form. - -### Bit - -Abbreviation for binary digit. A bit is a unit of data that can have a value of 0 or 1. It is the smallest unit of data that can be stored in a computer. - -### BMP - -Abbreviation for Bitmap — a format used for storing images. A Bitmap contains a representation of an image in computer memory which consists of rows and columns of dots. The Microsoft Paint program stores images in a Bitmap format. - -### Bookmark - -A stored link to a particular webpage or other web resource such as an image that can later be accessed by a user. - -### Browse - -The process by which a user accessess various web resources. - -### BPS - -Stands for Bits Per Second. BPS is the speed at which data is transmitted over the internet. - -### Browser - -Same as Web Browser. - -### Byte - -A unit of data containing 8 bits. A byte can store one text character. - -An advanced high-level computer programming language used for application development. C was originally developed by Dennis Ritchie at Bell Labs in the 1970's and was originally designed to be a systems programming language but since then has proven itself to be able to be used for various software applications such as business programs, engineering programs, and even games. The UNIX operating system is written in C. - -### C++ - -A descendant of C. The C++ language is an advanced high-level computer programming language used for application development . However C++ unlike C, is object-oriented. C++ was originally developed by Bjarne Stroustrup at Bell Labs. - -### C\# - -A language developed by Microsft that is a version of C++ and contains functions similar to the Java language. - -### Case Sensitive - -A situation where it is important if a letter or a set of letters are in upper or lower case. - -### Cache - -Pronounced as cash. In web terms, a cache is a storage space where the copies of web pages and other web resources such as images are stored. In general computer terms, a cache is also used for storage where it can be either a section of main memory that is reserved or an independent high-speed storage device. - -### Chat - -Communication between internet users that occurs through various mediums that allow for text-based communication such as instant message programs, chatrooms, and forums. - -### CGI - -Stands for Common Gateway Interface. CGI is a mechanism for transferring data between a web server and a CGI program. - -### CGI-Bin - -CGI-Bin is usually the name of the folder or directory on a web server that stores the CGI programs pertaining to the web server. - -### CGI Program - -Common Gateway Interface program. A CGI program is a program that manages the interaction between web servers and users, as well as handling the input and output from web servers. CGI programs can be written in a variety of languages including Java , Perl, C, and Visual Basic. - -### Cinepak - -A codec technology used for computer video originally developed by SuperMac Inc. - -### Click - -The process by which a user presses one of the mouse buttons to achieve a desired result such as opening a new page by clicking on a link or accessing a pop-up menu. - -### Clickthrough Rate - -The percentage of times that viewers of a webpage click on an advertisement link. For example, if 15 out of 100 viewers of a webpage click on an advertisement link, the clickthrough rate is 15%. - -### Codec - -An abbreviation for compressor/decompressor. Codec is a technology used for compressing and decompressing data. MPEG is a popular codec used for compressing and decompressing video. - -### Compression - -In web terms, compression is reducing the size of web resources such as webpages and images so that they are received and viewed quicker by the user. In general computer terms, compression is reducing the size of data so that it can be stored in a format that takes up less space. - -### Computer Virus - -A malicious program whose purpose is to harm a computer by deleting files, preventing log ins, and other malicious activities. Some viruses can even replicate themselves and attach onto non-malicious programs. - -### Cookie - -A small text file that a web server may store on a user's computer for the purpose of uniquely identifying the user during future visits to the website. - -### ColdFusion - -A web development software tool used to integrate databases and webpages. ColdFusion was originally created by the Allaire Corporation. - -### CSS - -Stands for Cascading Style Sheets. CSS is a language used for declaring stylesheets that describe how the content on webpages will appear. CSS is recommended by the World Wide Web Consortium (W3C) and can be used to define various styles for webpages including font size, font color, spacing between elements, and a background color/image. - -### Database - -A collection of data stored in a computer in such a way that a program or a webpage can easily find, select, and/or manipulate the desired data. Typically, databases are organized by fields, records and files. A field is one piece of data, a record is a collection of fields, and a file is a collection of records. - -### Database System - -A system used for the purposes of storing and manipulating data. There are various database systems including Microsoft Access, Oracle, SQL, and MySQL. - -### DB2 - -Short for Database 2. DB2 is a database system created by IBM which is used mostly on Unix and Solaris platforms. - -### DBA - -Stands for Database Administrator. A DBA is responsible for administering a database, whether it is a human or a software tool. Typical cuties of a DBA include installation, backup, maintenance, and implementation of databases. - -### DHCP - -Stands for Dynamic Host Configuration Protocol. DHCP is an internet protocol that assigns network devices dynamic IP addresses. - -### DHTML - -Stands for Dynamic HTML. DHTML refers to HTML content that changes dynamically. HTML content can change dynamically based on various factors including a users geographic location or data input by the user. - -### Dial-up Connection - -An analog internet connection that works through a phone line and a modem. - -### Digital - -The opposite of analog. Digital refers to a system that uses numbers or non-numeric symbols for the transmission of data as opposed to the transmission of continuous electronic signals. - -### DNS - -Stands for Domain Name System (or Service or Server). DNS is a system used to translate domain names into IP addresses. - -### DNS Server - -A web server that is running DNS. - -### DOM - -Stands for Document Object Model. The DOM is a set of rules for how elements on a webpage (text, frames, images, buttons, etc.) interact and are represented. - -### Domain - -A network that contains a group of computers and devices that are adminstered as one unit with a set of rules and procedures. - -### Domain Name - -The name used to identify a website. For example, www.yahoo.com - -### DOS - -Stands for Disk Operating System. DOS is short for MS-DOS — an operating system originally developed by Microsoft to be used in IBM personal computers. - -### Download - -The process by which data is transferred from a remote location to a local computer. - -### DSL - -Stands for Digital Subscriber Line. DSL is an internet connection that works over a regular telephone line, but at a much faster speed than dial-up, and also allows the user to be on the phone and on the internet at the same time. In addition, a DSL connection is digital unlike a dial-up connection which is analog. DSL speed ranges from 144 Kbps to 1.5Mbps (Mega bits per second). - -### DTD - -Stands for Document Type Definition. A DTD specifies a set of rules that are used to define how content can be displayed in an SGML, XML, or HTML document. Common rules in a DTD may include specifications on where certain tags are allowed, and which tags can or cannot appear within other tags. - -### Dynamic IP - -An IP address that changes every time a device is connected to the internet. In some cases, an IP address of a device can change while it is connected. - -### E-mail - -Abbreviation for Electronic Mail. E-mail refers to electronic messages that are sent over communications networks on the internet. E-mail is sent and retrieved with various protocols including SMTP, POP3, and IMAP. - -### E-mail Address - -A unique name that is used to identify and send e-mail messages to a person or organization on the internet. The format for an e-mail address is username@hostname.domain Example: john@mail.com - -### E-mail Server - -Also known as a mail server. An E-mail server is a server whose tasks include storing e-mail, defining rules in regards to the destination of specific messages, storing a database of users that are recognized by the mail server, and transferring messages to and from other mail servers and e-mail programs. - -### Encryption - -The process by which data is converted into a secret code from its original form via some algorithm. The data in its original form can then only be read by those who can reverse the encryption. Encryption prevents unauthorized reading of data. - -### Ethernet - -A type of LAN architecture. - -### Firewall - -A system used to prevent access to a network or certain devices on a network. There are software as well as hardware firewalls. - -### Flash - -A vector based animation technology originally developed by FutureWave Software. Flash was known as FutureSplash until 1997, when FutureWave Software was bought by MacroMedia Inc. Flash is used to create various animations and graphics that can be displayed in any modern web browser that contains the necessary plug-in. - -### Form - -A collection of fields that are filled with data and submitted. - -### Forum - -An online discussion group devoted to various subjects. Forum is synonomous with Newsgroup. - -### Frame - -In web terms, a frame is a part of the browsers display area which actually contains a different web page. In general computer terms, a frame is a rectangular area which can contain graphical components such as buttons and textboxes, as well as images and text. - -### FrontPage - -A software tool used for web development. FrontPage was originally created by Vermeer Technologies Inc. The company was later bought by Microsoft, at which point Frontpage became Microsoft Frontpage. - -### FTP - -Stands for File Transfer Protocol. FTP is a protocol that typically runs on port 21 and is used to send files between two computers through the use of specific FTP commands. - -### FTP Server - -A software tool installed on a computer so that users can log in, upload files to it and get files from it using the FTP protocol. - -### Firewall - -A system used to prevent access to a network or certain devices on a network. There are software as well as hardware firewalls. - -### Gateway - -A device on a network that acts as an entry point to another network. - -### GIF - -Stands for Graphics Interchange Format. GIF is a graphics format developed by CompuServe used for storing compressed image files. The GIF format is one of the most common image formats on the internet. - -### GB - -An abbreviation for gigabyte or gigabytes. Example: 1GB (1 gigabyte), 5GB (5 gigabytes) - -### Gigabyte - -A unit of data consisting of 1024 megabytes. Related terms: byte, kilobyte, and megabyte. - -### Graphics - -Visual images displayed on a computer. - -### Graphics Monitor - -A display monitor that is capable of displaying graphics. - -### Graphics Printer - -A printer that is capable of printing graphics. - -### Graphical Banner - -A Banner Ad that contains graphical elements instead of just text. - -### Helper application - -A program launched to display content that is retrieved by a web browser. Some helper applications include Windows Media Player and RealPlayer for playing streaming video files. - -### Home Page - -The root (main) page of a web site. The page that is displayed by default when a web site is visited. For example, when you enter www.landofcode.com into your web browser and visit this website, the page that is displayed by default is index.html - -### Host - -A computer that is accessed by a user from a remote location, also any computer on a network. - -### Hosting - -The process of providing services by which data will be stored on a network device. Users that want to access such data can then request it from the host. For example, through web hosting individuals or organizations can store the contents of their websites on network devices which can be accessed by various users who request it. - -### HTML - -Stands for Hyper Text Markup Language. HTML is a markup language that is the core language of the world wide web. HTML defines the structure of a web document as well as the layout of text and various elements on it such as buttons and images. - -### HTML Document - -A document that is written in HTML. HTML document is synonomous with HTML page. - -### HTML Editor - -A software tool used for editing the content of webpages. HTML editors present the page being edited exactly the way it will be displayed in a web browser. - -### HTML Form - -A form on a webpage filled out by the user that sends data to the web server. - -### HTML Page - -A document that is written in HTML. HTML page is synonomous with HTML document. - -### HTML Tags - -Pieces of code that are used to identify and structure different parts of an HTML document. Because of HTML tags, a web browser knows how to display an HTML document. - -### HTTP - -Stands for Hyper Text Transfer Protocol. HTTP is a protocol that typically runs on port 80 and is used to send web resources such as images and HTML documents across the world wide web. Through the use of HTTP, data is sent from an HTTP server program ( a web server ) to an HTTP client program ( a web browser ). - -### HTTP Client - -A software tool that receives data from a web server through the HTTP protocol. Some HTTP clients include web browsers like Mozilla Firefox and Netscape. - -### HTTP Server - -A software tool used to store and send data over the world wide web to HTTP clients. Some HTTP servers include Apache and IIS. - -### HTTPS - -Stands for Hyper Text Transfer Protocol Secure. HTTPS is a secure version of HTTP and provides communication using SSL. With HTTPS, data that is sent between a web server and a web client is encrypted. - -### Hyperlink - -A link on a webpage to another web document, usually a webpage, but can also be an image, a sound, or any other web resource. Hyperlink is synonomous with Link and Hotlink. - -### Hypermedia - -An extension to hypertext which includes graphics, audio, and video. - -### Hypertext - -Text that is linked to other documents in a way that makes it pssobile for readers to read related documents by clicking on a highlighted word or symbol. - -### IAB - -Stands for Internet Architecture Board. The IAB is an organization whose task is to oversee internet standards. - -### IAP - -Stands for Internet Access Provider. An IAP is a company that provides internet access. Not to be confused with ISP (Internet Service Provider), which is a company that provides internet access, and can also provide services such as leased lines and hosting. - -### IETF - -Stands for Internet Engineering Task Force. THE IETF is a subgroup of IAB and it is a community of people focused on the smooth running of the internet. - -### IIS - -Stands for Internet Information Server. IIS is a web server created by Microsoft that runs on Windows NT platforms. - -### IMAP - -Stands for Internet Message Access Protocol. IMAP is a protocol used for receiving e-mail messages from a mail server. - -### Indeo - -A software codec for computer video. Indeo was developed by Intel. While Indeo is a software codec, it is based on DVI — a hardware codec. - -### Internet - -An abbreviation for internetwork. The internet is a global network connecting together many other networks and thus making communications between the various devices and computers on these networks possible. - -### Internet Explorer - -A web browser originally developed by SpyGlass inc. and later purchased by Microsoft. Internet Explorer is currently the most popular web browser. - -### Intranet - -A private network accessible only by those on the network. An Intranet runs inside a LAN. - -### IP Address - -Stands for Internet Protocol Address. An IP address is a unique identifier for every computer or device on a network. - -### IRC - -Stands for Internet Relay Chat. IRC is an online discussion medium similar to a forum, but the chat occurs in real time as oppsed to a forum. - -### IRC Client - -A software tool used to establish and maintain a connection to IRC. - -### IRC Server - -A server that serves connections to IRC. - -### ISAPI - -Stands for Internet Server Application Programming Interface. ISAPI is an API for Microsoft's IIS web server. - -### ISDN - -Stands for Integrated Services Digital Network. ISDN is a telecommunications standard used for sending digital data over digital phone lines as well as non-digital telephone wires. - -### ISP - -Stands for Internet Service Provider. An Internet Service Provider is a company that provides individuals and companies with internet access. ISP is synonomous with IAP. - -### Java - -A high level, object-oriented, platform independent programming language developed by Sun Microsystems. Java can be used to write applications as well as applets that run in web pages. - -### Java Applet - -A Java program that can run within a webpage and can be downloaded to the user's computer from a webserver. - -### JavaScript - -An object-oriented high level language used for web development. Javascript was originally created by Netscape. Javascript can be used to interact with the user as well as create dynamic content such as moving images and clocks. - -### JPEG - -Stands for Joint Photographics Experts Group. This organization is responsible for and promotes the JPG and JPEG image compression formats. - -### JPEG and JPG - -Image compression formats created by the Joint Photographics Experts Group ( JPEG ). The JPEG and JPG formats are popular on the internet. - -### JScript - -A version of Javascript developed by Microsoft. - -### JSP - -Stands for Java Server Pages. JSP is a server-side technology that allows for dynamic scripts to work with HTML code. - -### KB - -An abbreviation for kilobyte or kilobytes. Example: 1KB ( 1 kilobyte ), 5KB ( 5 kilobytes ). - -### Keyword - -In the world wide web, a keyword is a word used by search engines to search for relevant information. In databases, a keyword is an entry used to specify a particular record. In programming, a keyword is a special word that is reserved by a particular language for some usage. - -### Kilobyte - -A unit of data consisting of 1024 bytes. Kilobyte is abbreviated as KB. - -### LAN - -Stands for Local Area Network. A LAN is a network spanning a relatively small area, usually limited to one building or a group of buildings. LAN's are often used by organizations that need their own network such as offices and educational institutions. Two or more LAN's connected together make up a WAN. - -### Link - -In general programming, the execution of a linker. In spreadsheet software, when two or more files are linked by common cells. In telecommunications, a path for data transmission. In data management systems, a pointer to another record. In some operating systems such as unix, a pointer to a file which makes it possible to access the file without specifying the files full path. In the world wide web, the same as hyperlink. - -### Linux - -A free open source operating system based on Unix. Linux gets its name from the man responsible for developing most of the operating system's kernel — Linus Trovalds. - -### Mail - -See E-mail - -### Mail Server - -See E-mail server - -### MB - -An abbreviation for megabyte or megabytes. Example: 1MB ( 1 megabyte ), 10MB ( 10 megabytes ). - -### Megabyte - -A unit of data consisting of 1024 kilobytes. Megabyte is abbreviated as MB. - -### Meta - -The word meta when used in computer science is a prefix that means "about". - -### Meta Data - -Data used to describe other data. Meta data is essentialy data about data. - -### Meta Search - -A search used to find meta data in documents. - -### Meta Tags - -Special HTML tags used to describe a webpage in some way. Meta tags can be used to specify the author of a webpage, the software used to create the webpage, the content of the webpage, and more. - -### MIDI - -Stands for Musical Instrument Digital Interface. MIDI is a standard which creates an interface between computers and musical instruments through which they can communicate. - -### MIME - -Stands for Multipurpose Internet Mail Extensions. MIME is a standard first created in 1992 by the IETF and is used to send messages in different document types over the internet. There is currently a new version of MIME called S/MIME which supports sending encrypted messages over the internet. - -### MIME Types - -Document types that are defined by MIME. Some MIME types include text/plain, text/html, image/jpeg, and video/mpeg. - -### Modem - -An abbreviation for modulator-demodulator. A modem is a piece of computer hardware (could be internal or external) used to send data through telephone or cable lines. While data on a computer is stored digitally, data on telephone and cable lines is stored in an analog form. Other than sending data, it is the modem's job to convert between digital and analog data. This is how modem gets its name — it modulates a digital signal into an analog signal, and then demodulates an analog signal into a digital signal. - -### Mosaic - -A web browser released in 1993 by the NCSA. Mosaic became the first commonly available web browser. - -### MOV - -A file extension used for multimedia files played on Apple's QuickTime. A video codec developed by Apple. - -### MP3 - -Stands for MPEG-1 Audio Layer-3. MP3 is an audio compression technology that removes the superfluous information of a sound signal. This audio compression makes MP3 files easily transferable over the internet. MP3 is also a file extension for audio files compressed using the MP3 technology. - -### MP3 File - -An audio file compressed using the MP3 technology. - -### MPEG - -Stands for Moving Picture Expert Group. MPEG is a standard codec created by the ISO used for audio and video. MPEG (as well as MPG ) is a file extension used for audio and video files created with the MPEG codec. - -### MPEG File - -An audio or video file created with the MPEG codec. - -### MPG File - -An audio or video file created with the MPEG codec. - -### MS-DOS - -Stands for Microsoft-Disk Operating System. MS-DOS is an operating system originally developed by Microsoft for IBM personal computers. MS-DOS later became the basis for the first versions of Windows. - -### Multimedia - -The integration of text, graphics, video, animation, and/or sound in a presentable way. - -### MySQL - -A free open source database system commonly used for interaction with web applications. - -### NetBEUI - -Stands for NetBios Extended User Interface. NetBEUI is an extended version of NetBIOS which was originally designed by IBM for the IBM Lan Manager Server. NetBEUI was later extended by Microsoft and Novell. - -### NetBIOS - -Stands for Network Basic Input Output System. NetBIOS is an API that contains special functions for commmunication between computers on LAN's. NetBIOS is used by DOS and Windows. - -### Navigate - -Same as browse. - -### Netscape - -A web browser developed by Netscape Communications. For some time, Netscape was the most popular web browser. As of now, Internet Explorer is the most popular web browser. - -### Newsgroup - -Same as forum. - -### News Reader - -A software tool dedicated to enabling users to read messages from a newsgroup, and post messages to a newsgroup. - -### News Server - -A server that serves newsgroups to users. - -### Node - -Any computer or device on a network. - -### Opera - -A web browser developed by the company Opera. Opera is available for various operating systems including Windows, Linux, and Mac. - -### OS - -Stands for Operating System. An OS is the central program on a computer. An OS is responsible for running other programs, getting input from the user, sending output to the screen, keeping track of files and directories, and communicating with hardware. Some OS's include Windows, Linux, Unix, Mac, and Solaris. - -### Packet - -See TCP/IP Packet. - -### Page Hits - -When ever a user views a resource from a web server such as an image or a webpage. Since a page hit is the viewing of any web resource, usually there is more than one page hit at once. For example, if a user views a webpage with 4 images and 1 sound, that is 6 page hits. The webpage itself is one page hit, the images are four page hits, and the sound is one page hit. - -### Page Impressions - -The viewing of an advertisement on a webpage. For example, if you view a webpage with two ads, thats two page impressions. - -### Page Views - -When a webpage is viewed by a user. - -### PDF - -Stands for Portable Document Format. PDF is a document format developed by Adobe Systems which makes it possible to view formatted documents exactly as they were intended. This is achieved by the way PDF technology gets formatting information from various desktop publishing applications. - -### Perl - -Stands for Practical Extraction and Report Language. PERL was originally developed by Larry Wall. It is a language used for writing CGI scripts. - -### PHP - -Stands for Hypertext Preprocessor. PHP is an open source, server-side, high level, object-oriented web language used to develop dynamic web pages. PHP can be used to interact with the user, access databases, open FTP connections, and more. PHP was originally created in 1994 By Rasmus Lerdorf. - -### Ping - -A method used to determine if an IP address is accessible. Ping works by sending some packets to a specified IP address. If there is a reply, than the IP address is accesible, otherwise it is not. Sometimes however, an IP address may be accessible, but will not respond to pings for security reasons. - -### Platform - -The central hardware and/or software of a computer. For example, the software platform of the average PC is Windows, while its hardware platform is Intel X86. In web terms, platform refers only to the central software of a computer ( its operating system ), such as Windows, Linux, or Mac. The term platform is sometimes used synonomously with operating system. - -- Car tracking devices -- Machine -- Chatroom -- Auto parts international -- Database management system -- Download -- Security System -- 8 Bits -- Abbreviations -- Activex -- Car tracking devices -- Machine -- Chatroom -- Auto parts international -- Database management system -- Download -- Security System -- 8 Bits -- Abbreviations -- Activex - -### Plug-In - -A piece of hardware or software that adds functionality to existing software by being installed to it. For example, there are many plug-ins for the Mozilla Firefox web browser that add functionality to it such as the Acrobat Reader plug-in which makes it possible to read PDF documents within the browser, once the plug-in is installed. - -### PNG - -Stands for Portable Network Graphics. PNG is a graphics format that uses lossless data compression. PNG is set to replace the GIF graphics format, as it is completely patent and license free, while GIF is not. - -### POP - -Stands for Post Office Protocol. POP is a protocol used for receiving and reading e-mail from an e-mail server. The first version of the POP protocol named POP2 was a standard in the mid-80's and required SMTP to send messages. The second version of the POP protocol named POP3 does not require SMTP to send messages, and can be used with or without it. - -### Port - -In terms of hardware, a port is the physical interface on a computer to which devices or other computers can be connected. Computers have hardware ports to connect devices such as mice, keyboards, modems, and microphones. In terms of software, a port is an endpoint to a logical connection. Software ports range in number from 1 to 65535, with each port number identifying what kind of connection the port excepts. For example, port 21 excepts FTP connections, while port 25 excepts SMTP connections. - -### Protocol - -A set of rules dictating how programs, computers, and devices communicate with each other over the internet. For Example, the Hyper Text Transfer Protocol (HTTP) specifies how data is sent over the world wide web between the web server and the user's web browser. - -### PPP - -Stands for Point to Point Protocol. PPP is used to establish a direct connection between two computers. Often times, a connection between a user's computer and that of an ISP's server, so that the user can connect to the internet through the server. - -### Proxy Server - -A server that acts as a middle man in a connection between two computers. A proxy server can be used to improve performance by saving the results of various requests, and consequently loading such data faster when it is requested again. A proxy server can also be used to filter out content by checking what information is requested, and potentially blocking that information from reaching the user who requests it. - -### QuickTime - -A multimedia format developed by Apple. Mac's as well as PC's can run video and animation in a QuickTime format. For Mac's , the QuickTime technology is built into the operating system. For PC's, a special QuickTime driver is required. Various encoding formats are supported by QuickTime including Cinepak, JPEG, and MPEG. - -### Router - -A software tool or hardware device that transfers data to different devices across networks. Since a router transfters data across networks, it has to be connected to at least two networks. These two networks can be two LANs, two WANs, or a LAN and its ISP'S network. - -### RAID - -Stands for Redundant Array of Independent Disks. RAID is a standard by which multiple disks are connected to the same server . With RAID, better security, speed, and performance is achieved. RAID is often used for web servers, as many domains are often hosted on one server. - -### RDF - -Stands for Resource Description Framework. RDF is a framework for describing the information contained in various web resources. RDF describes information such as when updates were made and keywords used by search engines to find various web pages. - -### Real Audio - -An audio format developed by RealNetworks in 1995. The current version of Real Audio is RealAudio 10. - -### Real Video - -A video format developed by RealNetworks in 1997. The current version of Real Video is RealVideo 10. - -### Redirect - -In web terms, a redirect is when a web page automatically sends the user to another web page. In general computer usage, a redirect is the process by which output on the command line is sent to a particular place such as a text file. In e-mail, a redirect is similar to a forward, the difference being when you redirect an e-mail to someone it will show the original senders e-mail address as well as your e-mail address in parentheses. For example, if you receive an e-mail from someone@adomain.com, your e-mail address is someone@anotherdomain.com, and you redirect the e-mail to the e-mail address thirdperson@email.com, the sender field will read something like From: someone@adomain.com (sent by your name). - -### RGB - -Stands for Red Green Blue. RGB is an acronym for the three primary colors that when mixed in various ways produce the entire color spectrum. - -### Robot - -In computer terms, a robot is a program that runs by itself. Three types of robots are agents, spiders, and daemons. - -S - -### Schema - -See XML Schema. - -### Script - -A list of statements that are executed without user interaction. Scripts are written using scripting languages such as Javascript and VBScript. - -### Scripting Language - -A scripting language is a language used to write scripts that are usually executed in a web browser or a web server. Scripting languages are often used to add functionality to web pages such as interaction with the user, animations, and different menus. Code written in a scripting language is not compiled, rather interpreted. Some scripting languages include Javascript, VBScript, PHP, and Python. - -### Scripting - -The process of writing a script in a scripting language. - -### Shareware - -Software that is free of charge, however the author(s) of the software request a small fee for its usage so that the user can receive assistance with the software as well as updates to it. Shareware is meant to be shared among people (hence the name — shareware), but anyone who uses shareware is expected to pay the small fee for its usage. - -### Shockwave - -A technology created by Macromedia, Inc. for including multimedia in web pages. - -### Search Engine - -A program used to find information on the world wide web using specific keywords. Some search engines include Google, Yahoo , AltaVista, and Lycos. - -### Semantic Web - -An extended version of the current world wide web that allows for an easier way to find, share, reuse, and combine information. - -### Server - -A computer or device on a network responsible for distributing data to other computers or devices on a network that request data, also a computer or device on a network that manages resources. For example, a print server is responsible for managing printers, a network server is responsible for managing network traffic, a web server is responsible for distributing web resources, and an e-mail server is responsible for storing and retrieving e-mail. - -### SGML - -Stands for Standard Generalized Markup Language. SGML was developed by the ISO and became a standard in 1986. SGML is a markup language that specifies the organization of documents created with other markup languages. - -### SMIL - -Stands for Synchronized Multimedia Integration Language. SMIL is a markup language that is currently in development for the world wide web by the W3C. SMIL will make it possible to divide multimedia content into separate entities, send them to a web browser individually, and then display them together as one single multimedia object. This will make multimedia content smaller in size, and consequently it will travel faster over the internet. - -### SMTP - -Stands for Simple Mail Transfer Protocol. The SMTP protocol typically runs on port 25 and is used to transfter e-mail messages across the internet. - -### SOAP - -Stands for Simple Object Access Protocol. SOAP is a platform independent protocol used for letting applications communicate with each other through XML. SOAP can be transported using various protocols including SMTP, MIME, and HTTP. - -### Solaris - -An operating system developed by Sun Microsystems. Solaris is based on Unix and contains support for various features including multithreading, symmetric multiprocessing, integrated TCP/IP networking, and centralized network administration. - -### SPAM - -Unsolicited junk e-mail or newsgroup posting. Spam usually comes in the form of advertisements for some product or service. - -### Spider - -See Web Spider. - -### Spoofing - -Forging an online identity in some way. With e-mail spoofing, someone can forge their real e-mail address. With web spoofing, someone can pretend they came from one webpage when they really came from another one. With IP spoofing, someone can pretend an IP address is their own when it is really not. - -### Spyware - -Hidden software whose purpose is to gather data about a user's web surfing habits. Spyware can come built in to various software that is downloadable from the internet, from software that comes pre-installed with a computer, or can secretly install itself from the web. Spyware usually gathers data about a user's surfing habits for advertising purposes. - -### SQL - -Stands for Structured Query Language. SQL was originally called SEQUEL (Structured English Query Language) and was designed in 1974-75 by an IBM research center. In 1979, the Oracle corporation introduced SQL as a commercial database system. Today, SQL is the ANSI standard language used to get data from and manipulate databases. - -### SQL Server - -A database system which stores data and outputs it to computers who send queries to it in the form of SQL statements. The SQL server is a DBMS offered by Microsoft as well as Sybase. - -### SSI - -Stands for Server Side Include. An SSI is a special type of HTML comment that when inserted on a web page, instructs the web server to dynamically generate content for the web page. Some content that can be generated on a webpage through the use of Server Side Includes is the content of other files on web pages and a standard header or footer for a webpage. - -### SSL - -Stands for Secure Socket Layer. SSL is a protocol developed by Netscape which encrypts data transmitted over the web. SSL is used by websites that obtain confidential information about users such as a user's address or credit card number. - -### Static IP address - -An IP address that does not change. Some computers that have static IP addresses include web servers and e-mail servers. - -### Streaming - -Downloading audio and video in such a way that it is being viewed while it is being downloaded. - -### Streaming Format - -The standard format used for files that are being streamed over the internet. - -### SVG - -Stands for Scalable Vector Graphics. SVG is a file format for vector graphics which allows images to be displayed in XML pages. These images are created through the use of text based commands that are formatted to comply with XML specifications. SVG images are scalable to the size of the window in which a web page is viewed and will adjust in size and resolution based on the window in which they are displayed, unlike JPEG and GIF images which always remain a specific size. Other benefits of SVG include being a smaller file size than JPEG and GIF image files, being resolution independent — so an SVG image can scale up or down on any type of web device, accordingly, being able to link to parts of an image, and containing complex animation. - -### Tag - -A command placed in a web document that specifies the structure and formatting of the document. - -### TCP - -Stands for Transmission Control Protocol. TCP is one of the main protocols of the TCP/IP protocol suite along with IP. TCP enables two devices on a network to establish a connection and exchange data. - -### TCP/IP - -Stands for Transmission Control Protocol/Internet Protocol. TCP/IP is a suite of protocols that dictate the logistics of communication over the internet. TCP and IP are the two main protocols in this protocol suite, others being HTTP, SMTP, telnet, HTTPS, and more. The TCP protocol is responsible for ensuring a connection between two computers that is error free and that the two computers exchange data. The IP protocol is responsible for the actual data packets sent over the internet as well as the addressing scheme (where the packets go). - -### TCP/IP Address - -See IP Address. - -### TCP/IP Packet - -A data packet that is sent over a network running TCP/IP. - -### Trojan Horse - -A program that appears harmless, but its true purpose is malicious. Trojan horses are used for various purposes including allowing someone remote access to a victim's computer (remote access trojan), providing an attacker with sensitive information such as usernames and passwords (data sending trojan), destroying files (destructive trojan), and using the victims computer as a proxy server (proxy trojan), among others. - -### UDDI - -Stands for Universal Description Discovery and Integration. UDDI is a web based business interaction model that makes it possible for businesses to list themselves on the internet as well as discover other businesses on the internet. - -### Unix - -An operating system developed by Bell Laboratories in the early 1970's. Unix is written in C, and is used primarily for servers. - -### UNZIP - -The process of uncompressing a file that has been zipped. - -### Upload - -The process by which data is transferred from a local computer to a remote location. - -### URI - -Stands for Uniform Resource Identifier. A URI is used to identify resources on the internet with a name or address. Some examples of a URI would be an IP address or a web address(URL). - -### URL - -Stands for Uniform Resource Locator. A URL is an address containing three parts that points to resources on the internet. The first part of a URL specifies the protocol to use. The second part of a URL specifies the domain or IP address where the resource is located. The third part of a URL specifies the location of the file. For example, the URL http://www.landofcode.com/view/about.html points to a resource which is an HTML file, particulary the file about.html. The first part of the URL specifies to use the HTTP protocol to get this resource. The second part of the URL specifies that the domain where this resource is located is www.landofcode.com. The third part of the URL specifies that this resource is located in the /view directory. - -### USENET - -A global news system that contains more than 14,000 forums called newsgroups covering a vast amount of information. USENET can be accessed through the internet and is used by millions of people daily. - -### User-Agent - -A string of text that identifies the web browser and operating system used by a user. The user-agent string is sent by the web browser the user is using. - -Your user-agent string is Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36. - -### VB - -See Visual Basic. - -### VBScript - -Stands for Visual Basic Scripting Edition. VBScript is a scripting language developed by Microsoft that works only in Microsoft's Internet Explorer web browser and browsers based on Internet Explorer's engine such as Flashpeak's SlimBrowser. VBScript can be used to print dates, make calculations, interact with the user, and more. VBScript is based on Visual Basic , but it is much simpler. - -### Virus - -See Computer Virus. - -### Visit - -Time spent at a website. - -### Visitor - -Someone who comes to a website. - -### Visual Basic - -A language developed by Microsoft based on the BASIC language. Visual Basic is a high level object-oriented language that can create various Windows applications. The VBScript language ( also developed by Microsoft ) is based on Visual Basic. - -### VPN - -Stands for Virtual Private Network. A VPN is a private network that uses encryption and other means of security as a means of private communication over a public network. - -### VRML - -Stands for Virtual Reality Modeling Language. VRML is a standard used for displaying 3-dimensional graphics on the world wide web. - -### W3C - -Stands for World Wide Web Consortium. The W3C develops and maintains standards for the world wide web. - -### WAN - -Stands for Wide Area Network. A WAN is a network that connects various computers and devices in a network larger than a LAN (in terms of geographical area). A WAN can also be used to connect together two or more LAN's. The largest WAN in the world is the internet. - -### WAP - -Stands for Wireless Application Protocol. WAP is the protocol used by various wireless devices such as mobile phones, pagers , and smartphones to receive data through a secure connection. - -### Web Applet - -A program that can be run inside a webpage, and downloaded by the user and run on a local computer. Web applets are mostly written in Java. - -### Web Client - -A program that communicates with and receives data from a web server for the purpose of accessing resources on a website. A web client is usually a web browser. - -### Web Browser - -A web client used to display web pages and other web resources. Some web browsers include Mozilla Firefox, Netscape, Opera , and Internet Explorer. - -### Web Document - -A document viewed on the world wide web. Web documents are formatted in a markup language like HTML or XML and can also contain content produced with scripting languages like Javascript, PHP, and Perl. - -### Web Error - -See Web Server Error. - -### Web Form - -See HTML form. - -### Web Host - -A company that provides services like server space and file maintenance to various individuals and compaines. - -### Web Hosting - -The process by which server space is provided to store various web content so that it can be accessed by users on various networks. - -### Web Page - -A document that is part of a website that is distributed to users requesting it over the world wide web. - -### Web Robot - -See Web Spider. - -### Web Server - -A type of server used to store the content of web sites and distribute it to users who request it. - -### Web Server Error - -A message generated by a web server when some error occurs during the interaction between it and a user. The various web server errors each have a code. For example, when a user tries to access a file that does not exist on the web server, they will get a 404 File Not Found error. - -### Web Services - -Software systems running on web servers that support interaction between computers that can work together to accomplish certain tasks over a network. - -### Web Site - -A location on the world wide web containing a top level domain extension such as.com,.net..org,.info. Web sites contain a set of related web pages and other web resources that collectively make up the website. Websites are owned and managed by various individuals, companies, and organizations. - -### Web Spider - -A software tool used to search the world wide web for web pages and indexing them accordingly. Search engines use spiders to add new pages to their search results. - -### Web Wanderer - -See Web Spider. - -### Wildcard - -A special character that means any and all characters. The wildcard character is often used to select a large amount of files at once. For example, in Windows and DOS, the wildcard character is \*. Suppose you are using Windows and you want to see a list of all of the files in a directory that have a.txt extension, for this task you would use the wildcard character \* in the form \*.txt. This will return all the files in the directory that have a.txt extension. - -### Windows 2000, Windows NT, Windows 95/98, Windows XP - -Operating systems that are part of the Windows family of operating systems developed by Microsoft. Currently, the most popular version of Windows is Windows XP. - -### Windows Media - -A set of audio and video formats developed by Microsoft. - -### WINZIP - -A software tool used to compress and decompress files. WINZIP was developed by WinZip Computing which is now owned by the Corel Corporation. - -### WMA - -Stands for Windows Media Audio. WMA is an audio format developed by Microsoft for the internet which uses a.wma file extension. The WMA format can encode digital audio the way the MP3 format does, but performs the compression of files at a higher rate than MP3. - -### WMV - -Stands for Windows Media Video. WMV is a video format developed by Microsoft for the internet which uses a.wmv file extension. The WMV video format is part of the Windows Media Framework. - -### WML - -Stands for Wireless Markup Language. WML is a language used to specify the content and interface for wireless devices such as mobile phones. - -### WML Script - -Stands for Wireless Markup Language script. WML is a scripting language used for WML. - -### Worm - -A computer virus that works by making copies of itself and infecting other computers in the process. - -### WSDL - -Stands for Web Services Description Language. WSDL is an XML formatted language that is used to describe the capabilities of a web service as well communication endpoints that are capable of exchanging messages. - -### World Wide Web - -A subset of the internet that uses mostly the HTTP (as well as HTTPS) protocols to transfer web documents to users across the internet. - -### WWW Server - -See Web Server. - -### WYSIWYG - -Stands for What You see Is What You Get. WYSIWYG is an acronym used to refer to seeing a document exactly how it will be displayed when it is published or printed. - -### XForms - -The next generation of HTML/XHTML forms. XForms will separate data definition and data display, unlike current HTML forms. XForms will also be used to describe interface components other than forms. - -### XHTML - -Stands for Extensible Hyper Text Markup Language. XHTML is the next step in the evolution of HTML. It's syntax is stricter and more verbose. - -### XPath - -XPath is a language used for defining parts of an XML document as well as computing values based on content in an XML document. XPath is part of XSL along with XSL-FO and XSLT. - -### XQuery - -XQuery is a language used for extracting information from XML documents. - -### XML - -Stands for Extensible Markup Language. XML is a markup language developed by the W3C where the tags are defined by developers . As such, the definition, transmission, validation, and interpretation of data between applications and organizations is enabled. XML is a simplified version of SGML. - -### XML Document - -A document that is written in XML. XML documents have a.xml file extension. - -### XML DOM - -Stands for XML Document Object Model. XML DOM is a set of rules for how an XML page is represented in a tree structure. XML DOM was developed by the W3C. - -### XML Schema - -A document used to describe the content, rules, structure, and syntax of an XML document. XML schema was designed by the W3C , and it is intended to replace DTD. - -### XSD - -Stands for XML Schema Definition. Same as XML Schema. - -### XSL - -Stands for Extensible Stylesheet Language. XSL is a standard developed by the W3C used to specify styles for various elements on a webpage, and is the second such standard. The first being CSS. XSL has two advantages over CSS — it allows developers to specify how web pages are printed, and transfer XML documents across different applications. The first draft of XSL was released in August 1998. - -### XSL-FO - -Stands for XSL Formatting Objects. XSL-FO is an XML language used to format documents. XSL-FO is part of XSL along with XSLT and XPath. - -### XSLT - -Stands for XSL Transformations. XSLT is an XML language used to transform XSML documents into other XML documents. XSLT is part of XSL along with XSL-FO and XPath. - -### ZIP - -A popular file compression format. Files that are compressed with the ZIP format have a.zip extension and are called ZIP files. Such files are said to be ZIPPED, while files that are decompressed from the ZIP format are said to be UNZIPPED. ZIP files are often offered for download over the internet, as this makes downloading faster for the user as well as makes the bandwidth usage of a web server more economical. Once downloaded, the ZIP file can be UNZIPPED by the user. - ---- - -### CDN - -
            Content Delivery Network - -This is typically a paid service you can use to get great performance for your app. Many CDNs act as caching proxies to your origin server; some require you to upload your assets to them. They give you a URL for each resource in your app. This URL will resolve differently for folks depending on where they're browsing. - -Behind the scenes, the CDN will distribute your content geographically with the goal of end-users being able to fetch your content with the lowest latency possible. For example, if a user is in India, they'd likely get content served from India faster than from the United States. - -### CoffeeScript, TypeScript - -These are both languages that compile to JavaScript. You're able to write your code using the syntax they offer and when ready you compile your TypeScript or CoffeeScript into JavaScript. - -CoffeeScript vs TypeScript - -### Evergreen browsers - -Browsers that update themselves (without user intervention). - -Evergreen Browsers - -### ES3, ES5, ES5.1, ES6 (aka ES2015), etc - -ES stands for ECMAScript, which is the specification that JavaScript is based on. The number that follows is the version of the specification. - -Most browsers support at least ES5, and some even have ES6 (also known as ES2015) support. You can check each browser's support (including yours) here: - -- ES5 support -- ES6 support - -ECMAScript - -### LESS, Sass - -
            Both LESS and Sass are types of CSS preprocessor markup intended to give you much more control over your CSS. During the build process, the LESS or Sass resources compile down to vanilla CSS (which can be executed in a browser). - -Sass/Less Comparison - -### Linter, linting, jslint, jshint - -A validation tool which checks for common issues in your JavaScript. You'd usually use this in your build process to enforce quality in your codebase. A great example of something to check for: _making sure you've always got your semicolons_. - -An example of some of the options you can configure - -### Polyfill - -This is a concept that typically means providing JavaScript which tests for features that are missing (prototypes not defined, etc) and "fills" them by providing an implementation. - -### Promise - -Asynchronous calls typically return a promise (or deferred). This is an object which has a state: it can be given handlers for when it's fulfilled or rejected. - -Ember makes use of these in places like the model hook for a route. Until the promise resolves, Ember is able to put the route into a "loading" state. - -- An open standard for sound, interoperable JavaScript promises -- emberjs.com — A word on promises - -### SSR - -Server Side Rendering - -Inside FastBoot: The Road to Server-Side Rendering - -### Transpile - -When related to JavaScript, this can be part of your build process which "transpiles" (converts) your ES6 syntax JavaScript to JavaScript that is supported by current browsers. - -Besides ES6, you'll see a lot of content about compiling/transpiling CoffeeScript, a short-hand language which can "compile" to JavaScript. - -- Ember CLI specifically uses Babel via the ember-cli-babel plugin. - -### Shadow DOM - -Not to be confused with Virtual DOM. Shadow DOM is still a work in progress, but basically a proposed way to have an "isolated" DOM encapsulated within your app's DOM. - -Creating a re-usable "widget" or control might be a good use-case for this. Browsers implement some of their controls using their own version of a shadow DOM. - -- W3C Working Draft -- What the Heck is Shadow DOM? - -### Virtual DOM - -Not to be confused with Shadow DOM. The concept of a virtual DOM means abstracting your code (or in our case, Ember) away from using the browser's DOM in favor of a "virtual" DOM that can easily be accessed for read/writes or even serialized. - ---- - -**Adaptive Web Design (AWD)** — encourages the creation of several versions of a -web page for a specified number of device dimensions. Which template to display -is determined in the HTTP GET request which recognises the screen size of the -device. Adaptive Web Design was introduced to deal with mobile browsing when -most sites were optimised for desktop only. As devices now exist in many sizes -and dimensions from different mobile brands through tablets to desktops, -**Responsive Web Design** has become a popular and more flexible alternative. - -**Authentication** — the process of verifying that you are who you say you are -E.g. when you login to your email you use a password to authenticate your -identity. Other methods for authentication include using an ID card or -fingerprint/biometric method. - -**Authorization** — check that you are authorised (have permission) to perform a -certain action or to see a given page. E.g. admin users are authorised to create -new users on the website. - -**Declarations** — in JavaScript declarations are `var`, `const` and `let` for -the creation of variables, constants and lexically scoped variables. - -**Closure** — the scope where a variable can be accessed. A function used within another function can access the parent function's variables since its scope extends to its parent. - -In this example, the variable `color` is accessible to the function `displayColor()`. - - function color() { - var color = 'red'; - function displayColor() { - alert(color); - } - displayColor(); - } - -**CSS Box Model** — the concept that in HTML all elements are contained within -rectangles or boxes. Each box consists of: margins, borders, padding, and the -actual content. - -**Customer relationship management (CRM)** — a CRM system allows businesses to -manage business relationships and the data and information associated with them. -E.g. using CRM to track holiday bookings for a holiday bookings site. The CRM -would have information on the customer and the trip they're planning/ have -booked and any staff members or actions that may need taking to progress or -confirm their booking. - -**Create, Read, Update, and Delete (CRUD)** — CRUD refers to the 4 basic -operations you can perform on data in a relational database application. Create -a new data entry, read or retrieve existing data from the database, update the -value of an existing piece of data or delete an existing piece of data. - -**Cross-Origin Resource Sharing (CORS)** — is a specification that allows -specified resources on a web page to be requested from another domain outside -the domain from which the first resource was served. E.g. uploading images using -different domains using Amazon S3. For more about origin policies see -'Same-origin Policy'. - -Destructuring Assignment - -the ability to unpack and assign variables when there are multiple parameters. - -A way to simply assign the variables and then swap their values. - - let x, y; - [x, y] = [5, 6]; - // x = 5, y = 6 - [y, x] = [x, y]; - // x = 6, y = 5 - -To assign values from an object. - - let obj = { 'a': 1, 'b': {'b1': '1.1'}} - let {a, b, b:{b1}} = obj - // a = 1, b = {'b1': '1.1'}, b1 = 1.1 - -There is an extensive list found here for more examples. - -**Domain Name** — the characters/words used to identify a website after `http://` or -`www.`. The domain name consists of two parts. Take this example: -`https://dwyl.com`, `dwyl` makes up the **second level domain (SLD)** which is -then followed by `.com` which what is known as the **top level domain (TLD)** or -**parent domain**. Other examples of top level domains are: `.org`, `.co.uk` -`.io`. Domain names are the more memorable and user-friendly representation of a -website's **IP address**. Domain names are registered under the **Domain Name -System (DNS)**. - -**Domain Name System (DNS)** — a distributed global directory of website domain -names (and other internet resources). The directory stores already registered -domain names along with their corresponding IP addresses. - -Hexadecimal — Uses 16 different symbols. "0"-"9" to represent the values 0 to 9 and "A"-"F" ("a"-"f" is acceptable too) to represent the values 10 to 15. It's common to use -hexadecimals when working in CSS to assign colors to your elements. - -The hexadecimal for dwyl's logo color is \#4bc0a9 (teal). -To convert the hexadecimal into RGB values, do the following: - - R = 4b - G = c0 - B = a9 - - Convert the letters to their numerical value. - b = 11 - c = 12 - a = 10 - - Red: 4 * (16^1) + 11 * (16^0) = 75 - Green: 12 * (16^1) + 0 * (16^0) = 192 - Blue: 10 * (16^1) + 9 * (16^0) = 169 - -Hex: \#4bc0a9 is RGB: 75, 192, 169. - -**Hoisting** — Hoisting is JavaScript's default behaviour of moving `var` -declarations to the top of the current **scope** when your code is run. What -this means is that whatever line your write a `var` declaration on e.g. `var x;`, -when your code is run it will automatically be lifted and read as if it were -written on the top lines of your current **scope** (to the top of the current -script or the current function). - -This means that you can use `var`'s higher up in the code before the line you've -declared them on. So this example: - - x = "hello"; - console.log(x) // logs 'hello' - var x; // declaring `x` which is hoisted as if it were written at the top on compilation - -Is read by the computer like this: - - var x; // declaring `x` which has been hoisted to the top line on compilation - x = "hello"; - console.log(x) // logs 'hello' - -**Higher-order Function** — Functions that take other functions as parameters and/or return a function. Some examples of these types of functions are the `map` and `reduce` method used for arrays. They both accept a function to use on the elements in the given array. - - // perform an action twice - function twice (func, value) { - return func(func(value)); - } - - // func can be any simple (preferably pure) function: - function func (value) { - return value + 3; - } - - console.log(twice(func, 1)); // 7 - console.log(twice(func, 7)); // 13 - -Not to be confused with pure functions, this comment explains the difference between the variations. - -**Hypertext Transfer Protocol (HTTP)** — the set of rules for transferring files -(text, graphic images, sound, video, and other multimedia files) on the World -Wide Web. When you enter http:// in your address bar in front of the domain, it -tells the browser to connect over HTTP. - -**Initialisation** — defining a variable and providing it with an initial value: -e.g. `var x = 1;`. - -**Internet Protocol (IP) Address** — a unique series of numbers or hexadecimal -digits used to identify a website. - -**Microservices** — the practice of running multiple web/application servers -simultaneously. It is a widely accepted/used application architecture used in -most companies. Lambda Functions are an example of a micro Node.js Server. - -**Polymorphism** — the ability for an object to take on many forms or types e.g. -when a parent class is used to refer to a child class object. **Operator -overloading** is one form of polymorphism. It is not used in Javascript but is a -feature of C++, Scala, Ruby, Haskell and Rust. - -**Progressive Web App (PWA)** — PWAs are traditional websites that are enhanced -with modern web technologies, allowing them to provide a more app-like -experience. They offer functionality such as being saved as a tile on your -mobile home screen, working offline and push notifications. The "progressive" -part means they're "progressively enhanced" with newer features, which means -they'll also work in older browsers that don't support the new features. Unlike -native apps, they don't have to be updated/listed in the app store although it -is possible to list them in the app store when this is desired. - -Regression Testing - -the re-running of existing tests to ensure that new changes/fixes have not -broken any existing functionality. We should perform regression testing any time -we modify an application, automated testing is a convenient way to achieve this. - -**REPL (READ, EVAL, PRINT, LOOP)** — a REPL is an interactive toplevel or -language shell. A simple, interactive computer programming environment that -takes single user inputs (i.e. single expressions), evaluates them, and returns -the result to the user. They are a handy tool for experimenting with -functionality outside of the context of a project. - -**Responsive Web Design (RWD)** — is designing one version of a web page which -reorders and resizes content in response to the size of a browser **at any given -point**, not just predetermined device sizes. This means the design of the site -is optimised for all screen sizes. See Adaptive Design for another approach to -designing. - -**Same-origin Policy** — Under this security policy implemented by web browsers, -a document (i.e. like a web page) hosted on server A can only interact with -other documents that are also on server A. In short, the same-origin policy -enforces that documents that interact with each other have the same origin. - -**Search Engine Optimisation (SEO)** — is the process of improving the visibility -of a website or web page in unpaid/organic search engine results. There are many -aspects to SEO and search engines change how it's calculated over time. It may -include the use of key words on a page, how often you add/edit content on your -site, to the way other sites link to you on the web. - -**Semantic HTML** — semantic HTML is the use of HTML elements that accurately -describe what they contain/are being used for E.g. a `

            ` tag indicates that the -text within it is a paragraph whereas a `