├── .gitignore
├── DOMElements16
├── DOMElements16.js
└── index.html
├── DOMSelectors14
├── DOMSelectors14.js
└── index.html
├── LICENSE
├── README.md
├── _config.yml
├── arraysObjects7
├── arraysObjects.js
└── index.html
├── conditionals8
├── conditionals8.js
└── index.html
├── console2
├── console2.js
└── index.html
├── dataTypes4
├── dataTypes4.js
└── index.html
├── editableDiv20
├── editableDiv20.js
└── index.html
├── events17
├── events17.js
└── index.html
├── functions10
├── functions10.js
└── index.html
├── intro1
├── index.html
└── intro1.js
├── loops9
├── index.html
└── loops9.js
├── manipulatingDOM11
├── index.html
└── manipulationDOM11.js
├── moreEvents18
├── index.html
└── moreEvents18.js
├── storage19
├── index.html
└── storage19.js
├── strings6
├── index.html
└── strings6.js
├── traversing15
├── index.html
└── traversing15.js
├── typeConversionCoercion5
├── index.html
└── typeConversionCoercion5.js
├── understandingDOM12
├── index.html
└── understandingDOM12.js
├── variables3
├── index.html
└── variables3.js
└── webCrawler1-13
├── index.html
└── webCrawler1-13.js
/.gitignore:
--------------------------------------------------------------------------------
1 | .vscode
2 | *.vim
3 | *.css.map
4 |
--------------------------------------------------------------------------------
/DOMElements16/DOMElements16.js:
--------------------------------------------------------------------------------
1 | console.log("Creating, Removing and Replacing Elements using JavaScript");
2 |
3 | let element = document.createElement('li');
4 | // document.createElement('ElementTag');
5 | // createElement creates a specified element in the document or any other parent
6 | // the ElementTag is the tag of the element you want to create, example: ul, li, table
7 | element.className = 'mainItems';
8 | // element.className = 'class';
9 | // it overwrites the classes of element and adds the specified class to the element
10 | // it can only add a single class to the element
11 | element.className = 'important';
12 |
13 | console.log(element.classList);
14 | // element.classList
15 | // returns the classes on a specific element
16 |
17 | element.classList.add('mainItems', 'created');
18 | // element.classList.add('class1','class2');
19 | // it adds the specified classes to the element without overwriting the existing classes of the element
20 |
21 | element.id = 'explosive';
22 | // element.id = 'id';
23 | // this sets the id of a specific element
24 |
25 | element.innerHTML = "Atom Bomb";
26 | // alters the HTML of a specified element
27 |
28 | element.setAttribute('title', 'created by javascript');
29 | // element.setAttribute('attribute', 'value')
30 | // this is used to set the specific attribute of a specific element to a specific value
31 | // the first arguement in this funciton is the attribute and the second arguement in the funciton is the value of the attribute
32 |
33 | let ul = document.querySelector('ul#list');
34 | // selects a particular element from the DOM
35 | ul.append('added by javascript');
36 | // element.append(thingToBeAppended)
37 | // this appends something to the element's end
38 | // it can append elements as well as strings
39 |
40 | ul.appendChild(element);
41 | // ul.appendChild('dd');
42 | // element.appendChild(element)
43 | // it is used to append a child element to a specific element
44 | // using this, you cannot append strings to the DOM, you can only append elements
45 | // trying to append strings using appendChild method will result in an error
46 | // in other words, using this method you can only append nodes and text is not a node
47 | // if you want to append text using this method you will have to create a text node using createTextNode method
48 |
49 | let text = document.createTextNode('(Also get some missiles, hehe)');
50 | element.appendChild(text);
51 | // as text is a TEXT NODE, it is appended to the element using appendChild method
52 | // if the text was not a node, it would not be appended by the appendChild method and we would have to use append() to append it
53 |
54 | // console.log(element);
55 |
56 |
57 | let heading = document.createElement('h2');
58 | heading.id = 'smallHeading';
59 | // giving an id
60 | heading.clasName = 'heading';
61 | // giving a class name
62 |
63 | let headingValue = document.createTextNode('This is a created text node');
64 | // creating a text node
65 | heading.appendChild(headingValue);
66 | // appending the text node to the heading
67 |
68 | // PREPENDING
69 | document.body.prepend(heading);
70 | // element.prepend(elementToBePrepended)
71 | // this method prepends a specific element inside a particular element
72 | // prepending is adding something to the start of something
73 |
74 | let weapon = document.createElement('li');
75 | // creating an element
76 | let weaponText = document.createTextNode(('Pickaxe').bold());
77 | // creating a text node
78 | weapon.appendChild(weaponText);
79 | // appending the text node to the element
80 | // if you enclose the text with html tags, the tags would hold no importance as while appending the textnode is appended as plain text and not HTML
81 | weapon.id = 'weapon';
82 | // setting an id
83 | weapon.className = 'weapons';
84 | // settng a class name
85 |
86 |
87 | // REPLACING DOM ELEMENTS
88 | element.replaceWith(weapon);
89 | // element.replacedWith(element2)
90 | // using this method, you can replace element with element2
91 |
92 | ul.firstElementChild.classList.add('first');
93 | ul.lastElementChild.classList.add('last');
94 |
95 | ul.replaceChild(weapon, ul.firstElementChild);
96 | // element.replaceChild(element1, element2)
97 | // using this method you can replace element2 with element1 but you have to be sure that element2 is a child of the element whose child we are replacing, otherwise it will give us an error
98 |
99 | // ul.remove()
100 | // element.remove()
101 | // it removes the element
102 |
103 | ul.removeChild(ul.firstElementChild);
104 | // node.removeChild(nodeChild)
105 | // this method removes the nodeChild from the node
106 | // nodeChild has to be a child of node otherwise it will return an error
107 |
108 | weapon.setAttribute('title', 'weapon fighters');
109 |
110 | console.log(weapon.getAttribute('title'));
111 | // element.getAttribute('attribute')
112 | // this method returns the specific attribute of a specific element
113 |
114 | console.log(weapon.hasAttribute('color'));
115 | // element.hasAttribute('attribute')
116 | // this method returns true or false
117 | // it returns true if a specfic element contains a specfic attribute
118 | // it returns false if a specific element does not contain a specific attribute
119 |
120 | {
121 | let heading = document.createElement('h2');
122 | let anchor = document.createElement('a');
123 | anchor.append("Go to Google");
124 | anchor.setAttribute('href', 'https://www.google.com')
125 | heading.appendChild(anchor);
126 | ul.appendChild(heading);
127 | }
--------------------------------------------------------------------------------
/DOMElements16/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Creating, Removing and Replacing Elements using JavaScript
8 |
9 |
10 |
11 |
12 |
13 |
14 | gg
15 |
Creating, Removing and Replacing Elements using JavaScript
16 |
17 |
Things to buy are as follows:
18 |
19 |
Pencils
20 |
21 |
Go to shopkeeper
22 |
Buy two pencils
23 |
24 |
Notebooks
25 |
Fruits
26 |
Vegetables
27 |
28 |
Carrots
29 |
Tomatoes
30 |
31 |
32 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/DOMSelectors14/DOMSelectors14.js:
--------------------------------------------------------------------------------
1 | console.log("DOM Selectors in JavaScript");
2 |
3 | /*
4 | there are two types of DOM element selectors:
5 | 1. Single element selector - selects a single element
6 | 2. Multi Element Selector - selects multiple elements
7 | */
8 |
9 | let child1 = document.getElementById('child1');
10 | // it is a single element selector as it returns a single element
11 |
12 | // document.getElementById(idName);
13 | // getElementById is used to select an element by its id name
14 |
15 | // child1 = child1.className;
16 | // element.className returns the classes on the element
17 |
18 | // child1= child1.childNodes;
19 | // element.childNodes returns the child nodes of an element
20 | // child nodes are the children of the element
21 | // it returns a nodelist
22 |
23 | // child1 = child1.parentNode;
24 | // element.parentNode returns the parent of the element
25 |
26 | // you can even change the css using javascript
27 | child1.style.color = "blue";
28 | // element.style.property = "value";
29 | // it changes the value of a property of a particular element
30 |
31 | child1.innerText = "Hargun is a very good boy :)";
32 | // element.innerText = "text";
33 | // it changes the text inside an element
34 |
35 | child1.innerHTML = "
these notes are POG
";
36 | // element.innerHTML = "html";
37 | // this changes the HTML of the element, it is different from innerText as using innerHTML you can add HTML content but using innerText you can only add text content
38 | // also innerHTML returns the HTML inside an element whereas innerText returns the text inside an element
39 | console.log(child1);
40 |
41 | let sel = document.querySelector('.child');
42 | // parent.querySelector('selector')
43 | // the above uses selectors to select an element inside another element, the format of the selectors is the same as css
44 | // prefix an id name with #
45 | // prefix a class name with .
46 | // any selector not prefixed will be considered a tag
47 | // if multiple elements match the selector, it only returns the first matching element as it is a single element selector
48 | sel.style.color = "green";
49 | console.log(sel);
50 |
51 |
52 | // MULTI ELEMENT SELECTOR
53 | // these types of selectors are used to select mutliple elements from the DOM
54 | let children = document.getElementsByClassName('child');
55 | // document.getElementsByClassName('className')
56 | // it returns all the elements with the particular class name
57 | // it returns an HTML collection which is an array
58 | console.log(children[1]);
59 | // it returns the second element in the array
60 |
61 | let elems = document.getElementsByTagName('div');
62 | // document.getElementsByTagName('tagName')
63 | // it returns an array of all the elements with the tagName
64 | Array.from(elems).forEach(element=>{
65 | element.style.border = "2px solid black";
66 | });
67 | // if you do not want to use Array.from you can use the traditional for loop
68 |
69 | let foo = document.querySelectorAll('.red');
70 | // document.querySelectorAll('selector')
71 | // selector follows the css selector syntax
72 | // it returns an array which have the specified selector
73 | Array.from(foo).forEach(element =>{
74 | element.style.background="#ff9999";
75 | });
--------------------------------------------------------------------------------
/DOMSelectors14/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | DOM Selectors in JavaScript
8 |
9 |
10 |
11 |
30 |
31 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | Copyright 2021 Hargunbeer Singh
179 |
180 | Licensed under the Apache License, Version 2.0 (the "License");
181 | you may not use this file except in compliance with the License.
182 | You may obtain a copy of the License at
183 |
184 | http://www.apache.org/licenses/LICENSE-2.0
185 |
186 | Unless required by applicable law or agreed to in writing, software
187 | distributed under the License is distributed on an "AS IS" BASIS,
188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189 | See the License for the specific language governing permissions and
190 | limitations under the License.
191 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
20 |
21 |
22 | # Introduction
23 | This repository contains descriptive notes of almost every ES6 JavaScript topic(including depcrecated topics) in the form of comments in JavaScript files. This repository will also contain links to JavaScript Projects which you can make while follwing the curriculum
24 |
25 | ## Table of Contents
26 | - [Introduction](#introduction)
27 | - [Table of Contents](#table-of-contents)
28 | - [Points to be noted](#points-to-be-noted)
29 | - [Folder Structure](#folder-structure)
30 | - [Curriculum](#curriculum)
31 |
32 | ## Points to be noted
33 | - Links will be provided in the notes for extra information
34 | - It will be specified in the notes whether a function/method is deprecated or non-functional
35 | - There will be exercises
36 | - There will be Projects
37 | - The notes aren't complete yet and will be posted consistently
38 |
39 | ## Folder Structure
40 | Each JavaScript folder/file is named with the following naming convention:
41 | `topicName`+`topicSerialNumber`
42 | For example, the name of the topic is `functions` and the serial number of the topic is `7`, so the folder name would be `functions7`
43 | Many a time, inside a folder you would find a HTML Markup file and a javascript file for the same
44 |
45 | ## Curriculum
46 | There will be about 55 to 60 tutorial notes. The topics are as follows:
47 | 1. [Introduction to Javascript](https://github.com/hamiecod/JavaScript-Notes/tree/main/intro1/intro1.js)
48 | 2. [Console Object](https://github.com/hamiecod/JavaScript-Notes/tree/main/console2/console2.js)
49 | 3. [Variables](https://github.com/hamiecod/JavaScript-Notes/tree/main/variables3/variables3.js)
50 | 4. [Data Types](https://github.com/hamiecod/JavaScript-Notes/tree/main/dataTypes4/dataTypes4.js)
51 | 5. [Type Conversion and Coercion](https://github.com/hamiecod/JavaScript-Notes/tree/main/typeConversionCoercion5/typeConversionCoercion5.js)
52 | 6. [Strings](https://github.com/hamiecod/JavaScript-Notes/tree/main/strings6/strings6.js)
53 | 7. [Arrays and Objects](https://github.com/hamiecod/JavaScript-Notes/tree/main/arraysObjects7/arraysObjects7.js)
54 | 8. [Conditionals](https://github.com/hamiecod/JavaScript-Notes/tree/main/conditionals8/conditionals8.js)
55 | 9. [Loops](https://github.com/hamiecod/JavaScript-Notes/tree/main/loops9/loops9.js)
56 | 10. [Functions](https://github.com/hameicod/JavaScript-Notes/tree/main/functions10/functions10.js)
57 | 11. [DOM window object manipulation](https://github.com/hamiecod/JavaScript-Notes/tree/main/manipulatingDOM11/manipulatingDOM11.js)
58 | 12. [Understanding DOM](https://github.com/hamiecod/JavaScript-Notes/tree/main/understandingDOM12/understandingDOM12.js)
59 | 13. [WebPage Crawler-1](https://github.com/hameicod/JavaScript-Notes/tree/main/webCrawler1-13/webCrawler1-13.js)
60 | 14. [HTML Selectors](https://github.com/hamiecod/JavaScript-Notes/tree/main/DOMSelectors14/DOMSelectors14.js)
61 | 15. [Children, Parent and Traversing the DOM](https://github.com/hamiecod/JavaScript-Notes/main/tree/traversing15/traversing15.js)
62 | 16. [Creating, Removing and Replacing Elements](https://github.com/hamiecod/JavaScript-Notes/main/tree/DOMElements16/DOMElements16.js)
63 | 17. [Events and Event Object](https://github.com/hamiecod/JavaScript-Notes/main/tree/events17/events17.js)
64 | 18. [More on Events](https://github.com/hamiecod/JavaScript-Notes/main/tree/moreEvents18/moreEvents18.js)
65 | 19. [Local and Session Storage](https://github.com/hamiecod/JavaScript-Notes/main/tree/storage19/storage19.js)
66 | 20. [Creating editable div](https://github.com/hamiecod/JavaScript-Notes/main/tree/editableDiv20/editableDiv20.js)
67 | 21. [Project1- Notes Taking App](#)
68 | 22. Math Object
69 | 23. Date Object
70 | 24. Creating an editable div-2
71 | 25. Improving notes website
72 | 26. Object Literals and Constructors
73 | 27. Object Prototype
74 | 28. Notes App
75 | 29. Prototype Inheritance
76 | 30. ES6 Classes and Inheritance
77 | 31. Implimenting a library class
78 | 32. [Project2- College Library Website](#)
79 | 33. What is Asynchrounous Programming?
80 | 34. AJAX
81 | 35. Library Class Implementation
82 | 36. Callback functions
83 | 37. Using a dictionary API
84 | 38. Promises
85 | 39. [Project3- Creating a News Website]
86 | 40. Arrow Functions
87 | 41. Fetch API
88 | 42. Async/Await
89 | 43. Error Handling and Try Catch
90 | 44. Using JavaScript Objects
91 | 45. JavaScript Regular Expressions and related functions
92 | 46. Regular Expressions- Metacharacters in JavaScript
93 | 47. Regular Expressions - Character Sets
94 | 48. Regular Expressions - Shorthand character classes
95 | 49. [Project4- Form Validation using regular expressions](#)
96 | 50. Iterators
97 | 51. Creating an Alarm App
98 | 52. Generators
99 | 53. Alarm Clock
100 | 54. [Project5- Creating a CV Screener](#)
101 | 55. For of vs For in loop
102 | 56. Maps
103 | 57. Sets
104 | 58. Symbols
105 | 59. Destructuring
106 | 60. Javascript Wall Clock
107 | 61. Creating a Clock
108 | 62. [Project6- Postman Clone](#)
109 | 63. Drag and Drop elements with JavaScript
110 | 64. [Project7- Creating a Calculator](#)
--------------------------------------------------------------------------------
/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-hacker
--------------------------------------------------------------------------------
/arraysObjects7/arraysObjects.js:
--------------------------------------------------------------------------------
1 | console.log("Tutorial 7 - Arrays and Objects");
2 |
3 | let marks = [23, 56, 43, 62, 95, 89];
4 | // this is an array
5 | const fruits = ["Orange", "Apple", "Pineapple"];
6 | const mixed = ["str", 89, [3, 5]];
7 |
8 | /*
9 | you can create arrays in two ways:
10 | 1. including the values within []
11 | example: [1,2,3,4]
12 |
13 | 2. using new Array()
14 | example: newArray(1,2,3,41)
15 | */
16 |
17 | const arr = new Array(23, 123, 21, "Orange");
18 | // console.log(arr);
19 | console.log(marks);
20 | // console.log(mixed);
21 | // console.log(fruits);
22 | // indexing in arrays starts from 0
23 | // so we start counting in array from 0, loosely saying
24 |
25 | // console.log(fruits[1]);
26 | // array[index]
27 | // this will return the index value of a specific array
28 | // so index 1 one will return the second element of the array
29 |
30 | // there are two things in array: property and method
31 | // when a method is suffixed with () then it is a method, if not then it is a property
32 |
33 | // it is a property
34 | console.log(arr.length);
35 | // array.length
36 | // returns the number of elements in an array
37 |
38 | console.log(Array.isArray([1, 2]));
39 | // Array is a class
40 | // isArray() is a method
41 | // Array.isArray(array)
42 | // returns whether a particular array is an array or not
43 |
44 | // you can also change the elements of an array
45 | arr[0] = "Hargun";
46 | // changes the 0 index element(first element) to Hargun
47 | let name = arr[0];
48 | console.log("element:", name);
49 | console.log(arr);
50 |
51 | // we will primarily work with marks array
52 |
53 | let value = marks.indexOf(56, 2);
54 | // array.indexOf(element, index to start searching from);
55 | // returns the index of the first occurence of the element
56 | // if it is not found it returns -1
57 | console.log(value);
58 |
59 | // Mutating or Modifying arrays
60 | marks.push(12);
61 | // array.push(value)
62 | // this method adds a specific value to the end of a particular array
63 | console.log(marks);
64 |
65 | marks.unshift(31);
66 | // array.unshift(value);
67 | // this method adds a specific value to the beginning of a particular array
68 | console.log(marks);
69 |
70 | console.log(marks.pop());
71 | // array.pop()
72 | // this method removes the last array item and returns it
73 | console.log(marks);
74 |
75 | console.log(marks.shift());
76 | // array.shift();
77 | // this method removes the first array item and returns it
78 | console.log(marks);
79 |
80 | console.log(marks.splice(1, 2, 55));
81 | // marks.splice(startIndex, noOfElements, ...elementsToBeAdded)
82 | // this method deletes the noOfElements starting from startIndex, and adds ...elementsToAdded in the place of the elements deleted
83 | // it returns the deleted elements
84 | console.log(marks);
85 |
86 | marks.reverse();
87 | // array.reverse();
88 | // this method reverses the array
89 | // all the methods change the actual array
90 | console.log(marks);
91 |
92 | let marks2 = [1, 2, 3, 4, 5];
93 | marks = marks.concat(marks2);
94 | // array.concat(array2)
95 | // this method concatinates array and array2
96 | // the array2 elements are added to the end of the array
97 | // this method does not change the actual array
98 | console.log(marks);
99 |
100 | marks.constructor;
101 | // array.constructor
102 | // this method returns the constructor function for the array object
103 | // it does not change the actual array
104 |
105 | marks.copyWithin(5, 0, 5);
106 | // array.copyWithin(target, start, end)
107 | // this method copies certain elements inside an array to certain element inside the same array itself
108 | // target is the index position to start pasting the elements from
109 | // start is the index position to start copying the elements from
110 | // end is the index position to stop copying the elements from
111 | // the end index position is not copied
112 | // if you want to copy the elements from 0 to 5
113 | // it will copy the 0, 1, 2, 3, 4 elements
114 | // it changes the actual array
115 | console.log(marks);
116 |
117 | const marksValue = marks.entries();
118 | // array.enteries()
119 | // this method returns an array iterator which can be iterated to get the key and value of each element in an array
120 | console.log(marksValue);
121 | // we need to iterate the Array Iterator in a loop to get the key value pairs
122 | // the first variable in the for of loop contains the key and the value
123 | console.groupCollapsed("MarksValue");
124 | // running a for of loop to iterate the array iterator and get the key value pairs
125 | // in arrays, the index is the key
126 | for (let value of marksValue) {
127 | console.log(value);
128 | }
129 | console.groupEnd("MarksValue");
130 |
131 | console.log(marks.every(checkPass));
132 | // array.every(function)
133 | // this methods checks whether each and every element of the array follows certain criteria
134 | // if the function returns all trues, then it will return true, and if the function returns atleast one false, it will return false
135 | // the function is to contain the condition, like marks>40
136 | // you need to supply the array as the parameter of the function
137 | function checkPass(marks) {
138 | return marks >= 20;
139 | }
140 |
141 | fruits.fill("Kiwi");
142 | // array.fill(value)
143 | // this method fills each element of an array with the same value that is given in the parameter
144 | // this method changes the actual array
145 | console.log(fruits);
146 |
147 | console.log(marks.filter(checkMerit));
148 | // array.filter(function)
149 | // this method returns the elements which follow certain criteria in the array
150 | // the function contains the condition, and if the condition returns true for a particular element, array.filter will return it
151 | // you need to supply the array as the parameter of the function
152 | function checkMerit(marks) {
153 | return marks >= 90;
154 | }
155 |
156 | console.log(
157 | marks.find((marks) => {
158 | return marks >= 90;
159 | })
160 | );
161 | // array.find(function)
162 | // this method returns the first value that passes certain criteria
163 | // the function contains the condition, and if the condition returns true for a certain element, array.find returns the particular element
164 | // it only returns the first value matching the criteria
165 |
166 | console.log(
167 | marks.findIndex((marks) => {
168 | return marks >= 90;
169 | })
170 | );
171 | // array.findIndex(function)
172 | // this method returns the index of the first value that passes certain criteria
173 | // the function contains the condtion, if it returns true, array.findIndex will return the index of the first element that the function returns true for
174 | // it only returns the index of the first element matching the criteria
175 |
176 | console.groupCollapsed("GoodMarks");
177 | marks.forEach((studentMarks) => {
178 | if (studentMarks > 80) {
179 | console.log("✨", studentMarks);
180 | }
181 | });
182 | console.groupEnd("GoodMarks");
183 | // array.forEach(valueVariable =>{}) is a loop
184 | // forEach runs the function for each element of the array
185 | // the first parameter of the function inside forEach stores the value of the current element of the array
186 |
187 | console.log(Array.from("abcdef"));
188 | // Array,from(string)
189 | // this method generates an array from a string
190 | // it transforms each character of the string into an array element
191 | // it is a method of the Array class
192 |
193 | console.log(marks.includes(95));
194 | // array.includes(value, startIndex)
195 | // checks whether an array includes a specific value
196 | // returns either true or false
197 | // startIndex is the index from where to start searching
198 |
199 | console.log(marks.join(" "));
200 | // array.join(separator)
201 | // this method transforms the elements of an array into a string
202 | // it separates each element of the array in the string by the sepearator
203 | // if the separator is omitted, then comma is used to seperate the elements in the string
204 |
205 | console.log(marks.keys());
206 | console.groupCollapsed("marksKeys");
207 | marksKeys = marks.keys();
208 | // array.keys();
209 | // this method returns an array iterator
210 | // we need to iterate the array iterator to perform operations on the keys
211 | for (let x of marksKeys) {
212 | console.log("🏹", x);
213 | }
214 | // the for of loop's first variable will contain the key and the second will contain the array iterator object
215 | console.groupEnd("marksKeys");
216 |
217 | console.log([NaN].indexOf(NaN));
218 | console.log([NaN].includes(NaN));
219 | // difference between indexOf and includes
220 | // indexOf gives the index of the first matching value
221 | // includes returns either true or false, based on whether a value is there in the array or not
222 | // as indexOf uses string checking(===), it returns -1, when you search for NaN in an array which contains NaN
223 | // include uses samevaluezero comparison algorithm instead of strict checking(===)
224 | // samevaluezero algo is mostly same as ===, but when you compare NaN and NaN, they return true
225 | // includes solves this problem as it returns true when you check if NaN is present in an array which has NaN
226 | // more: https://stackoverflow.com/questions/35370222/array-prototype-includes-vs-array-prototype-indexof
227 |
228 | console.log(marks.lastIndexOf(95));
229 | // array.lastIndexOf(value)
230 | // this method returns the index of the last occurence of a value in an array
231 | // it returns -1 if the value is not found
232 |
233 | console.log(marks.map(multiply));
234 | // array.map(function(currentValue, index, arr))
235 | // this method calls the function for each value of the array
236 | // the function can have three parameters: currentValue, index(the array index of the current element), array(the array the current element belongs to)
237 | function multiply(num) {
238 | return num * 10;
239 | }
240 |
241 | Array.prototype.myUcase = function () {
242 | for (let i = 0; i < this.length; i++) {
243 | this[i] = this[i].toUpperCase();
244 | }
245 | };
246 | // Array.prototype.name=function(){}
247 | // prototype is a global constructor
248 | // it is a method of Array class
249 | // you can create your own methods using prototype
250 | // you need to give a function to ur prototype
251 |
252 | console.log(
253 | marks.reduce((accumulator, currentValue) => accumulator + currentValue)
254 | );
255 | // marks.reduce(function)
256 | // this method executes a reducer fucntion on each element of the area, and returns a single output value
257 | // the function takes four arguements: accumulator, currentValue, currentIndex and sourceArray
258 | // the reducer function's returned value is assigned to the accumulator, whose value is remembered across each iteration, and the accumaltor value then ultimately becomes the final, resulting value
259 | // you can add a callback function, which will run if there is no accumulator value supplied
260 | // you need to supply initialValue as an arguement to the callback function, the callback function's initialValue parameter will be used as the accumulator
261 | // if no initial value is supplied, it takes the first value of the array as default
262 |
263 | // current value is the value currently being processed in the array
264 | // index is the index of the currently being proccessed value
265 | // array is the array reduce() was called upon
266 |
267 | console.log(
268 | marks.reduceRight((accumulator, currentValue) => accumulator + currentValue)
269 | );
270 | // array.reduceRight(function)
271 | // reduceRight does the same thing as reduce() but it starts reducing from the end
272 |
273 | console.log(marks.some((marks)=>{
274 | return marks>90;
275 | }));
276 | // array.some(function(array))
277 | // this method returns if some elements follow some specific criteria
278 | // returns true or false
279 | // the function contains the condition which either returns true or false for each specific element
280 | // if even a single element obeys the critieria array.some returns true
281 |
282 | marks.push(104);
283 |
284 | console.log(marks.sort());
285 | // array.sort
286 | // this method can sort an array in alphabetical order or in numerical order
287 | // it can sort an array in ascending as well as descending order
288 | // it returns the sorted array
289 |
290 | console.log(marks.sort(function(a,b){ return a-b; }));
291 | // generally, array.sort() wont sort numbers correctly, as suppose it will think 100 to be smaller that 90, because 1 comes before 9, as it compares from digit to digit
292 | // so to make this not happen, we will have to supply a function as the parameter
293 | // it will be used as a compare function by the compiler
294 | // in the above function, it compares two numbers, so if it is comparing 100 and 40, the function will return -60, telling the interpreter that 40 should be placed before 100
295 | // we can do array.sort in descending order by return b-a
296 |
297 | console.log(marks.valueOf());
298 | // returns the same value as marks
299 |
300 |
301 | // --------------------------
302 | // OBJECTS
303 |
304 | let info = {
305 | name: "hargun",
306 | channel: "Simplest Tech",
307 | 'is Active': true,
308 | marks: [1,2,3]
309 | }
310 | // an object contains a key and a value, a specific value corresponds to a specific key
311 | // an object can also have arrays
312 | // you have to contain the key inside quotes, if it has a space between
313 |
314 | console.log(info);
315 | // prints the whole object
316 |
317 | console.log(info.name);
318 | // object.key
319 | // prints the specific key value from the specific object
320 |
321 | console.log(info['is Active']);
322 | // object[key]
323 | // returns the specific value from the specific object
324 | // it is the same as object.key but if you want to access a key which has a space in its name, you will have to use this format, and contain the key name in quotes
325 |
326 | // Where to use arrays and objects
327 | // when you just want to store some values, use arrays
328 | // when you want to store some data in key-value pairs, use objects
329 |
330 | array.forEach(element => {
331 |
332 | });
--------------------------------------------------------------------------------
/arraysObjects7/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Arrays and Objects in JavaScript
8 |
9 |
10 |
11 |
Arrays and Objects in JavaScript
12 |
13 |
--------------------------------------------------------------------------------
/conditionals8/conditionals8.js:
--------------------------------------------------------------------------------
1 | // CONDITIONALS IN JAVASCRIPT
2 | console.log("This is tutorial 8 about conditionals");
3 | let age = 14;
4 |
5 | // conditionals are of two types in javascript- if..else statements and switch case
6 | // an if else statement is a block of code which performs certain tasks when certain conditions are true
7 |
8 | if (age == 14) {
9 | // in this case, it will only run this code if the age is 14
10 | console.log("Age is 14");
11 | } else if (age < 65) {
12 | console.log("Age is less than 65");
13 | } else {
14 | // it will run this code if the above if conditions are not true
15 | console.log("Age is not 14");
16 | }
17 | /*
18 | syntax:
19 | if(condition){
20 | ...code;
21 | } else if(condition){
22 | ...code;
23 | } else{
24 | ...code;
25 | }
26 |
27 | the code inside an "if" block is executed when the condition in the respective block is true
28 |
29 | the code inside and "else if" block is executed when the condition in the respective block is true
30 |
31 | the code inside "else" block is executed when none of the if or else if conditions are true
32 |
33 | when a condtion is found to be true and the code inside the respective block is executed, the if-else statement breaks
34 |
35 | when a condition is found to be true and the code inside the respective block is executed, the if-else statement will not execute the other else if and else blocks and will stop the execution of the statement then and there
36 |
37 | in the above if statement as well when the first block is executed the statement would break and the second block won't be executed
38 |
39 | if we use "if" instead of "else if" then it wont break the statement if a condtion is true, it will check both the conditions
40 | */
41 |
42 | const marks = "90";
43 |
44 | if (marks > 90) {
45 | console.log("you are a topper");
46 | } else if (marks == 90) {
47 | console.log("you got a 90");
48 | }
49 | /*
50 | == logical operator compares the value
51 | === logical operator compares the value as well as the data type, and hence is called strict comparison
52 |
53 | == will return true even if the data types of two particular values do not match.
54 | === will not return true even if the value matches but the data type of the two particular vaues do not match.
55 | */
56 |
57 | let password = "1234";
58 |
59 | if (password == 1234) {
60 | console.log("Correct Password");
61 | } else if (password !== 1234) {
62 | console.log("Wrong password, try again");
63 | }
64 | // != is a logical operator that means "not equal to", it compares whether the lhs is not equal to the rhs or not
65 | // !== is strict not equal to comparison, it even compares the data type
66 |
67 | let isProgrammer = true;
68 |
69 | // if(isProgrammer){
70 | // console.log('isProgrammer is declared');
71 | // }
72 | // else{
73 | // console.log('isProgrammer is not defined');
74 | // }
75 | // if just a variable is written as the condition, if it exists, then it will return true
76 | // that is a way to check whether a variable is declared or no
77 | // this is not a very good way of checking whether a variable is declared or not because when you check a non-declared(undefined) variable as a condition it will return an error if it does not exist at all, thus there is a better way to this which is as follows:
78 | // !variable name returns whether the variable is not true
79 | console.log(typeof isProgrammer);
80 | // undefined is a data type
81 | // undefined means that it does not exist at all
82 | // undefined also means when a variable has no value
83 | if (typeof isProgrammer !== undefined) {
84 | // the condtion states: if isProgrammer is undefined
85 | console.info("isProgramemr is declared");
86 | } else {
87 | console.info("isProgrammer is not declared");
88 | }
89 |
90 | let doesDrive = true;
91 | let isDrunk = true;
92 |
93 | if(doesDrive && (!isDrunk)){
94 | // if doesDrive is true and isDrunk is not true
95 | console.log('You can drive');
96 | }
97 | else{
98 | console.log("You can't drive");
99 | }
100 | // && is a logical operator that means "and"
101 | // || is a logical operator that means "or"
102 | // and and or operators are usually used to connect condtions in if statements
103 | // when you combine two conditons using &&, the if statement code block will only execute if both the condtions are true.
104 | // when you combine two conditions using || , the if statement code block will only execute if either of the condtions are true
105 |
106 | // another example of && and || operators
107 | age = 12;
108 | let parentalConsent = true;
109 |
110 | if(age>18 || parentalConsent){
111 | // this block will only be executed if either the age is more than 18 or he/she has parental consent
112 | // it will work even if one of them is true, in this case the first conditon is not true whereas the second is
113 | console.log('you can use social media :)');
114 | }
115 | else{
116 | console.log('you cannot use social media :/');
117 | }
118 |
119 | // TERNARY OPERATOR
120 | // ternary operator is an operator used for decision making
121 | // ternary operator takes three operands - a condition, expression to be executed if the condtion returns true and the expression to be executed if the conditoin returns false
122 | console.log(age==18? 'You are very young':'You are not very young');
123 | // condition? condtionToBeExecutedIfTrue : conditionToBeExecutedIfFalse;
124 |
125 | // SWITCH CASE
126 | let rank = 1;
127 | switch (rank) {
128 | case 1:
129 | console.log('You have got the first rank');
130 | break;
131 | case 2:
132 | console.log('You have got the second rank');
133 | break;
134 | case 3:
135 | console.log('You have got the third rank');
136 | break;
137 | default:
138 | console.log('You have got no rank :/');
139 | break;
140 | }
141 | /*
142 | switch(conditionLHS){
143 | case conditionRHS:
144 | code...
145 | break;
146 | case conditionRHS:
147 | code...
148 | break;
149 | case conditionRHS:
150 | code...
151 | break;
152 | default:
153 | code...
154 | break;
155 | }
156 |
157 | a switch case statement is just like if else statements
158 | it executes particular code when a particular condtion is true.
159 | conditionLHS is the expression to compare the cases to
160 | conditionRHS is the expression to compare to with the conditonLHS
161 | case checks if a certain value is equal to conditionLHS, if it is then it executes the code in the particular block
162 | you have to break the switch case statement after the code inside the case has been executed, it is done so to stop the execution of the switch case tree
163 | if we do not break the switch case after the code has been executed, the interpreter will run all the code inside the remaining switch cases without even checking whether the cases are true
164 |
165 | a switch case statement is useful when you have to check for values of a common variable
166 | */
--------------------------------------------------------------------------------
/conditionals8/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Conditionals in JavaScript
8 |
9 |
10 |
11 |
Conditionals in JavaScript
12 |
13 |
--------------------------------------------------------------------------------
/console2/console2.js:
--------------------------------------------------------------------------------
1 | // information about console API: https://console.spec.whatwg.org/
2 |
3 | console.time("Your Code Took");
4 | // syntax: console.time("identifier");
5 | // starts the timer
6 | // the timer calculates the time taken to run the code between two identifiers with the same name
7 | // the identifiers can also be compared to checkpoints loosely
8 |
9 | // you can also run javascript in browser console, but when you are making your own website,you would definitely want to keep the javascript code in an external file which is linked to the website HTML markup
10 |
11 | // if a file that you have linked is not actually available, javascript will return you 404 not found error
12 |
13 | // alert('this');
14 | // earlier, before es6, alert was used to debug javascript instead of console logs
15 |
16 | console.log('hello world');
17 | // console.log is used to debug javascript code
18 | // syntax= console.log(variable or string eclosed in quotes)
19 | // if you want to console log a string, you need to suplly the string as the parameter of the console, encolsed within single or double quotes
20 | // it logs a message into your console
21 | // we can access any function/variable from our console
22 | // it is also used to analyze webpages, suppose i want to know that how a particular webpage uses javascript, I can use the console to access various variables and functions to see how the website utilizes javascript
23 | // console.log prints the variable or the string(in quotes) and returns undefined
24 | // undefined informally means nothing
25 |
26 | console.log(51+32);
27 | // in javascript, you can also use the console as a calculator
28 | // even if you write calculations directly in the console without console.log, it will still perform the calculations and act as a calculator
29 | // if sometimes, you need a calculator immediately while in a browser, you can just open the browser console and use it as a calculator :)
30 | // console.log means that write something in the console as a log as it is
31 |
32 | console.log(true);
33 | // true will be printed in console
34 | // it is a boolean and you do not need to contain booleans within quotes
35 |
36 | console.log([32.4,42,21]);
37 | // you can also console log arrays and it will show it is a list in the console
38 | // an array is a set of values starting from index 0, more in further tutorials
39 |
40 | console.log({hargun:"boy", marks:43});
41 | // you can also console log objects
42 | // an object is also printed as a list
43 | // objects are contained within curly braces
44 | // an object has many key-value pairs and one key-value pair is sepearated by a comma
45 | // in javascript, you do not need to enclose the key of an object inside double quotes, only if it is a single work.. you need to contain the key in double quotes if it is not a single word
46 |
47 | console.table({hargun:"boy", marks:43});
48 | // console.table is used to print the contents of the paramenter of itself in the form of a table in the console
49 | // this is very helpful in debugging when you are dealing with bigger objects
50 |
51 | console.warn("This is a warning to you");
52 | // this is used to print a warning in the console
53 | // this is useful when you want to throw a warning according to your code logic
54 | // specifically in chrome dev tools, there is a different tab for warnings
55 |
56 | // console.clear();
57 | // this clears all the messages so far in the console
58 | // this returns a message which confirms that console is clearned
59 | // this method takes no arguements
60 | // it returns undefined
61 | // more here https://forum.freecodecamp.org/t/how-do-i-use-console-clear-to-modify/274951/2
62 |
63 | // semicolons in javascript
64 | // it is not mandatory to add a semicolon at the end of every javascript statement
65 | // javascript is a very forgiving langauge and runs your code without semicolons
66 | // it automatically assumes semicolons where they are needed
67 | // though it is a very good practice to add a semicolon at the end of every javascript statement, depecting the end of the statement to the parser
68 |
69 | console.timeStamp('hi');
70 | // it is non functional and does not work at most places
71 | // more here https://www.geeksforgeeks.org/node-js-console-timestamp-method/ https://nodejs.org/api/console.html#console_console_timestamp_label https://developer.mozilla.org/en-US/docs/Web/API/Console/timeStamp
72 |
73 | console.timeLog('Your Code Took');
74 | // logs the time at the timer of a specific identifier
75 |
76 | console.count('hi');
77 | console.count("hi");
78 | // console.count tells how many times a particular call has been made to the console
79 |
80 | // wheter you use '' or "" or `` doesnt matter
81 | // if you want to contain "" inside the string you should use '' or ``, it stands the same for the others
82 |
83 | console.log(console.memory);
84 | // prints the memory info
85 |
86 | console.timeEnd('Your Code Took');
87 | // this will end the timer with the specific identifier
88 | // if the console is cleared after starting the timer, timeEnd would return an error
89 |
90 | console.assert(564<180, 'Age above 180 is not possible');
91 | // syntax: console.assert(condition, error to be printed)
92 | // the condition is the first parameter and the error to be thrown is the second parameter
93 | // if the condition returns false then the error is thrown
94 | // if no particular error statement is defined it will throw the error as `Assertion failed`
95 |
96 | // What does console.assert help in?
97 | // the literal meaning of assert is to belief confidently
98 | // if the condition is false then assertion fails
99 | // console.assert is just used to check whether certain conditions are true
100 | // there are some cases where a set of code is run when certain conditons are met, if else is used there, console.assert is just used as a dummy to quickly check if conditions are true
101 |
102 | console.error('This is an error');
103 | // syntax: console.error('statement');
104 | // this throws an error in the console with a particular statement
105 |
106 | console.profile('hargun');
107 | // console.profile(identifier);
108 | // profiles are made mainly for performance reviews
109 | // you can find detailed analysis of a particular file in the performance tab of dev tools
110 |
111 | console.info('hi');
112 | // this is just like console.log but prints messages at info log levels
113 | // it can be compared to semantic HTML, it is semantic javascript
114 |
115 | console.debug('bruhhh');
116 | // this is also like console.log but prints the messages at debug log levels
117 | // it is also like semantic HTML
118 |
119 | // ending the profile
120 | console.profileEnd('hargun');
121 | // profile and profileEnd can give a message in the console at weird times seeing the hierarcy of the code
122 | // this is because profile and porfileEnd are syncronously called
123 |
124 | console.dir(Math);
125 | console.dir(Array);
126 | // console.dir returns the functions and methods inside a predefined javasript object
127 | // console.dir(predefined javascript object)
128 |
129 | function foo(){
130 | function bar(){
131 | console.trace();
132 | }
133 | bar();
134 | }
135 | foo();
--------------------------------------------------------------------------------
/console2/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Console Logs, Errors and Warnings in Javascript
8 |
9 |
10 |
11 | this is hargun
12 |
13 |
--------------------------------------------------------------------------------
/dataTypes4/dataTypes4.js:
--------------------------------------------------------------------------------
1 | // there are two types of data types: reference data types and primitive data types
2 | // primitive: data allocatoin in stack
3 | // reference: data allocation in heap
4 | // primitive data types are base data types
5 | // reference data types are objects, they are derived
6 |
7 | // javascript is a dynmaically typed language
8 | // dynamically typed means that if you assign a value to a variable, it will automatically figure out its data type and you do not explicitly have to tell a data type for a variable
9 |
10 | /*
11 | types of primitive data types:
12 | string - a collection of alphanumeric characters, they are to enclosed within '' or "" or ``
13 | numbers- they do not need to be enclosed
14 | boolean- either true or false
15 | null- intentionally null value
16 | undefined- it is the default value of every variable
17 | symbol- in further tutorials
18 | */
19 |
20 | /*
21 | types of reference data types:
22 | arrays
23 | object literals
24 | functions
25 | dates
26 | */
27 |
28 | // string operator
29 | let name = "Hargun";
30 | console.log("My name is "+ name);
31 | console.log("My name is", name);
32 | // you can concatinate two string variables or anything
33 | // concatination means joining of two or more things
34 | // in javascript you can use + or , for concatination
35 | // difference between + and , in concatination
36 | // + does not by default keep a space between two string or numbers which are to be concatinated
37 | // , by default keeps a space between two strings or numbers which are to be concatinated
38 | var bro;
39 |
40 | console.log("Data type is", (typeof bro));
41 | // you can figure out the type of a value using `typeof` method
42 | // syntax: (typeof value)
43 | // it will return the data type of the value, it could be any data type
44 |
45 |
46 | // NUMBERS
47 | let marks = 39;
48 | console.log("Data type is", (typeof marks));
49 | // this will return the data type of marks as number, if we enclose the number in quotes, it will become a string
50 |
51 | // BOOLEAN
52 | // a boolean can only be either true or false
53 | let isDriver = true;
54 | console.log("Data type is", (typeof isDriver));
55 | // the data type is boolean
56 |
57 | // NULL
58 | // null has a very bogus value
59 | let nullVar = null;
60 | console.log("Data type is", (typeof nullVar));
61 | // the data type of null is object, whereas null is a primitive data type and object is a reference data type
62 | // null is a primitive data type and this occurs due to a bug in javascript version 1 which cannot be fixed because it would break other code
63 | // more about it https://2ality.com/2013/10/typeof-null.html
64 |
65 | // UNDEFINED
66 | let undef = undefined;
67 | console.log("Data type is", (typeof undef));
68 | // the data type of undefined is undefined
69 |
70 | // more about undefined and null https://stackoverflow.com/questions/801032/why-is-null-an-object-and-whats-the-difference-between-null-and-undefined
71 |
72 |
73 | // REFERENCE DATA TYPES
74 | // Arrays
75 | let myArr = [1,2,3,4];
76 | console.log("Data type is",(typeof myArr));
77 | // the data type of an array is object
78 |
79 | // Object Literals
80 | let employee = {
81 | name: "Hargun",
82 | salary: 600000,
83 | 'job Post': "CEO"
84 | }
85 | // if you want to add a space in between key name, you will have to contain your key in quotes
86 |
87 | console.log("Data type is", (typeof employee));
88 |
89 | function findName() {
90 |
91 | }
92 | console.log("Data type is", (typeof findName));
93 | // the data type of a function is function
94 |
95 | let date = new Date();
96 | console.log("Data type is", (typeof date));
97 | // the data type of date is object
98 |
99 | // more about primitive and reference data types
100 | // https://www.youtube.com/watch?v=9ooYYRLdg_g
101 | // very informative
--------------------------------------------------------------------------------
/dataTypes4/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Data Types in JavaScript
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/editableDiv20/editableDiv20.js:
--------------------------------------------------------------------------------
1 | /*
2 | 1. create a div using javascript
3 | 2. when the div is clicked, it is transformed into a textarea
4 | 3. input something in the textarea
5 | 4. when the textarea loses focus, it is again converted to the div, and the value of the div is the vlaue of the textarea
6 | 5. store the value in localStorage so that next time when you visit the website it is updated
7 | */
8 | let main = document.querySelector('main');
9 | let keyPressed = false;
10 | // variable to store the state of the program
11 |
12 | let container = document.createElement('div');
13 | container.id = 'div';
14 | container.style = `width: 400px; height: 200px; border: 2px solid black;`
15 | main.appendChild(container);
16 |
17 | if(localStorage.getItem('divValue') !== null){
18 | container.innerText = localStorage.getItem('divValue')
19 | }
20 | // if there is some value for the div stored in the localStorage, LOAD THAT
21 |
22 | div.addEventListener('click', ()=>{
23 | var textArea = document.createElement('textarea');
24 | textArea.style = `width: 400px; height: 200px; border: 2px solid blue;resize: none;`;
25 | textArea.setAttribute('placeholder', 'Enter text to be placed in the div')
26 | container.replaceWith(textArea);
27 | if(localStorage.getItem('divValue') !== null){
28 | textArea.value = localStorage.getItem('divValue');
29 | }
30 | // if some value is there in teh local storage, LOAD THAT and make it editable
31 |
32 | textArea.addEventListener('keydown', (e)=>{
33 | keyPressed = true;
34 | // the blur function is not executed if keyPressed is true
35 | // the state of the function is kept in a variable because, when element is replaced- it automatically triggers the blur event as well
36 | if(e.key == "Enter"){
37 | localStorage.setItem('divValue', textArea.value);
38 | if(container.parentNode == null){
39 | // checks if container is still in the dom
40 | textArea.replaceWith(container);
41 | }
42 | container.innerText = textArea.value;
43 | }
44 | })
45 |
46 | textArea.addEventListener(('blur'), ()=>{
47 | localStorage.setItem('divValue', textArea.value);
48 | // sets the text of textarea as a value in the localstorage
49 | if(keyPressed == false){
50 | // runs only if the enter key is not pressed
51 | if(container.parentNode == null){
52 | // checks if container is in the dom
53 | textArea.replaceWith(container);
54 | }
55 | container.innerText = textArea.value;
56 | }
57 | });
58 | })
--------------------------------------------------------------------------------
/editableDiv20/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Exercise 2: Editable Div in JavaScript
8 |
9 |
10 |
11 |
12 |
Editable Div in JavaScript
13 |
14 |
15 |
--------------------------------------------------------------------------------
/events17/events17.js:
--------------------------------------------------------------------------------
1 | console.log('Events in JavaScript');
2 | // when you interact with your browser, you trigger some events
3 | // javascript provides us with the capability of capturing these events
4 | // when you click something it triggers an event
5 | // when you hover over something, it triggers an event and so on
6 |
7 | // click event is triggered when you click a certain element
8 | document.querySelector('h1').addEventListener('click', function(e){
9 | console.log("You are clicking the heading");
10 | // console.log(e);
11 | // location.href = "https://google.com";
12 | e.target.classList.add('heading', 'header');
13 | // console.log(e.target.classList);
14 | // it returns a DOM Token list
15 |
16 | // console.log(e.offsetX);
17 | // e.offsetX returns the x-offset of the location of your event relative to the start position of the element
18 |
19 | // console.log(e.offsetY);
20 | // e.offsetY returns the y-offset of the location of your event relative to the top position of the element
21 |
22 | console.log(e.clientX);
23 | // e.clientX returns the x-offset of the location of your event relative to the start of the browser window
24 |
25 | console.log(e.clientY);
26 | // e.clientY returns the y-offset of the location of your event relative to the top of the browser window
27 | });
28 | // element.addEventListener('event', function(){code})
29 | // this method executes the function when a specific event is triggered on the specific element
30 | // the first parameter of the call back function of this method is the event object, usually represented by 'e'
31 | // the event object has a lot of functions, a prominnet being e.target
32 | // e.target returns the target of the event that has occured or the element on which the event took place
33 |
34 |
35 | // mouseover event is triggered when your mouse is on a particular element
36 | document.querySelector('p').addEventListener('mouseover', function(e){
37 | console.log("your mouse is on the paragraph");
38 | });
39 |
40 | // makes the paragraph hidden and visible when the button is clicked
41 | document.querySelector('#hide').addEventListener('click', function(e){
42 | var pDisplay = document.querySelector('#para').style.display;
43 | if(pDisplay == 'none'){
44 | document.querySelector('#para').style.display = 'block';
45 | }else{
46 | document.querySelector('#para').style.display = 'none';
47 | }
48 | });
--------------------------------------------------------------------------------
/events17/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Events in JavaScript
8 |
9 |
10 |
11 |
Events in JavaScript
12 |
Lorem ipsum dolor sit amet consectetur adipisicing elit. Obcaecati vitae consequuntur soluta culpa eos reprehenderit assumenda harum odio sapiente aperiam error cupiditate nam, vero adipisci numquam facere debitis expedita sequi distinctio nobis rerum quisquam. Accusantium minus quisquam rerum nihil repellendus non.
13 |
14 |
15 |
--------------------------------------------------------------------------------
/functions10/functions10.js:
--------------------------------------------------------------------------------
1 | console.log("Functions and scopes in JavaScript");
2 | // a function is a block of code used to do certain tasks repeatedly on various different values without writing long lines of code
3 | // for example, you can write a function to greet a person
4 | function greet(name, role='friend') {
5 | console.log(`Happy Birthday ${name}. Thanks for being a ${role}!`);
6 | return "i am returning this";
7 | console.log("organise a birthday party");
8 | }
9 | /*
10 | function name(arguement1, arguement2=defaultValue){
11 | code;
12 | }
13 | arguements are the values a function will act on
14 | arguements can be infinitely many
15 | arguements are variables which are referenced in the function block
16 | those variables are assigned the values as per the calling of the function
17 | default value is the default value of a specific parameter, it is taken as the value on execution if no particular value is defined for a specific arguement
18 | it is a good practice to add default values as they save you from taking the parameter as undefined
19 | */
20 |
21 | greet("Rahul");
22 | /*
23 | you need to call a function to make it work and supply the arguments as values while you call the function
24 | functionName(arguments);
25 | the function will execute its code on your arguements
26 | if no value is given to a specific argument to a function, it takes it as undefined
27 | to prevent this you can set a default value of a parameter when you define a function
28 | */
29 |
30 | // a function by default returns undefined
31 | // you can return a specific value in a function using the return keyword
32 | // you can check what a function returns by calling it in a console.log
33 | // the function stops after the return statement
34 | // in a function, the code after the return statement will not be executed
35 | let val = greet("Hargun", 'god');
36 | console.log(val);
37 |
38 | let hobbies = ["programming", "dancing", "cooking"];
39 | function hobbyIncrease(arr) {
40 | arr.splice(arr.length - 1, 1, "singing");
41 | console.log(arr);
42 | }
43 | hobbyIncrease(hobbies);
44 | // if a function changes a value, it is changed outside the function as well
45 | console.log("The new array is", hobbies);
46 |
47 | // FUNCTION EXPRESSIONS
48 | const prize = function(awardType){
49 | console.log(`Congratulations! You won a prize for ${awardType}.`);
50 | }
51 | // here a function is being declared in a variable, you can call the function by the variable name
52 | // when you use a function expression to declare a function, you do not need to specify the function name
53 | // this type of function is called an anonymous function
54 | prize('Sports');
55 |
56 | // you can also declare a function as a key's value in an object
57 | const employee={
58 | name: 'Hargun',
59 | game: function(game){
60 | return `${this.name}'s favorite game is ${game}`;
61 | }
62 | }
63 | // you can call a function declared inside an object by referencing the key and then executing it
64 | // object.key();
65 | console.log(employee.game('Fortnite'));
66 |
67 |
68 | // SCOPES IN JAVASCRIPT
69 | let i = 212;
70 | console.log(i);
71 | function ui(name){
72 | i = 9;
73 | console.log(i);
74 | {
75 | var k = 'g';
76 | }
77 | console.log(k);
78 | return `This is by ${name}`;
79 | }
80 | console.log(ui('Dani'), i);
81 | // a function forms a closure
82 | // a closure is a binding which defines the scope of execution
83 | // a scope is the current context of execution of code
84 | // in other words, scope is the context where code can be referenced
85 | // a variable declared inside a function with the var keyword has function scope meaning that it can be referenced anywhere in the whole function
86 | // a variable declared inside a funciton with the let or const keyword has block scope meaning that it can only be referened in the block it has been declared an and the lower level blocks
87 | // a variable declared inside a function with no keywork has a global scope meaning that it can be referred from anywhere in the document
88 |
89 | function two(){
90 | console.log('Inside of two()',a);
91 | }
92 | function one(){
93 | var a = 2;
94 | console.log('Inside of one()',a);
95 | two();
96 | }
97 | var a = 1;
98 | console.log(a);
99 | one();
100 |
101 | function extFunc() {
102 | const extVar = "I used a closure"
103 | function intFunc() {
104 | console.log(extVar)
105 | }
106 | return intFunc;
107 | }
108 | const closure = extFunc();
109 | console.log(extFunc());
110 | console.log(closure());
111 | // extFunc() is a closure and closure() is taking advantage of extFunc() being a closure
112 | // the variable closure has the intFunc function as extFunc returns intFunc, extFunc has been executed
113 | // when you run closure() function, it will return you what intFunc() was supposed to return, intFunc refers to a variable outside its lexical environment
114 | // it refers to a variable in the outer environment which has already been executed, but still it can access the variable because of closures
115 | // closures store the data as reference types in heap memory
116 | // closures give you access to the variables outside a function
117 | // closures are usually functions bundled with scopes
118 | // closures help you to keep your code clean as they keep certain variables in the function and block memory
119 | // more about closures https://developer.mozilla.org/en-US/docs/Web/JavaScript/ClosureseFunc();
--------------------------------------------------------------------------------
/functions10/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Functions and Scopes in JavaScript
8 |
9 |
10 |
11 | Functions and Scopes in JavaScript
12 |
13 |
--------------------------------------------------------------------------------
/intro1/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Introduction to Javascript
8 |
9 |
10 |
11 |
12 | Intro
13 |
14 |
--------------------------------------------------------------------------------
/intro1/intro1.js:
--------------------------------------------------------------------------------
1 | console.log('hi');
2 | // this is just an introduction to javascript
3 | // move to tutorial 2
--------------------------------------------------------------------------------
/loops9/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Loops in JavaScript
8 |
9 |
10 |
11 |
Loops in JavaScript
12 |
13 |
--------------------------------------------------------------------------------
/loops9/loops9.js:
--------------------------------------------------------------------------------
1 | console.log("Loops in JavaScript");
2 |
3 | // a loop is a function which is repeatedly executed until a condition returns false
4 | // loops are used to do tasks repeatedly
5 | // there are three main loops: for, while and do while
6 |
7 | // FOR LOOP
8 | for (let i = 0; i < 10; i++) {
9 | console.log("🐸i is", i);
10 | }
11 | /*
12 | for(declaration; condition; updation){
13 | code;
14 | }
15 |
16 | declaration is the declaration of the variable to be used in the loop
17 | declaration is only executed once during the timeline of the loop
18 | the condition needs to be true for the loop to be executed
19 | updation is the updation of the loop variable to let the loop work on updated values and not the same value everytime
20 | */
21 | let a = 2;
22 | for (null; a < 10; a++) {
23 | console.log("🐈a is", a);
24 | }
25 | // if you do not want to declare a variable in a for loop, just write 'null' in declaration
26 |
27 | // WHILE LOOP
28 | // let j= 0;
29 | let j = 110;
30 | while (j < 100) {
31 | console.log("🐉j is", j);
32 | j++;
33 | j += 1;
34 | }
35 | /*
36 | while(condition){
37 | code;
38 | updation;
39 | }
40 | while loop is similar to for loop but in while loops, you do not need to declare a variable and define the updation in the parameters of the loop instead you just need to define a condition in the parameter of the while loop
41 | it is very highly recommended to add an updation after the main loop code because if the conditon variable is not updated the loop would transform into an infinite loop causing trouble
42 | when the conditon returns false, the loop wont run
43 | j++ and j+=1 are one and the same thing
44 | if the condition is false, the loop won't run at all
45 | */
46 |
47 | // DO WHILE LOOP
48 | let k = 0;
49 | // delete(k);
50 | // you can delete a global variable as well as an object property by using delete(variable)
51 | // it will not delete variables declared with var, let or const keyword
52 | console.log(k);
53 | do {
54 | if (k == 5) {
55 | break;
56 | // the break statement breaks the loop
57 | } else if (k == 2) {
58 | k += 1;
59 | continue;
60 | // the continue statement stops the loop and does not execute the commands after the it has broken the loop
61 | // it does not execute the code after it is executed and then it runs the loop from the start
62 | }
63 | console.log("😉k is " + k);
64 | k++;
65 | } while (k < 10);
66 | /*
67 | do{
68 | ...code;
69 | } while(condition)
70 |
71 | do while loop is exactly similar to while loop, there is just one difference that the condition is checked after the loop has been executed
72 | due to this, the loop is run the first time even if the condition is false
73 | */
74 |
75 | // FOR EACH LOOP
76 | let hobbies = ["programming", "talking", "cooking"];
77 | hobbies.forEach((element, index, array) => {
78 | console.info("My hobby is", element, index, array);
79 | });
80 | /*
81 | array.forEach(function(element, index, array){
82 | code;
83 | });
84 | forEach iterates over the values of an array
85 | the first parameter for the function inside the forEach is a value of the array
86 | the second parameter for the function inside the forEach is an index of the corresponding value of the array
87 | the third parameter for the function inside the forEach is the array itself
88 | you can also use an arrow function inside of forEach
89 | */
90 |
91 | // For of loop
92 | let info = {
93 | name: "Hargun",
94 | 'github repository': "JavaScript-Notes",
95 | // contain the object key inside quotes if it contains spaces
96 | age: 14,
97 | 'favorite programming language': 'JavaScript',
98 | }
99 | for (const key in info) {
100 | console.log(`The ${key} of Hargun is ${info[key]}`)
101 | }
102 | /*
103 | for(const key in object){
104 | code...;
105 | }
106 | forIn loop is used to iterate over the keys of an object
107 | it takes two parameters- the first one being the key and the second one being the corresponding object
108 | */
109 |
110 | // FOR OF LOOP
111 | for (const element of hobbies) {
112 | console.log('I like', element);
113 | }
114 | /*
115 | for of loop is similar to for in and forEach
116 | for of loop is used to iterate over the values of an iterable object
117 | for(const element of iterableObject){
118 | code;
119 | }
120 | the first parameter is the value of the iterableObject
121 | the second parameter is the iterable object
122 | */
123 |
124 | /*
125 | BONUS
126 | the difference between , and + concatinator
127 | when you use , for concatination, it returns the concatinated value without converting it to a string and returns the concatinated value by just joining the two(or more) values
128 | when you use + for concatination, it returns the concatinated value by converting it to a string data type
129 | */
130 |
--------------------------------------------------------------------------------
/manipulatingDOM11/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Manipulating Websites in JavaScript
8 |
9 |
15 |
16 |
17 |
Manipulating Websites in JavaScript
18 |
19 |
--------------------------------------------------------------------------------
/manipulatingDOM11/manipulationDOM11.js:
--------------------------------------------------------------------------------
1 | console.log('%cManipulating Websites using JavaScript', 'background: green;color: yellow;');
2 | // DOM manipulation in JavaScript
3 | // DOM stands for Document Object Model
4 | // DOM is the HTML
5 | // using DOM object in JavaScript, you can manipulate the HTML
6 |
7 | console.dir(window)
8 | // it will return the window object, we can see all the functions window object has in the console
9 | // window is a global object in JavaScript
10 | // alert('hargun');
11 | // window.alert('hargun');
12 | // alert() and window.alert() are one and the same thing because the window object4 in global in JavaScript
13 | // document is a part of the Window Object
14 |
15 | // PROMPT
16 | // window.prompt() and prompt() are one and the same thing because the window object in global in JavaScript
17 | // let name = prompt("Please enter your name", "Dani");
18 | // let varName = prompt(Question, defautValue);
19 | // the variable varName stores the value inputted by the user via the prompt
20 | // the Question is the thing to be asked for in the prompt
21 | // defaultValue is the defautlt
22 | // console.log('The good name is %c'+name, 'color: red;');
23 |
24 | // CONFIRM
25 | // let confirmationVal =confirm("Are you sure you want to delete this?");
26 | // confirm(message)
27 | // the confirm method displays a dialog box with a specified message, along with an OK and a cancel button
28 | // it is often used if you want the user to verify or accept something
29 | // it returns either true or false, it returns true if the "OK" button is clicked, it returns false if the "Cancel" button is clicked
30 | // console.log(confirmationVal);
31 |
32 | // WINDOW DIMENSIONS
33 | console.info('The outer height of window is '+ window.outerHeight);
34 | // window.outerHeight returns the outerHeight of the window, outerHeight is the outer height of the window
35 | console.info('The inner height of window is '+ window.innerHeight);
36 | // window.innerHeight returns the innerHeight of the window
37 | console.info('The difference between the inner and outer heigt of the window is '+(window.outerHeight - window.innerHeight));
38 |
39 | console.info(scrollX);
40 | // scrollX is the scroll value on the x-axis
41 | console.info(scrollY);
42 | // scrollY is the scroll value on the y-axis
43 |
44 | console.info(location);
45 | // location is an object which contains information about your location on the web
46 | console.info(location.href)
47 | // location.href returns the link of the website you are currently in
48 |
49 | // location.href = "https://google.com";
50 | // it will change the href of the web page
51 |
52 | console.info(location.toString());
53 | // location.toString returns the href of the webpage in a string datatype
54 |
55 | console.info(window.history);
56 | // window.history returns the history of the links you had visited on that particular tab
57 | history.go(2);
58 | // history.go(value) will go to the link in your history, value number of times, a negative value will go back to the link you had surfed
59 | // history.go() immitiates the behavior of the last webpage and the next webpage buttons
--------------------------------------------------------------------------------
/moreEvents18/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | More on events in JavaScript
8 |
9 |
18 |
19 |
20 |
More on events in JavaScript
21 |
Lorem ipsum dolor sit amet consectetur adipisicing elit. Obcaecati vitae consequuntur soluta culpa eos reprehenderit assumenda harum odio sapiente aperiam error cupiditate nam, vero adipisci numquam facere debitis expedita sequi distinctio nobis rerum quisquam. Accusantium minus quisquam rerum nihil repellendus non.
22 |
23 |
24 |
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/moreEvents18/moreEvents18.js:
--------------------------------------------------------------------------------
1 | console.log("More on Events in JavaScript");
2 |
3 | document.getElementById("para").style.color = "black";
4 | // setting the default color of the paragraph
5 |
6 | // listen to the click event on the button
7 | document.getElementById("colorBtn").addEventListener("click", () => {
8 | if (document.getElementById("para").style.color == "red") {
9 | // change the color to black if the color is red
10 | document.getElementById("para").style.color = "black";
11 | } else if (document.getElementById("para").style.color == "black") {
12 | // change the color to red if the color is black
13 | document.getElementById("para").style.color = "red";
14 | }
15 | });
16 |
17 | const submitBtn = document.getElementById("submit");
18 |
19 | submitBtn.addEventListener("click", func1);
20 | // executes the func1 function when the button is clicked
21 |
22 | function func1(e) {
23 | // console.log("Thanks");
24 | e.preventDefault();
25 | // e.preventDefault() prevents the default behaviour of the target
26 | // in this case, the default behaviour of the button is to submit the form and e.preventDefault() prevents that
27 | }
28 |
29 | submitBtn.addEventListener('dblclick', (e)=>{
30 | console.log("hi");
31 | }, {capture: false, passive: true})
32 | // target.addEventListener('event', funciton, options)
33 | // dblclick means double click
34 | // if capture is false then it will take place after the eventListener whose capture is set to true
35 | // if passive is true, then it returns a warning in the console if preventDefault is called in the function
36 |
37 | submitBtn.addEventListener('dblclick', func2, {once: true, capture: true, passive: true});
38 | // if once is set to true then the function will only be executed once
39 |
40 | function func2() {
41 | console.info("Yay! its a double click!");
42 | }
43 |
44 | document.querySelector('#hold').addEventListener('mousedown', (e)=>{
45 | console.info("Its a mousedown");
46 | });
47 | // mousedown is triggered when you click the target, it could be a left, right or middle click
48 |
49 | document.querySelector('#box').addEventListener('mouseenter', (e)=>{
50 | console.log("you have entered the box");
51 | })
52 | // mouseenter is triggered when you enter the target
53 |
54 | document.querySelector('#box').addEventListener('mouseleave', (e)=>{
55 | console.log("you have left the box");
56 | })
57 | // mouseleave is triggered when you leave the target
58 |
59 | document.body.addEventListener('mousemove', (e)=>{
60 | console.log(`The coordinates of your mouse are ${e.offsetX} and ${e.offsetY}`)
61 | document.body.style.background= `rgb(${e.offsetX}, ${e.offsetY}, ${e.offsetX - e.offsetY})`
62 | // we are changing the background of the body according to the coordinates of the mouse when it moves
63 | })
64 | // mousemove is triggered when you move your mouse inside the target
--------------------------------------------------------------------------------
/storage19/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Local and Session Storage in JavaScript
8 |
9 |
10 |
11 |
Local and Session Storage in JavaScript
12 |
13 |
--------------------------------------------------------------------------------
/storage19/storage19.js:
--------------------------------------------------------------------------------
1 | console.log("Local and Session storage in JavaScript");
2 |
3 | // there are two types of browser storage: local storage and session storage
4 | // local storage is the storage of a browser where particular key-value pairs are stored and retained unless they are deleted
5 | // local storage has a different container for every website
6 | // you can see the key-value pairs graphically in chrome dev tools by: Application >> Local Storage >> Domain
7 |
8 | // session storage is the browser storage in which key-value pairs are stored and retained for the current user session
9 | // a session is the time while the website is open
10 |
11 |
12 | localStorage.setItem('name', 'hargun');
13 | localStorage.setItem('name2', 'dani');
14 | // localStorage.setItem(key, value)
15 | // this is used to add values to the local storage
16 |
17 | console.log(localStorage);
18 | // localStorage is an object containing all the key-value pairs
19 |
20 | console.log(typeof localStorage.name)
21 | // returns the type of the name key in local storage
22 | // you can reference the value of a key by localStorage.key
23 |
24 | console.log("The first name is " + localStorage.getItem('name'));
25 | // to fetch the value of a key from localstorage use the following syntax:
26 | // localStorage.getItem(key)
27 | // it returns the value corresponding to the key
28 | console.log("The second name is " + localStorage.getItem('name2'));
29 |
30 | console.log("The rank is " + localStorage.getItem('rank'))
31 | // when you try to fetch a value from github whose key-value pair does not exist, it will return null
32 |
33 | // localStorage.clear()
34 | // clears the localStorage
35 | // deletes all the key-value pairs in the localStorage
36 |
37 | localStorage.removeItem('name');
38 | // localStorage.removeItem(key)
39 | // this function deletes a specified key-value pair from local storage
40 |
41 | let hobbies = ['programming', 'dancing', 'cooking'];
42 |
43 | // localStorage.setItem('myHobbies', hobbies)
44 | // there is a problem with storing arrays in localStorage
45 | // their values are individually stringified and when you retrieve them, they are not in an array form
46 |
47 | localStorage.setItem('myHobbies', JSON.stringify(hobbies))
48 | // we Json stringify an array or object before storing it to the localStorage so that we can parse it when we retrieve it
49 |
50 | console.log(localStorage.getItem('myHobbies'))
51 | // this will return the value in myHobbies as a JSON string
52 |
53 | console.log(JSON.parse(localStorage.getItem('myHobbies')))
54 | // this will return an array that was JSON stringified and stored to myHobbies, we JSON parse that array so that its data type is array
55 |
56 |
57 | // SESSION STORAGE
58 | // the methods of session object are identical to that of local storage
59 | // session storage is cleared when the session ends
60 | // a session ends when the website tab is closed
61 | // a session does not end on page refresh
62 |
63 | // sessionStorage.setItem('github', 'hamiecod');
64 | console.log("The session storage github username is "+ sessionStorage.getItem('github'));
65 | // the setItem and getItem and clear methods are exactly the same as of localStorage methods
--------------------------------------------------------------------------------
/strings6/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Strings in JavaScript
8 |
9 |
10 |
11 |
12 | Strings in JavaScript
13 | hi wassup
14 |
15 |
16 |
--------------------------------------------------------------------------------
/strings6/strings6.js:
--------------------------------------------------------------------------------
1 | console.log("We are tut 6");
2 | const name = "Hargun";
3 | const greeting = "Good Morning";
4 | console.log(greeting, name);
5 | // the comma is used for concatination
6 | // javascript is primarily used to make websites thus there is a lot of string manipulation javascript can do
7 | // in this tutorial we will discuss about string functions, methods and template literals
8 |
9 | let html;
10 | // declaration
11 |
12 | // html will hold html markup
13 | // html = "
this is heading
14 | //
this is My Para";
15 | // double quotes or single quotes cannot be used to write multiple line strings like the one above which is HTML code
16 | // there are three solutions to it:
17 | // 1. concatinate strings on multiple lines using + or ,
18 | html = "
this is heading
" + "
this is My Para
";
19 | // but if you are long strings, this is not at all efficient and feasible
20 | // you can also you the concat string function
21 | html = html.concat("this", "hi");
22 | // string.concat(...stringtoBeadded)
23 | console.log(html);
24 |
25 | console.log(html.length);
26 | // string.length will return the character length of the string
27 | console.log(html.toUpperCase());
28 | // string.toUpperCase() will turn all the characters to upper case
29 | console.log(html.toLowerCase());
30 | // string.toLowerCase() will turn all the characters to lower case
31 |
32 | console.log(html[1]);
33 | // string[index] will return the letter at ${index} of the string
34 | // the index starts from 0 and goes on
35 |
36 | console.log(html.indexOf("this"));
37 | // string.indexOf(subString) returns the index of the first character of the first occurence of the particular substring
38 | console.log(html.lastIndexOf("this"));
39 | // string.lastIndexOf(subString) returns the index of the first character of the last occurence of the particular substring
40 | console.log(html.charAt(3));
41 | // string.charAt(index) returns the character at the particular index of the string
42 | console.log(html.endsWith(">", 4));
43 | // string.endsWith(substring) returns whether a string ends with a particular substring
44 | // syntax: string.endsWith(substring, lenghtofactualstring)
45 | // the length of actual string is the length of be searched from
46 | // for example
47 | // the length of actual string is given to be 22, so the interpretor will only check whether the first 22 characters end with substring or not
48 | // so it slices particular number of letters from the real string and checks if that ends with search string or not
49 | // it returns either true or false
50 | // more https://www.w3schools.com/jsref/jsref_endswith.asp
51 |
52 | console.log(html.startsWith("h", 1));
53 | // string.startsWith(searchString, startIndex);
54 | // it checks whether the string starts with the search value starting from the supplied start Index
55 | // more: https://www.w3schools.com/jsref/jsref_startswith.asp
56 |
57 | console.log(html.includes("th"));
58 | // string.includes(searchString);
59 | // checks whether a string includes the search string
60 | // return true or false
61 |
62 | console.log(html.substring(1, 6));
63 | // string.substring(startIndex, endIndex+1)
64 | // startIndex = x ; endIndex = y
65 | // substring function returns the substring from a string, the substring returned starts from startIndex(x) and through endIndex-1(y-1)
66 | // for example, substring(1,7) will return the letters at index 1,2,3,4,5,6 as the substring
67 | // it includes the startIndex position and does not include the end index position within the substring
68 | // if the startIndex is equal to the endIndex, it return empty string ""
69 | // if stop is omitted, it extracts the whole string till the end
70 | // if any arguement is greater than the string length, the string's length will be used
71 | // if startIndex > endIndex, then it swaps both the values
72 | // a negative or ineligible arguement is treated as 0
73 |
74 | console.log(html.slice(0, 5));
75 | // string.slice(startIndex, endIndex+1)
76 | // it does the same thing as substring except that it can except negative values
77 | console.log(html.slice(-4, -1));
78 | // negativey indexes start from -1
79 | // negative index -1 starts from the last character of the string
80 | // the above will return a string containing character at -4, -3 and -2 index of the string
81 | // negative indexes start from the end, and go on decreasing
82 | // if startIndex > endIndex then it returns an empty string
83 | // if value is negative then = string.length - value
84 |
85 | // difference between slice and substring: https://www.geeksforgeeks.org/javascript-difference-between-string-slice-and-string-substring
86 |
87 | console.log(html.substr(1, 5));
88 | // string.substr(startIndex, lengthtoextract)
89 | // the first arguement is the index to start extracting the string from
90 | // the second arguement is the number of characters to be extracted from the string starting from the start Index
91 |
92 | console.log(html.split(" "));
93 | // string.split(stringWhereToSplit)
94 | // it splits a string into an array of elements
95 | // it splits the string where a particular string is found
96 | // for example: split('hi')
97 | // wherever the interpretor finds the specific string, it splits the string to another array element, it will not consider hi in the element
98 | // split(' ');
99 | // "hi die bro"
100 | // in the above the interpretor will form three elements and split the string where it finds a space and will not include the space in the elements
101 | // it will return ['hi','die','bro']
102 |
103 | console.log(html.replace("this", "it"));
104 | // string.replace(subStringToBeChanged, newSubString)
105 | // it will replace the first occurence of the specific substring with the new substring
106 | // in the above the interpretor replaces 'this' with 'it'
107 | // NOTE: it only replaces the first occurence
108 |
109 | const whiteSpace = " d dsf ds ";
110 | console.log(whiteSpace.trim());
111 | // string.trim() removes all the spaces at the START and the END of the string
112 | // it removes all the spaces before the first character and all the spaces after the last character
113 |
114 | console.log(html.anchor("link"));
115 | // string.anchor(name);
116 | // it is non standard function
117 | // it encloses the string within anchor tags with a specific name
118 |
119 | console.log(html.big());
120 | // this function is deprecateed
121 | // it encloses the string within big tags
122 |
123 | console.log(html.blink());
124 | // encloses the string inside blink tags
125 |
126 | console.log(html.bold());
127 | // encloses the string inside bold tags
128 |
129 | console.log(html.charCodeAt(2));
130 | // string.charCodeAt(index)
131 | // this function returns the character code of the character at particular index
132 | // prints UFF-16 code
133 |
134 | console.log(html.codePointAt(2));
135 | // string.charPointAt(index)
136 | // this function returns the character code of the character at particular index
137 | // prints unicode
138 |
139 | // charPointAt vs charCodeAt: https://stackoverflow.com/questions/36527642/difference-between-codepointat-and-charcodeat
140 |
141 | console.log(html.fixed());
142 | // non standard method
143 | // it encloses the string in tag representing teletype
144 | // tt tag prints the contents in consolas font
145 |
146 | console.log(html.match("h1"));
147 | // string.match(string)
148 | // this method is used for substring search and uses regular expressions
149 | // more about regular expressions in later tutorial
150 | // more: https://www.w3schools.com/jsref/jsref_match.asp
151 |
152 | console.log(html.fontcolor("green"));
153 | // this method is non standard
154 | // this method encloses the string within the font tag
155 | // the parameter is the color
156 |
157 | console.log(html.fontsize(32));
158 | // string.fontsize(size)
159 | // this method encloses the string in font tag and specifies the size which is the parameter
160 |
161 | console.log(html.italics());
162 | // non standard method
163 | // this method encloses the string in i tag, italicizing it
164 |
165 | console.log(html.link("https://google.com"));
166 | // non standard method
167 | // encloses the string within anchor tag with href attribute
168 | // the parameter is the value of href attribute
169 |
170 | let str1 = "ab";
171 | let str2 = "b";
172 | console.log(str1.localeCompare(str2));
173 | // referenceString.localeCompare(compareString);
174 | // it returns whether the reference string comes before, after or is equal as the compareString in sort order
175 | // -1 = reference string is sorted before compareString
176 | // 0 = the two string are equal
177 | // 1 = the reference string is sorted after the compare string
178 | // the longer string will be sorted before the shorter string
179 |
180 | let devName = `\u0048\u0061\u0072\u0067\u0075\u006e`;
181 | console.log(devName.normalize());
182 | // string.normalize(form)
183 | // this method converts unicodes into normal alphabets
184 | // the format for unicode is : u\0001
185 | // there are three forms for normalization: nfc, nfd, nfkc and nfkd, nfc is default
186 | // they are almost the same
187 | // more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize
188 | // unicodes: https://unicode-table.com/en/alphabets/english/
189 |
190 | console.log(html.matchAll("h1"));
191 | // just like match() but returns multiple matches
192 | // more about them in reg ex tutorial
193 |
194 | console.log(html.padEnd(71, "hi"));
195 | // string.padEnd(maxLength, padString)
196 | // this method continuously adds the padString to the end of the original string until it reaches the maxLength whilst doing so
197 |
198 | console.log(html.search("<<"));
199 | // string.search(searchString)
200 | // this method returns the index of the first character of the first occurence of the search string
201 | // return -1 if no value found
202 | // similar to indexOf
203 | // if you are using regular expressions use search, if not use indexOf
204 | // string.search('/hi/i')
205 | // include the string value withit /.../i to perform a case insensitive search
206 |
207 | // search vs match
208 | // search is for fast and less info checks, match is for slow but more info checks
209 | // in detail: https://stackoverflow.com/questions/18687530/using-match-and-the-difference-between-search
210 |
211 | console.log(html.padStart(71, "hi"));
212 | // string.padStart(maxLength, padString)
213 | // this method continuously adds the padString at the beginning of the string until it reaches the maxLength specified
214 |
215 | console.log(html.repeat(2));
216 | // string.repeat(count)
217 | // this method returns a new string with $Pcount} number of copies of the string in the same string
218 |
219 | console.log(html.small());
220 | // string.small()
221 | // this method encloses the string within element which causes the string to be displayed in a small font
222 |
223 | console.log(html.startsWith("
"));
224 | // string.startWith(subString);
225 | // this method returns whether a string starts with a particular substring
226 | // it returns either true or false
227 |
228 | console.log(html.strike());
229 | // string.strike()
230 | // encloses a string in tag, the strike tag strikes the text inside
231 |
232 | console.log(html.sub());
233 | // string.sub();
234 | // encloses a string in tag, the sub tag, makes the string inside a subscript
235 |
236 | console.log(html.sup());
237 | // string.sup();
238 | // encloses a string in tag, the subp tag, makes the string inside a superscript
239 |
240 | console.log(html.toLocaleLowerCase());
241 | // string.toLocaleLowerCase()
242 | // this method transforms the string to lower case taking localization of langauge into account
243 |
244 | console.log(html.toLocaleUpperCase());
245 | // string.toLocaleUpperCase()
246 | // this method transforms the string to upper case taking localization of langauge into account
247 |
248 | console.log(whiteSpace.trimEnd());
249 | // string.trimEnd()
250 | // this method removes the whitespaces at the end of the string
251 |
252 | console.log(whiteSpace.trimStart());
253 | // string.trimStart()
254 | // this method removes the whitespaces at the start of the string
255 |
256 | console.log(whiteSpace.trimLeft());
257 | // string.trimLeft()
258 | // this method removes the whitespaces at the left of the stirng
259 | // this is an alias for trimStart
260 |
261 | console.log(whiteSpace.trimRight());
262 | // string.trimRight()
263 | // this method removes the whitespaces at the right of the stirng
264 | // this is an alias for trimEnd
265 |
266 | let employee = {
267 | name: "hargun",
268 | age: 42,
269 | };
270 | console.log(employee.valueOf());
271 | // this method just returns the value of a particular string
272 |
273 | // Template Literals
274 | let lang1 = "CSS";
275 | let lang2 = "SCSS";
276 | let myHtml = `Hello ${name}
277 |
This is heading
278 |
I like ${lang1}, but I like ${lang2} more
279 | `;
280 | // template literals are contained within backticks(``), you can include '' and "" inside of them, they also provide support for variables
281 | // they are just used as fill in the blanks
282 | // ${varName}, when written in the template literal, it will be replaced by the value of the variable
283 |
284 | document.querySelector('.container').innerHTML = "";
285 | document.querySelector('.container').innerHTML = myHtml;
286 |
287 | let owner = 'Hargun\'s';
288 | // when you need to use ' in a string enclosed with '' you need to write it as \'
289 | // when you need to use " in a string enclosed with "" you need to write it as \"
290 | // you need to prefix the every uncommon letter with \ in a string when it is enclosed with "" or ''
291 | console.log(owner);
--------------------------------------------------------------------------------
/traversing15/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Children, Parent and Traversing the DOM
8 |
9 |
10 |
11 |
12 |
13 |
14 | gg
15 |
Traversing the DOM
16 |
17 |
Things to buy are as follows:
18 |
19 |
Pencils
20 |
21 |
Go to shopkeeper
22 |
Buy two pencils
23 |
24 |
Notebooks
25 |
Fruits
26 |
Vegetables
27 |
28 |
Carrots
29 |
Tomatoes
30 |
31 |
32 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/traversing15/traversing15.js:
--------------------------------------------------------------------------------
1 | console.log('Traversing the DOM');
2 |
3 | let container = document.querySelector('.container');
4 | console.log(container.childNodes);
5 | // element.childNodes returns all the child nodes of the element
6 | // childNodes also includes the comments and the newlines as text, it also considers other things like doctype html as a child
7 | // we do not want these things most of the time, but in some cases we could need them
8 | // it returns a node list
9 |
10 | console.log(container.children);
11 | // element.children returns all the children of the element as an HTML collection
12 | // it will not consider the text and comments as an element, it will only consider the tags as elements
13 |
14 | console.log(container.childNodes[3].nodeName);
15 | // nodeName returns the name of the node
16 |
17 | console.log(container.childNodes[1].nodeType);
18 | // nodeType returns the type of the node, it returns a number
19 | // Node types
20 | // 1: element
21 | // 2: attribute
22 | // 3: text node
23 | // 8: comment
24 | // 9: document
25 | // 10: doctype
26 |
27 | // you can also find the children of children of an element
28 | console.log(container.children[1].children[1].children[5].children[0].innerText);
29 |
30 | console.log(container.firstChild);
31 | // firstchild returns the first child node
32 |
33 | console.log(container.firstElementChild);
34 | // firstElementChild returns the first element child
35 |
36 | console.log(container.lastChild);
37 | // lastchild returns the last child node
38 |
39 | console.log(container.lastElementChild);
40 | // lastElementChild returns the last element child
41 |
42 | console.log(container.childElementCount);
43 | // returns the number of child elements
44 |
45 | console.log(container.parentNode);
46 | // parent node returns the element's parent node
47 |
48 | console.log(container.parentElement);
49 | // returns the element's parent element
50 |
51 | console.log(container.firstElementChild.nextSibling);
52 | // returns the next sibling node
53 |
54 | console.log(container.firstElementChild.nextElementSibling);
55 | // returns the next element nextSibling
--------------------------------------------------------------------------------
/typeConversionCoercion5/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Type Conversion and Type Coercion in JavaScript
8 |
9 |
10 |
11 | Type Conversion and Type Coercion in JavaScript
12 |
13 |
--------------------------------------------------------------------------------
/typeConversionCoercion5/typeConversionCoercion5.js:
--------------------------------------------------------------------------------
1 | // type conversion in JavaScript
2 | console.log("Welcome tutorial 5");
3 | let myVar;
4 | myVar = String(34);
5 | // here we are changing the data type of 34 that is a number to a String data type
6 |
7 | console.log(myVar, (typeof myVar));
8 |
9 | let booleanVar = String(true);
10 | // here we are converting a boolean into string
11 | console.log(booleanVar, (typeof booleanVar));
12 |
13 | let date = String(new Date());
14 | // converting a date object to a string
15 | console.log(date, (typeof date));
16 |
17 | let arr = String([1,2,3,4,5]);
18 | // converting an array to string data type
19 | // while converting an array to a string the enclosing brackets do not count
20 | console.log(arr, (typeof arr));
21 | // data type determines the properties of a value
22 | // for example in the above array, their are 5 values, but when you convert it to a string it is classified as 9 characters(the commas are included)
23 |
24 | // what is the benefit of converting other data types to string data type:
25 | // on string data type, you can use a vast collection of string functions
26 |
27 | let position = 8;
28 | console.log(position.toString());
29 | console.log(String(position));
30 | // converting number to string
31 | // their are two ways two convert a data type to a string, they are listed above- value.toString() and String(value)
32 | // these both methods have very minor difference that too at the interpretation level
33 | // their difference: https://stackoverflow.com/questions/3945202/whats-the-difference-between-stringvalue-vs-value-tostring
34 |
35 |
36 | // Number
37 | let stri = Number("3234");
38 | // converting a string to number
39 | // if you convert an alphanumeric value to a number it will return NaN
40 | console.log(stri, (typeof stri));
41 |
42 | let isTouching = Number(true);
43 | // while converting boolean to number, true will correspond to 1 and false will correspond to 0
44 | console.log(isTouching, (typeof isTouching));
45 | // if you try to convert anything invalid to a number, it will return NaN
46 |
47 | let roll = Number([23,133,34]);
48 | console.log(roll, (typeof roll));
49 | // an array cant be converted to a number so it will return NaN
50 |
51 | // let length = parseInt('33.232');
52 | let length = parseFloat('33.346');
53 | // parseInt will convert a value to an integer value
54 | // parseFloat will convert a value to a decimal value
55 | console.log(length.toFixed(2), (typeof length));
56 | // toFixed(value) will show the ${value} number of decimal points after the value, also it rounds up the value while showing a specific number of decimal points
57 |
58 |
59 | // TYPE COERCION IN JAVASCRIPT
60 | let salary = "3000";
61 | let bonus = 100;
62 | console.log(salary + bonus);
63 | // when you are using the + operator with string and number type, during runtime the interpretor has two options:
64 | // 1. convert the number to a string and concatinate both the strings
65 | // 2. convert the string to a number and add the both
66 | // so the compiler chooses the former, this is called type coercion
67 | // type coercion refers to the implicit conversion of values
68 | // you can choose the 2nd explicitly by type converting the string to a number
69 |
70 | /*
71 | there are three types of type coercion:
72 | 1. non-string to string conversion: it is done when a non-string data type is added to a string
73 | 2. non-number to number: it is done when -,*,/ or % operation is performed, all non-number values are converted to number
74 | 3. Boolean to number: when a boolean is added to a number, it is converted to number, 0 for false and 1 for true
75 | 4. equality operation(non-number to number): == is used to compare values irrespective of their data types, so suppose a string is compared to a number, it will be converted to a number due to coercion, all non-number types are converted to number type.
76 |
77 | more about coercion: https://www.geeksforgeeks.org/what-is-type-coercion-in-javascript/
78 | */
--------------------------------------------------------------------------------
/understandingDOM12/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Understanding DOM in JavaScript
8 |
9 |
10 |
11 |
30 |
31 |
--------------------------------------------------------------------------------
/understandingDOM12/understandingDOM12.js:
--------------------------------------------------------------------------------
1 | console.info('Understanding DOM in JavaScript');
2 |
3 | console.dir(document);
4 | // returns the document object
5 |
6 | // DOM is the structrual representation of the HTML markup
7 |
8 | console.log(document.all);
9 | // document.all returns all the tags in the document
10 | // it returns a kind of array but it is not actually an array and array funciton wont run on it
11 |
12 | // (document.all).forEach(function(element){
13 | // console.log(element);
14 | // });
15 | // this wont work as document.all is not really an array
16 |
17 | console.groupCollapsed('Items of document.all');
18 | Array.from(document.all).forEach(element=>{
19 | console.log(element);
20 | });
21 | // Array.from(value)
22 | // Array.from makes an array from the HTML collection
23 | // you can run a forEach after converting document.all into an array
24 | console.groupEnd('Items of document.all');
25 |
26 | console.log(document.body);
27 | // document.body returns the body tag
28 |
29 | console.log(document.forms[0]);
30 | // document.forms returns all the forms in the document
31 | // it returns an array
32 |
33 | console.log(document.links);
34 | // document.links will return all the links in the document
35 | // it returns an array
36 | console.log(document.links[0].href);
37 | // it will return the link of the first link
38 |
39 | console.log(document.scripts)
40 | // document.scripts returns all the script tags in the document in an array
--------------------------------------------------------------------------------
/variables3/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Variables in JavaScript
8 |
9 |
10 |
11 | Variables(let, var and const) in JavaScript
12 |
13 |
--------------------------------------------------------------------------------
/variables3/variables3.js:
--------------------------------------------------------------------------------
1 | console.log("tutorial3- varaibles");
2 | /* Variables in js
3 | a variable is a container that is used to contain something
4 | suppose you use a bottle for storing water, similarly we use variables to store values
5 | you cannot store rice in a bottle, because bottle is made to store something else, similarly particular type of variables are used to store particular type of values
6 |
7 | keywords used to make variables: var, let, const
8 | when we tell our interpreter that a particular variable exists - it is called declaration/initialization
9 | a value can be assigned to a particular varaible after it has been declared */
10 |
11 | var name = 'hargun';
12 | /*
13 | var variableName = value;
14 | a string in modern javascript can be contained within single quotes(''), double quotes("") and backticks(``)
15 | what is the difference between using each of them:
16 | the only difference is that when you are using a particular symbol to represent a string, you can use another type of symbol inside the string
17 | for example you are using backticks(``) to represent a string, then you can use '' and "" inside the string
18 | for example you are using "" to represent a string then you can use `` and '' inside the string but you cannot using "" inside the string as it will return an error
19 | it is a common pratice in modern javascript to use `` to contain strings as backticks are rarely used in the formation of string, and also you can use '' and "" in the strings when you use `` to contain the strings
20 |
21 | these all symbols represent strings
22 | a string is a value made up of alphanumerics(digits, symbols and alphabets)
23 | */
24 |
25 | var channel;
26 | /* var nameOfVariable;
27 | here we are just initializing the variable and not assigning it any value
28 | we are just telling the interpreter to reserve the space and memory for the variable and not assign it any value
29 | it is just like buying a bottle and not storing anything in it
30 | */
31 |
32 | channel = 'Simplest Tech';
33 | // existingVariable = value
34 | // here we are assigning a value to an already existing variable
35 | // it is just like using an already bought bottle to store something
36 |
37 | var marks = 42;
38 | /* here we are asigining an integer value to marks variable
39 | you can also write 42 as a string instead of a number but that comes with its own advantages and disadvantages: as u will not be able to perform arithmetic operators on strings, whereas you can perform arithmetic operators on numbers
40 | a number cannot contain alphabets
41 | var number= 3463fs;
42 | it will throw you an error as this is not a valid number as it contains alphabets */
43 |
44 | marks = 0;
45 | // variableName = newValue;
46 | // we can change the value of a variable like this
47 |
48 | console.log(name, channel, marks);
49 | // if a variable has no value it will print `undefined` as it has no value
50 | // you will notice that an integer value is printed in blueish color in the color representing a number, it will appear normally if it is a string
51 |
52 | // comma(,) is used as a concatinator and is used for concationation of values, it adds a space between values, when it is used
53 | // more about concatination in further tutorials
54 |
55 | /* Rules for creating javascript variables:
56 | 1. Cannot start with numbers
57 | 2. Can start with letter, number, _ or $
58 | 3. Variable names are case sensitive
59 | */
60 |
61 | var city = 'Delhi';
62 | // if you use some other symbol like ^ the variable will not be valid and the interpreter will throw you an error
63 | // you can use $ and _ in variable names, but you should always avoid them as they create confusion, though it would be correct syntax
64 | // _ and $ create confusion because _ is used in variable names to represent private variable in object oriented javascript and $ is used in frameworks like jquery
65 | console.log(city);
66 |
67 | // with the arrival of modern javascript, let and const are used more than var
68 | // they improve code readability a lot
69 | const ownerName = "Hari Ram";
70 | // ownerName= "hargun";
71 | // we cannot change the value of const
72 | // const is used in making variables which could not be changed
73 | console.log(ownerName);
74 |
75 | const fruit = 'Orange';
76 | // const fruit;
77 | // we cannot just declare a const, we need to give it a value
78 |
79 | // const has a block scope
80 | // const has a global scope if declared at the root. as it then assumes the root as its block
81 |
82 | // LET
83 | // let has block level scope where as var has global scope
84 | // block can be inside loops and conditionals, etc.
85 | {
86 | let city = "Seoul";
87 | // this will only keep Seoul as the city for only this block as let has a block scope
88 |
89 | // let, just like const, has a global scope if declared at the root(not inside any block) - it just assumes the whole document as the block
90 |
91 | city = "Texas"
92 | // if there is no let variable in the block it will change the global variable
93 |
94 | console.log(city);
95 | }
96 | console.log(city);
97 | // it will print the global variable
98 |
99 | const arr1 = [1,232,35,12];
100 | // an array is defined within [], it is a collection of values
101 |
102 | arr1.push(46);
103 | // you can still push values to an array or an object even if it is a constant
104 | // arr1=[2321,23112,232];
105 | // you cannot re-assign it if it is a constant
106 |
107 | console.log(arr1);
108 |
109 | /* Popular programming case types:
110 | 1. camelCase : the first word's first letter is small and all other word's first letters' are capital
111 | 2. kebab-case : two words are separated by -
112 | 3. snake_case : two words are separatated by _
113 | 4. PascalCase : each word's first letter is capital
114 | */
--------------------------------------------------------------------------------
/webCrawler1-13/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Web Crawler 1 in JavaScript
8 |
9 |
10 |
11 |
Web Crawler Exercise 1 in JavaScript
12 | Learn javascript
13 | Learn good javascript
14 | Go to Google
15 | Go to YouTube
16 |
17 |
--------------------------------------------------------------------------------
/webCrawler1-13/webCrawler1-13.js:
--------------------------------------------------------------------------------
1 | console.log('Web Crawler Exercise 1 in JavaScript');
2 | /*
3 | Exercise 1
4 | Scrape all the links which contain a particular text
5 | */
6 | Array.from(document.links).forEach(function(link){
7 | if(link.innerText.includes("javascript")){
8 | console.log(link.href);
9 | }
10 | });
11 | // if an anchor tag contains the word javascritpt as text, it returns the link of the anchor tag
--------------------------------------------------------------------------------