├── .all-contributorsrc
├── .github
└── FUNDING.yml
├── LICENSE
├── README.md
├── arrays
├── 01-arrayFromRange.js
├── 02-includes.js
├── 03-except.js
├── 04-move.js
├── 05-countOccurrences.js
├── 06-max.js
├── 07-addToArray.js
├── 08-findingElements.js
├── 09-arrowFunctions.js
├── 10-removeFromArray.js
├── 11-emptyAnArray.js
├── 12-combiningSlicingArrays.js
├── 13-spreadOperator.js
├── 14-iteratingArray.js
├── 15-joiningArrays.js
├── 16-urlSlug.js
├── 17-sortingArrays.js
├── 18-everyAndSome.js
├── 19-filterArray.js
├── 20-mapArray.js
├── 21-reduceArrays.js
├── 22-tally.js
├── 23-findColors.js
├── 24-nairaDollarConverter.js
├── 25-movies.js
├── 26-loopFind.js
└── 27-convertArrayLikeObject.js
├── control-flow
├── 01-max.js
├── 02-landscape.js
├── 03-fizzBuzz.js
├── 05-evenOrOdd.js
├── 06-countTruthy.js
├── 07-stringProperties.js
├── 08-multiples.js
├── 09-grade.js
├── 10-stars.js
├── 11-primeNumber.js
├── 12-checkUser.js
├── 13-oddNumbers.js
├── 14-loopObjects.js
├── 15-loopArrays.js
├── 16-movieControl.js
├── 17-getWeekDay.js
└── 18-arrangeObjects.js
├── crud-operations
└── fetch.js
├── dom
├── 01-introDom.js
├── 02-documentObject.js
├── 03-domElements.js
├── 04-domHtml.js
├── 05-domCss.js
├── 06-domAnimation.js
├── 07-domEvents.js
├── 08-eventsListener.js
├── 09-domNavigation.js
├── 10-domNodes.js
├── 11-domCollections.js
├── app.css
├── index.html
└── index.js
├── functions
├── 01-sumOfArgs.js
├── 02-areaOfCircle.js
├── 03-errorHandling.js
├── 04-checkMaxNumber.js
├── 05-showStars.js
├── 06-promises.js
├── 07-generators.js
├── 08-mapsAndWeakMaps.js
├── es6Modules
│ ├── index.html
│ ├── index.js
│ └── math.js
└── math
│ ├── addition.js
│ ├── division.js
│ ├── modulus.js
│ ├── multiplication.js
│ └── subtraction.js
├── index.html
├── index.js
├── objects
├── 01-maxOfTwo.js
├── 02-landscape.js
├── 03-fizzBuzz.js
├── 04-checkSpeed.js
├── 05-showNumbers.js
├── 06-countTruthy.js
├── 07-showProperties.js
├── 08-sum.js
├── 09-grade.js
├── 10-showPrimes.js
├── 11-methodsInObjects.js
├── 12-factoryFunctions.js
├── 13-constructorFunctions.js
├── 14-constructorVsFactory.js
├── 15-dynamicObjects.js
├── 16-callFunctions.js
├── 17-applyFunctions.js
├── 18-objectsProperties.js
├── 19-cloneObject.js
├── 20-typeOfStrings.js
├── 21-templateLiterals.js
├── 22-dateObject.js
├── 23-addressObject.js
├── 24-objectEquality.js
├── 25-blogPost.js
├── 26-blogSetup.js
├── 27-priceRange.js
├── 28-paramObjectDestructure.js
└── 29-restParameter.js
└── operators
├── conversion.js
├── swap.js
└── tenary.js
/.all-contributorsrc:
--------------------------------------------------------------------------------
1 | {
2 | "files": [
3 | "README.md"
4 | ],
5 | "imageSize": 100,
6 | "commit": false,
7 | "contributors": [
8 | {
9 | "login": "BolajiAyodeji",
10 | "name": "Bolaji Ayodeji",
11 | "avatar_url": "https://avatars2.githubusercontent.com/u/30334776?v=4",
12 | "profile": "https://bolajiayodeji.com",
13 | "contributions": [
14 | "code"
15 | ]
16 | },
17 | {
18 | "login": "mikeattara",
19 | "name": "Mike Perry Y Attara",
20 | "avatar_url": "https://avatars1.githubusercontent.com/u/31483629?v=4",
21 | "profile": "https://blog.mikeattara.com",
22 | "contributions": [
23 | "code"
24 | ]
25 | },
26 | {
27 | "login": "1baga",
28 | "name": "Umar Mash",
29 | "avatar_url": "https://avatars2.githubusercontent.com/u/4129853?v=4",
30 | "profile": "https://github.com/1baga",
31 | "contributions": [
32 | "code"
33 | ]
34 | },
35 | {
36 | "login": "Edmund1645",
37 | "name": "Edmund Ekott",
38 | "avatar_url": "https://avatars1.githubusercontent.com/u/34253790?v=4",
39 | "profile": "http://www.edmundekott.me",
40 | "contributions": [
41 | "code"
42 | ]
43 | },
44 | {
45 | "login": "Eronmmer",
46 | "name": "Erons",
47 | "avatar_url": "https://avatars0.githubusercontent.com/u/37238033?v=4",
48 | "profile": "http://erons.me",
49 | "contributions": [
50 | "code"
51 | ]
52 | },
53 | {
54 | "login": "Henry-Asante",
55 | "name": "Henry Asante",
56 | "avatar_url": "https://avatars1.githubusercontent.com/u/30865594?v=4",
57 | "profile": "http://henryasante.ml",
58 | "contributions": [
59 | "code"
60 | ]
61 | }
62 | ],
63 | "contributorsPerLine": 7,
64 | "projectName": "js-code-snippets",
65 | "projectOwner": "BolajiAyodeji",
66 | "repoType": "github",
67 | "repoHost": "https://github.com"
68 | }
69 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | patreon: bolajiayodeji
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 Bolaji Ayodeji
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | [](#contributors)
4 |
5 | # JAVASCRIPT CODE SNIPPETS
6 |
7 | [](http://makeapullrequest.com)
8 | [](http://www.firsttimersonly.com/)
9 | [](https://www.codetriage.com/bolajiayodeji/js-code-snippets)
10 |
11 | Learn basic JavaScript concepts in action. :zap:
12 | For beginners and intermediates!
13 |
14 |
15 |
16 | ## Contributors Guide
17 |
18 | - If you are new to Git and Github, it is advisable you go through
19 | [GitHub For Beginners](http://readwrite.com/2013/09/30/understanding-github-a-journey-for-beginners-part-1/)
20 | before moving to the next step.
21 |
22 | - Fork the Repository [here](https://github.com/BolajiAyodeji/js-code-snippets/fork)
23 |
24 | - Clone the forked Repository
25 | ```git
26 | $ git clone https://github.com/BolajiAyodeji/js-code-snippets.git
27 | ```
28 | - Enter the cloned directory
29 | ```git
30 | cd js-code-snippets
31 | ```
32 |
33 | - Open directory in your Code Editor
34 | ```git
35 | code .
36 | ```
37 |
38 | - Add new snippets!
39 | Ensure to add each snippets in the expected folder directory.
40 | If possible, try to show multiples ways of solving the same problem from the less efficient to the most efficient algorithm.
41 |
42 | - Push your files
43 | ```git
44 | $ git add --all
45 | $ git commit -m "commit description here"
46 | $ git push -u origin master
47 | ```
48 | - To keep your fork up to date with the original
49 | ```git
50 | $ git add remote upstream https://github.com/BolajiAyodeji/js-code-snippets.git
51 | $ git fetch upstream
52 | $ git merge upstream/master
53 | ```
54 | - Open a Pull Request ( [What is a pull request?](https://yangsu.github.io/pull-request-tutorial/) )
55 | - Add enough description of what you did, changes you made and if possible screenshots
56 | - Wait for Review (Your PR would be reviewed and merged if deemed fit)
57 |
58 | ## Reference
59 | [CodeWithMosh JavaScript for Beginners Course](https://codewithmosh.com/courses/324741)
60 |
61 | ## Author
62 | [Bolaji Ayodeji](https://github.com/BolajiAyodeji)
63 |
64 | ## Licence
65 | [MIT](https://opensource.org/licenses/MIT)
66 |
67 | ## Contributors
68 |
69 | Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
70 |
71 |
72 |
73 |
83 |
84 |
85 |
--------------------------------------------------------------------------------
/arrays/01-arrayFromRange.js:
--------------------------------------------------------------------------------
1 | const arrayFromRange = function arrayFromRange (min, max) {
2 | const output = [];
3 | for (let i = min; i <= max; i++)
4 | output.push(i);
5 | return output;
6 | }
7 |
8 | console.log(arrayFromRange(1, 100));
9 |
--------------------------------------------------------------------------------
/arrays/02-includes.js:
--------------------------------------------------------------------------------
1 | const array = [1, 3, 4, 6]
2 | function includes(array, searchElement) {
3 | for(let element of array)
4 | if (element === searchElement)
5 | return true;
6 | return false;
7 | }
8 |
9 | console.log(includes(array, 4));
10 |
--------------------------------------------------------------------------------
/arrays/03-except.js:
--------------------------------------------------------------------------------
1 | const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2 |
3 | function except(array, excluded) {
4 | const output = [];
5 | for (let number of array)
6 | if(!excluded.includes(number))
7 | output.push(number);
8 | console.log(output);
9 | }
10 |
11 | except(numbers, [1, 4, 8, 3, 10]);
12 |
--------------------------------------------------------------------------------
/arrays/04-move.js:
--------------------------------------------------------------------------------
1 | const numbers = [1, 2, 3, 4, 5];
2 |
3 | function move(array, index, offset) {
4 | const position = index + offset;
5 | if (position >= array.length || position < 0) {
6 | console.error('Invalid offset.');
7 | return;
8 | }
9 | else {
10 | const output = [...array];
11 | const number = output.splice(index, 1)[0];
12 | output.splice(position, 0, number);
13 | return output
14 | }
15 | }
16 |
17 | console.log(move(numbers, 1, -1));
18 |
--------------------------------------------------------------------------------
/arrays/05-countOccurrences.js:
--------------------------------------------------------------------------------
1 | const numbers = [1, 2, 3, 4];
2 |
3 | const count = countOccurrences(numbers, 1);
4 |
5 | console.log(count);
6 |
7 | function countOccurrences(array, searchElement) {
8 | // let count = 0;
9 | // for (let element of array)
10 | // if (element === searchElement)
11 | // count++;
12 | // return count;
13 |
14 | return array.reduce((accumulator, current) => {
15 | const occurrence = (current === searchElement) ? 1 : 0;
16 | console.log(accumulator, current, searchElement);
17 | return accumulator + occurrence;
18 | }, 0);
19 | }
20 |
--------------------------------------------------------------------------------
/arrays/06-max.js:
--------------------------------------------------------------------------------
1 | const numbers = [1, 2, 3, 4];
2 |
3 | const max = getMax([]);
4 |
5 | console.log(max);
6 |
7 | function getMax(array) {
8 | if (array.length === 0) return undefined;
9 |
10 | // let max = array[0];
11 |
12 | // for (let i = 1; i < array.length; i++)
13 | // if (array[i] > max)
14 | // max = array[i];
15 |
16 | // return max;
17 |
18 | return array.reduce((a, b) => (a > b) ? a : b);
19 | }
20 |
--------------------------------------------------------------------------------
/arrays/07-addToArray.js:
--------------------------------------------------------------------------------
1 | const numbers = [4, 5];
2 | console.log(numbers);
3 |
4 | // Add to end
5 | numbers.push(9, 10, 11);
6 |
7 | // Add to start
8 | numbers.unshift(1, 2, 3)
9 |
10 | // Add to middle
11 | numbers.splice(5, 0, 6, 7, 8);
12 |
--------------------------------------------------------------------------------
/arrays/08-findingElements.js:
--------------------------------------------------------------------------------
1 | // Finding elements in an array
2 |
3 | // Primitives
4 | const numbers = [1, 2, 3, 4, 1];
5 |
6 | console.log(numbers.indexOf('a')); // Would return -1 because 'a' does not exist in the array
7 | console.log(numbers.indexOf(2, 0)); // Would return 1 because 2 exists in the array
8 | console.log(numbers.lastIndexOf(1)); // Would return the last index of 1 in the array which is 4
9 |
10 | console.log(numbers.indexOf(1) !== -1); // returns true
11 |
12 | // A better way
13 | console.log(numbers.includes(1)); // returns true
14 |
15 | // Reference types
16 | const courses = [
17 | {id: 1, name: 'maths'},
18 | {id: 2, name: 'english'},
19 | ];
20 |
21 | const course = courses.find(function (course) {
22 | return course.name === 'maths';
23 | });
24 |
25 | const index = courses.findIndex(function (course) {
26 | return course.name === 'maths';
27 | });
28 |
29 | console.log(course, index);
30 |
--------------------------------------------------------------------------------
/arrays/09-arrowFunctions.js:
--------------------------------------------------------------------------------
1 | // syntax
2 | (param1, param2, …, paramN) => { statements }
3 | (param1, param2, …, paramN) => expression
4 | // equivalent to: => { return expression; }
5 |
6 | // Parentheses are optional when there's only one parameter name:
7 | (singleParam) => { statements }
8 | singleParam => { statements }
9 |
10 | // The parameter list for a function with no parameters should be written with a pair of parentheses.
11 | () => { statements }
12 |
13 | // sample arrow function
14 | const courses = [
15 | {id: 1, name: 'maths'},
16 | {id: 2, name: 'english'},
17 | ];
18 |
19 | const course = courses.find((course) => course.name === 'maths');
20 |
21 | console.log(course);
22 |
--------------------------------------------------------------------------------
/arrays/10-removeFromArray.js:
--------------------------------------------------------------------------------
1 | const numbers = [1, 2, 3, 4];
2 | console.log(numbers);
3 |
4 | // remove from end
5 | const last = numbers.pop();
6 |
7 | // remove from start
8 | const first = numbers.shift();
9 |
10 | // remove middle
11 | numbers.splice(3, 2);
12 | console.log(numbers);
13 |
--------------------------------------------------------------------------------
/arrays/11-emptyAnArray.js:
--------------------------------------------------------------------------------
1 | let numbers = [1, 2, 3, 4];
2 | let another = numbers;
3 |
4 | // solution 1
5 | numbers = [];
6 |
7 | // solution 2
8 | numbers.length = 0; // most preferred method
9 |
10 | // solution 3
11 | numbers.splice(0, numbers.length);
12 |
13 | // solution 4
14 | while(numbers.length > 0) {
15 | numbers.pop();
16 | }
17 |
18 | // solution 5
19 | while(numbers.length > 0) {
20 | numbers.shift();
21 | }
22 |
23 |
24 | console.log(numbers);
25 |
--------------------------------------------------------------------------------
/arrays/12-combiningSlicingArrays.js:
--------------------------------------------------------------------------------
1 | // combining arrays
2 | const first = [1, 2, 3];
3 | const second = [4, 5, 6];
4 | const third = [{id: 1, nama: 'a'}];
5 |
6 | const merged = first.concat(second, third);
7 | console.log(merged);
8 |
9 | // slice arrays
10 | const slice = merged.slice(0, 3);
11 | console.log(slice);
12 |
--------------------------------------------------------------------------------
/arrays/13-spreadOperator.js:
--------------------------------------------------------------------------------
1 | // combining arrays
2 | const first = [1, 2, 3];
3 | const second = [4, 5, 6];
4 |
5 | // const merged = first.concat(second);
6 | const merged = [...first, ...second];
7 | console.log(merged);
8 |
9 | // you can add another element
10 | const merged2 = [...first, 'chill',...second, 'done'];
11 | console.log(merged2);
12 |
13 | // const copy = merged.slice();
14 | const copy = [...merged];
15 | console.log(copy);
16 |
--------------------------------------------------------------------------------
/arrays/14-iteratingArray.js:
--------------------------------------------------------------------------------
1 | const numbers = [1, 2 , 3];
2 |
3 | // for of method
4 | for (let number of numbers) {
5 | console.log(number);
6 | }
7 |
8 | // for each method
9 | numbers.forEach((number, index) => console.log(index, number));
10 |
--------------------------------------------------------------------------------
/arrays/15-joiningArrays.js:
--------------------------------------------------------------------------------
1 | const numbers = [1, 2, 3];
2 | const joined = numbers.join(',');
3 | console.log(joined);
4 |
5 | // This method is for strings
6 | const message = 'this is my first message!'
7 | const split = message.split(' ');
8 | console.log(split);
9 |
10 | console.log(split.join('-'));
11 |
--------------------------------------------------------------------------------
/arrays/16-urlSlug.js:
--------------------------------------------------------------------------------
1 | const url = 'https://bolajiayodeji.com/'
2 | const urlSlug = (postTitle, category) => {
3 | let postUrl = postTitle.toLowerCase().split(' ');
4 | let postSlug = `${url}` + category + '/' + postUrl.join('-');
5 | return postSlug;
6 | }
7 | let postTitle = 'Introduction to Chrome Lighthouse'
8 | let category = 'dt'
9 | console.log(urlSlug(postTitle, category));
10 |
11 | // https://bolajiayodeji.com/dt/introduction-to-chrome-lighthouse
12 |
--------------------------------------------------------------------------------
/arrays/17-sortingArrays.js:
--------------------------------------------------------------------------------
1 | const numbers = [2, 4, 1, 3];
2 |
3 | let sorted = numbers.sort();
4 | console.log(sorted);
5 |
6 | let reversed = numbers.reverse();
7 | console.log(reversed);
8 |
9 | // Sorting arrays with objects
10 | const courses = [
11 | {id: 1, name: 'React.js'},
12 | {id: 2, name: 'Node.js'},
13 | ]
14 |
15 |
16 | courses.sort((a, b) =>{
17 | // a < b => -1
18 | // a > b => 1
19 | // a =b => 0
20 | const nameA = a.name.toLowerCase();
21 | const nameB = b.name.toLowerCase();
22 |
23 | if (nameA < nameB) {
24 | return -1
25 | }
26 | if (nameB > nameA) {
27 | return 1
28 | }
29 | return 0;
30 | })
31 |
32 | console.log(courses);
33 |
--------------------------------------------------------------------------------
/arrays/18-everyAndSome.js:
--------------------------------------------------------------------------------
1 | const numbers = [1, -1, 2, 3];
2 |
3 | // checks if all numbers are positive
4 | let allPositive = numbers.every(function(value) {
5 | return value >= 0;
6 | })
7 | console.log(allPositive); // would return false
8 |
9 | // checks if at least one number is positive
10 | let atLeastOnePositive = numbers.some(function(value) {
11 | return value >= 0;
12 | })
13 | console.log(atLeastOnePositive); // would return true
14 |
--------------------------------------------------------------------------------
/arrays/19-filterArray.js:
--------------------------------------------------------------------------------
1 | const numbers = [-1, 2, 3, -4, 'hello'];
2 |
3 | const filtered = numbers.filter(n => {
4 | return n >= 0;
5 | })
6 | console.log(filtered);
7 |
--------------------------------------------------------------------------------
/arrays/20-mapArray.js:
--------------------------------------------------------------------------------
1 | const numbers = [-1, 2, 6, 8, 12, 20, 99, 3, -4, 'hello'];
2 |
3 | const filtered = numbers.filter(n => n >= 0);
4 |
5 | const items = filtered.map(n => {
6 | return '' + n + '';
7 | })
8 |
9 | const html = '';
10 | document.write(html);
11 |
12 | // map to object
13 | const filteredObj = filtered.map(n => ({value: n}));
14 |
15 | console.log(filteredObj);
16 |
17 |
--------------------------------------------------------------------------------
/arrays/21-reduceArrays.js:
--------------------------------------------------------------------------------
1 | const numbers = [100, 300, 500, 70];
2 |
3 | // let sum = 0;
4 | // for (let n of numbers) {
5 | // sum += n;
6 | // }
7 | // console.log(sum);
8 |
9 | // reduce method
10 | const sum =numbers.reduce((accummulator, value) => accummulator + value);
11 |
12 | console.log(sum);
13 |
14 | // Find average
15 | const euros = [10, 20, 20, 10];
16 | const average = euros.reduce((total, amount, index, array) => {
17 | const sum = total += amount;
18 | console.log(sum);
19 | if( index === array.length-1) {
20 | return sum/array.length;
21 | }else {
22 | return total;
23 | }
24 | });
25 | console.log(average); // 39.37
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/arrays/22-tally.js:
--------------------------------------------------------------------------------
1 | const fruitBasket = ['banana', 'cherry', 'orange', 'apple', 'cherry', 'orange', 'apple', 'banana', 'cherry', 'orange', 'fig' ];
2 | const count = fruitBasket.reduce( (tally, fruit) => {
3 | tally[fruit] = (tally[fruit] || 0) + 1 ;
4 | return tally;
5 | } , {})
6 | console.log(count); // { banana: 2, cherry: 3, orange: 3, apple: 2, fig: 1 }
7 |
--------------------------------------------------------------------------------
/arrays/23-findColors.js:
--------------------------------------------------------------------------------
1 | const data = [
2 | {a: 'happy', b: 'robin', c: ['blue','green']},
3 | {a: 'tired', b: 'panther', c: ['green','black','orange','blue']},
4 | {a: 'sad', b: 'goldfish', c: ['green','red']}
5 | ];
6 |
7 | const colors = data.reduce((total, amount) => {
8 | amount.c.forEach( color => {
9 | total.push(color);
10 | })
11 | return total;
12 | }, [])
13 | colors //['blue','green','green','black','orange','blue','green','red']
14 |
--------------------------------------------------------------------------------
/arrays/24-nairaDollarConverter.js:
--------------------------------------------------------------------------------
1 | const dollars = [50, 150, 250];
2 | const naira = [1000, 500, 200];
3 |
4 | const toNaira = dollars.map(eachAmount => '₦' + eachAmount * 361.50);
5 | const toDollar = naira.map(eachAmount => '$' + eachAmount *0.0028);
6 |
7 | //361.50 was the exchange rate on google on 5th Feb 2019
8 | //0.0028 was the exchange rate on google on 5th Feb 2019
9 |
10 | console.log(toNaira);
11 | console.log(toDollar);
12 |
--------------------------------------------------------------------------------
/arrays/25-movies.js:
--------------------------------------------------------------------------------
1 | const movies = [
2 | {title: 'a', year: 2018, rating: 4.5},
3 | {title: 'b', year: 2018, rating: 4.7},
4 | {title: 'c', year: 2018, rating: 3},
5 | {title: 'd', year: 2017, rating: 4.5}
6 | ]
7 |
8 | // All movies in 2018 with rating > 4
9 | // sort them by their rating
10 | // descending order
11 | // pick their title
12 |
13 | const titles = movies
14 | .filter(m => m.year === 2018 && m.rating >= 4)
15 | .sort((a, b) => a.rating - b.rating)
16 | .reverse()
17 | .map(m => m.title);
18 |
19 | console.log(titles);
20 |
--------------------------------------------------------------------------------
/arrays/26-loopFind.js:
--------------------------------------------------------------------------------
1 | let people = [
2 | {
3 | "firstName": "Skyler",
4 | "lastName": "Carroll",
5 | "phone": "1-429-754-5027",
6 | "email": "Cras.vehicula.alique@diamProin.ca",
7 | "address": "P.O. Box 171, 1135 Feugiat St."
8 | },
9 | {
10 | "firstName": "Kylynn",
11 | "lastName": "Madden",
12 | "phone": "1-637-627-2810",
13 | "email": "mollis.Duis@ante.co.uk",
14 | "address": "993-6353 Aliquet, Street"
15 | },
16 | ]
17 |
18 | people.forEach(({firstName})=> console.log(firstName))
19 |
--------------------------------------------------------------------------------
/arrays/27-convertArrayLikeObject.js:
--------------------------------------------------------------------------------
1 | const products =
2 | Array.from(document.querySelectorAll('.product'));
3 |
4 | products
5 | .filter(product => parseFloat(product.innerHTML) < 10)
6 | .forEach(product => product.style.color = 'red');
7 |
8 | console.log(products);
9 |
--------------------------------------------------------------------------------
/control-flow/01-max.js:
--------------------------------------------------------------------------------
1 | let number = max(5, 3);
2 | console.log(number);
3 |
4 | function max(a, b) {
5 | return (a > b) ? a : b;
6 | }
7 |
--------------------------------------------------------------------------------
/control-flow/02-landscape.js:
--------------------------------------------------------------------------------
1 | function isLandscape (width, height) {
2 | return (width > height);
3 | }
4 | console.log((isLandscape(200, 300)));
5 |
--------------------------------------------------------------------------------
/control-flow/03-fizzBuzz.js:
--------------------------------------------------------------------------------
1 | //FizzBuzz
2 | //If number is divisible by 3 ==> Fizz
3 | //If number is divisible by 5 ==> Buzz
4 | //If number is divisible by 3 and 5 ==> FizzBuzz
5 | //If number is not divisible by 3 or 5 ==> Number
6 | //If input is not a number ==> Not a number!
7 |
8 | let fizzBuzz = function (input) {
9 | if (typeof input !== 'number')
10 | return 'Not a number!';
11 |
12 | if ((input % 3 === 0) && (input % 5 === 0))
13 | return 'FizzBuzz';
14 |
15 | if (input % 3 === 0)
16 | return 'Fizz';
17 |
18 | if (input % 5 === 0)
19 | return 'Buzz';
20 |
21 | if (input % 3 !== 0 && input % 5 !== 0)
22 | return input;
23 |
24 | return input;
25 | }
26 |
27 | try {
28 | let output = fizzBuzz(Hello);
29 | console.log(output);
30 | } catch (e) {
31 | if (e instanceof ReferenceError) {
32 | console.log("Not a number!")
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/control-flow/05-evenOrOdd.js:
--------------------------------------------------------------------------------
1 | showNumbers(10);
2 |
3 | function showNumbers(limit) {
4 | for (let i = 0; i <= limit; i++) {
5 | const message = (i % 2 === 0) ? 'EVEN' : 'ODD';
6 | console.log(i, message);
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/control-flow/06-countTruthy.js:
--------------------------------------------------------------------------------
1 | // count number of Truthy and Falsy values in an Array
2 | // Returns number of Truthy values in the array
3 | // List of Falsy values
4 | // - undefined
5 | // - null
6 | // - ''
7 | // - false
8 | // - 0
9 | // - NaN
10 |
11 | function countTruthy(array) {
12 | let count = 0;
13 | for (let value of array)
14 | if (value)
15 | count++;
16 | return count;
17 | }
18 | console.log(countTruthy([1, 2, 3]));
19 |
--------------------------------------------------------------------------------
/control-flow/07-stringProperties.js:
--------------------------------------------------------------------------------
1 | // count number of strings in an Object
2 | // return strings in the object
3 |
4 | function showProperties(obj) {
5 | let count = 0;
6 | for (let value in obj) {
7 | if (typeof obj[value] === 'string')
8 | console.log(value + '==>' + obj[value])
9 | }
10 | }
11 | const userData = {
12 | name: 'Bolaji',
13 | gender: 'male',
14 | age: 19,
15 | telNumber: 08109445504,
16 | email: 'hi@bolajiayodeji.com',
17 | mood: 'happy',
18 | magicNumber: 5
19 | }
20 | console.log(showProperties(userData));
21 |
--------------------------------------------------------------------------------
/control-flow/08-multiples.js:
--------------------------------------------------------------------------------
1 | // Return the sum of the multiples of 3 and 5 which is < limit
2 |
3 | function sum(limit) {
4 | let sum = 0;
5 |
6 | for (let i = 0; i <= limit; i++)
7 | if (i % 3 === 0 || i % 5 === 0)
8 | sum += i;
9 |
10 | return sum;
11 | }
12 | console.log(sum(10));
13 |
--------------------------------------------------------------------------------
/control-flow/09-grade.js:
--------------------------------------------------------------------------------
1 | // Calculate the average of the marks
2 | // 0 - 59 ==> Fail
3 | // 60 - 69 ==> Pass
4 | // 70 - 79 ==> Good
5 | // 80 - 89 ==> Very Good
6 | // 90 - 100 ==> Excellent
7 |
8 | function calculateAverage(array) {
9 | let sum = 0;
10 | for (let value of array)
11 | sum += value;
12 | return sum / array.length;
13 | }
14 |
15 | function calculateGrade(marks) {
16 | const average = calculateAverage(marks);
17 | if (average < 60) return 'Fail';
18 | if (average < 70) return 'Pass';
19 | if (average < 80) return 'Good';
20 | if (average < 90) return 'Very Good';
21 | return 'Excellent';
22 | }
23 | const marks = [40, 57, 90];
24 | console.log(calculateGrade(marks));
25 |
--------------------------------------------------------------------------------
/control-flow/10-stars.js:
--------------------------------------------------------------------------------
1 | // Loop stars per row
2 | // Increment star +1 per row
3 |
4 | function showStars(rows) {
5 | for (let row = 1; row <= rows; row++) {
6 | let pattern = '';
7 | for (let i = 0; i < row; i++)
8 | pattern += '*';
9 | console.log(pattern);
10 | }
11 | }
12 | showStars(50);
13 |
--------------------------------------------------------------------------------
/control-flow/11-primeNumber.js:
--------------------------------------------------------------------------------
1 | showPrimes(19);
2 |
3 | function isPrime(number) {
4 | for (let factor = 2; factor < number; factor++)
5 | if (number % factor === 0)
6 | return false;
7 |
8 | return true;
9 | }
10 |
11 | function showPrimes(limit) {
12 | for (let number = 2; number <= limit; number++)
13 | if (isPrime(number)) console.log(number);
14 | }
15 |
--------------------------------------------------------------------------------
/control-flow/12-checkUser.js:
--------------------------------------------------------------------------------
1 | let role = 'admin';
2 |
3 | switch (role) {
4 | case 'guest':
5 | console.log('Guest User');
6 | break;
7 | case 'admin':
8 | console.log('Administrator');
9 | break;
10 | case 'mod':
11 | console.log('Moderator');
12 | break;
13 | default:
14 | console.log('Unknown User');
15 | }
16 |
--------------------------------------------------------------------------------
/control-flow/13-oddNumbers.js:
--------------------------------------------------------------------------------
1 | //Log ODD numbers between 0 and 20
2 |
3 | //forLoop
4 | for (let i = 0; i <= 20; i++;) {
5 | if (i % 2 !== 0)console.log(i);
6 | }
7 |
8 | //whileLoop
9 | let i = 0;
10 | while (i <=20) {
11 | if (i % 2 !== 0)console.log(i);
12 | i++;
13 | }
14 |
15 | //do-whileLoop
16 | let i = 0;
17 | do {
18 | if (i % 2 !== 0)console.log(i);
19 | i++;
20 | } while (i <=20);
21 |
22 | //Note:
23 | //When running this file once with all the loops,
24 | //remember to change the variable name of the "do-whileLoop" from 'i' to something else
25 | //You can't declare two variables with the same name using 'let'
26 | //You will get an error
27 |
--------------------------------------------------------------------------------
/control-flow/14-loopObjects.js:
--------------------------------------------------------------------------------
1 | const person = {
2 | lastName: ': ' + 'bolaji',
3 | firstName: ': ' +'ayodeji',
4 | age: ': ' + 19,
5 | gender: ': ' + 'male',
6 | status: ': ' + 'single',
7 | beards: ': ' +'NO',
8 | skinColor: ': ' + 'dark'
9 | }
10 |
11 | for (index in person)
12 | console.log(index, person[index]);
13 |
--------------------------------------------------------------------------------
/control-flow/15-loopArrays.js:
--------------------------------------------------------------------------------
1 | //for-in method
2 | const colors = ['red', 'green', 'blue', 'purple', 'orange', 'white', 'black']
3 |
4 | for (let item in colors)
5 | console.log(colors[item]);
6 |
7 | //for-of method (es6 standard!!)
8 | for (let item of colors)
9 | console.log(item);
10 |
--------------------------------------------------------------------------------
/control-flow/16-movieControl.js:
--------------------------------------------------------------------------------
1 | switch (movie) {
2 | case 'play':
3 | playMovie();
4 | break;
5 | case 'pause':
6 | pauseMovie();
7 | break;
8 | default:
9 | doNothing();
10 | }
11 |
--------------------------------------------------------------------------------
/control-flow/17-getWeekDay.js:
--------------------------------------------------------------------------------
1 | switch (new Date().getDay()) {
2 | case 0:
3 | day = "Sunday";
4 | break;
5 | case 1:
6 | day = "Monday";
7 | break;
8 | case 2:
9 | day = "Tuesday";
10 | break;
11 | case 3:
12 | day = "Wednesday";
13 | break;
14 | case 4:
15 | day = "Thursday";
16 | break;
17 | case 5:
18 | day = "Friday";
19 | break;
20 | case 6:
21 | day = "Saturday";
22 | }
23 |
--------------------------------------------------------------------------------
/control-flow/18-arrangeObjects.js:
--------------------------------------------------------------------------------
1 | // count number of strings and numbers in an Object
2 | // rearrange and log strings before numbers
3 |
4 | function showProperties(obj) {
5 | let count = 0;
6 |
7 | console.log('-----strings-----');
8 |
9 | for (let value in obj) {
10 | if (typeof obj[value] === 'string')
11 | console.log(value + '==>' + obj[value]);
12 | }
13 |
14 | console.log('-----numbers-----');
15 |
16 | for (let value in obj) {
17 | if (typeof obj[value] === 'number')
18 | console.log(value + '==>' + obj[value]);
19 | }
20 | }
21 | const userData = {
22 | name: 'Bolaji',
23 | gender: 'male',
24 | age: 19,
25 | telNumber: 08109445504,
26 | email: 'hi@bolajiayodeji.com',
27 | mood: 'happy',
28 | magicNumber: 5
29 | }
30 | console.log(showProperties(userData));
31 |
--------------------------------------------------------------------------------
/crud-operations/fetch.js:
--------------------------------------------------------------------------------
1 | // Example POST method implementation: --------------------------------------------------------
2 | postData('http://example.com/answer', {answer: 42})
3 | .then(data => console.log(JSON.stringify(data))) // JSON-string from `response.json()` call
4 | .catch(error => console.error(error));
5 |
6 | function postData(url = '', data = {}) {
7 | // Default options are marked with *
8 | return fetch(url, {
9 | method: 'POST', // *GET, POST, PUT, DELETE, etc.
10 | mode: 'cors', // no-cors, cors, *same-origin
11 | cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
12 | credentials: 'same-origin', // include, *same-origin, omit
13 | headers: {
14 | 'Content-Type': 'application/json',
15 | // 'Content-Type': 'application/x-www-form-urlencoded',
16 | },
17 | redirect: 'follow', // manual, *follow, error
18 | referrer: 'no-referrer', // no-referrer, *client
19 | body: JSON.stringify(data), // body data type must match "Content-Type" header
20 | })
21 | .then(response => response.json()); // parses JSON response into native Javascript objects
22 | }
23 | //-------------------------------------------------------------------------------------------------
24 |
25 |
26 |
27 | // Example POST JSON method implmentation --------------------------------------------------------
28 | var url = 'https://example.com/profile';
29 | var data = {username: 'example'};
30 |
31 | fetch(url, {
32 | method: 'POST', // or 'PUT'
33 | body: JSON.stringify(data), // data can be `string` or {object}!
34 | headers:{
35 | 'Content-Type': 'application/json'
36 | }
37 | }).then(res => res.json())
38 | .then(response => console.log('Success:', JSON.stringify(response)))
39 | .catch(error => console.error('Error:', error));
40 | //-------------------------------------------------------------------------------------------------
41 |
42 |
43 |
44 | // Example POST FILE method implmentation --------------------------------------------------------
45 | var formData = new FormData();
46 | var fileField = document.querySelector('input[type="file"]');
47 |
48 | formData.append('username', 'abc123');
49 | formData.append('avatar', fileField.files[0]);
50 |
51 | fetch('https://example.com/profile/avatar', {
52 | method: 'PUT',
53 | body: formData
54 | })
55 | .then(response => response.json())
56 | .catch(error => console.error('Error:', error))
57 | .then(response => console.log('Success:', JSON.stringify(response)));
58 | //-------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------
/dom/01-introDom.js:
--------------------------------------------------------------------------------
1 | // The HTML DOM (Document Object Model)
2 | // When a web page is loaded, the browser creates a Document Object Model of the page.
3 |
4 | // The HTML DOM model is constructed as a tree of Objects
5 |
6 | // What is the DOM?
7 | // The DOM is a W3C (World Wide Web Consortium) standard.
8 |
9 | // The DOM defines a standard for accessing documents:
10 |
11 | // "The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."
12 |
13 | // The W3C DOM standard is separated into 3 different parts:
14 |
15 | // Core DOM - standard model for all document types
16 | // XML DOM - standard model for XML documents
17 | // HTML DOM - standard model for HTML documents
18 |
19 | // What is the HTML DOM?
20 | // The HTML DOM is a standard object model and programming interface for HTML. It defines:
21 |
22 | // The HTML elements as objects
23 | // The properties of all HTML elements
24 | // The methods to access all HTML elements
25 | // The events for all HTML elements
26 | // In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
27 |
28 | // With the object model, JavaScript gets all the power it needs to create dynamic HTML:
29 |
30 | // JavaScript can change all the HTML elements in the page
31 | // JavaScript can change all the HTML attributes in the page
32 | // JavaScript can change all the CSS styles in the page
33 | // JavaScript can remove existing HTML elements and attributes
34 | // JavaScript can add new HTML elements and attributes
35 | // JavaScript can react to all existing HTML events in the page
36 | // JavaScript can create new HTML events in the page
37 |
38 |
--------------------------------------------------------------------------------
/dom/02-documentObject.js:
--------------------------------------------------------------------------------
1 | // Below are some examples of how you can use the document object to access and manipulate HTML.
2 |
3 | // Finding HTML Elements
4 | document.getElementById(id) // Find an element by element id
5 | document.getElementsByTagName(name) // Find elements by tag name
6 | document.getElementsByClassName(name) // Find elements by class name
7 |
8 | // Changing HTML Elements
9 | element.innerHTML = new htmlContent // Change the inner HTML of an element
10 | element.attribute = new value // Change the attribute value of an HTML element
11 | element.setAttribute(attribute, value) // Change the attribute value of an HTML element
12 | element.style.property = new style // Change the style of an HTML element
13 |
14 | // Adding and Deleting Elements
15 | document.createElement(element) // Create an HTML element
16 | document.removeChild(element) // Remove an HTML element
17 | document.appendChild(element) // Add an HTML element
18 | document.replaceChild(element) // Replace an HTML element
19 | document.write(text) // Write into the HTML output stream
20 |
21 | // Adding Events Handlers
22 | document.getElementById(id).onclick = function(){code} // Adding event handler code to an onclick event
23 |
24 | // Finding HTML Objects
25 |
26 | // The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and properties. These are still valid in HTML5.
27 | // Later, in HTML DOM Level 3, more objects, collections, and properties were added.
28 |
29 | document.anchors // Returns all elements that have a name attribute 1
30 | document.applets // Returns all