├── .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 | [![All Contributors](https://img.shields.io/badge/all_contributors-6-orange.svg?style=flat-square)](#contributors) 4 | 5 | # JAVASCRIPT CODE SNIPPETS 6 | 7 | [![Pull Requests Welcome](https://img.shields.io/badge/PRs-welcome-red.svg?style=flat)](http://makeapullrequest.com) 8 | [![first-timers-only Friendly](https://img.shields.io/badge/first--timers--only-friendly-blue.svg)](http://www.firsttimersonly.com/) 9 | [![Open Source Helpers](https://www.codetriage.com/bolajiayodeji/js-code-snippets/badges/users.svg)](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 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 |
Bolaji Ayodeji
Bolaji Ayodeji

💻
Mike Perry Y Attara
Mike Perry Y Attara

💻
Umar Mash
Umar Mash

💻
Edmund Ekott
Edmund Ekott

💻
Erons
Erons

💻
Henry Asante
Henry Asante

💻
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 elements (Deprecated in HTML5) 1 31 | document.baseURI // Returns the absolute base URI of the document 3 32 | document.body // Returns the element 1 33 | document.cookie // Returns the document's cookie 1 34 | document.doctype // Returns the document's doctype 3 35 | document.documentElement // Returns the element 3 36 | document.documentMode // Returns the mode used by the browser 3 37 | document.documentURI // Returns the URI of the document 3 38 | document.domain // Returns the domain name of the document server 1 39 | document.domConfig // Obsolete. Returns the DOM configuration 3 40 | document.embeds // Returns all elements 3 41 | document.forms // Returns all
    elements 1 42 | document.head // Returns the element 3 43 | document.images // Returns all elements 1 44 | document.implementation // Returns the DOM implementation 3 45 | document.inputEncoding // Returns the document's encoding (character set) 3 46 | document.lastModified // Returns the date and time the document was updated 3 47 | document.links // Returns all and elements that have a href attribute 1 48 | document.readyState // Returns the (loading) status of the document 3 49 | document.referrer // Returns the URI of the referrer (the linking document) 1 50 | document.scripts // Returns all 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /dom/index.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BolajiAyodeji/js-code-snippets/b23d54e6aa02d6e9956b65f8f54eab4af7ad60b5/dom/index.js -------------------------------------------------------------------------------- /functions/01-sumOfArgs.js: -------------------------------------------------------------------------------- 1 | 2 | function sum(...nums) { 3 | if (nums.length === 1 && Array.isArray(nums[0])) { 4 | nums = [...nums[0]]; 5 | } 6 | return nums.reduce((a, b) => a + b); 7 | } 8 | 9 | console.log(sum([1, 2, 3, 4])); 10 | 11 | -------------------------------------------------------------------------------- /functions/02-areaOfCircle.js: -------------------------------------------------------------------------------- 1 | const circle = { 2 | radius: 1, 3 | get area() { 4 | return Math.PI * this.radius * this.radius; 5 | } 6 | }; 7 | 8 | console.log(circle.area); 9 | -------------------------------------------------------------------------------- /functions/03-errorHandling.js: -------------------------------------------------------------------------------- 1 | 2 | function countOccurrences(array, searchElement) { 3 | if (!Array.isArray(array)) { 4 | throw new Error('Enter a valid array'); 5 | } 6 | return array.reduce((accumulator, current) => { 7 | const occurrence = (current === searchElement) ? 1 : 0; 8 | return accumulator + occurrence; 9 | }, 0) 10 | } 11 | 12 | try { 13 | const numbers = null; 14 | const count = countOccurrences(numbers, 1); 15 | console.log(count); 16 | } 17 | catch(e) { 18 | console.log(e.message) 19 | } 20 | -------------------------------------------------------------------------------- /functions/04-checkMaxNumber.js: -------------------------------------------------------------------------------- 1 | function max (a, b){ 2 | return (a > b) ? a : b; 3 | } 4 | console.log(max (30, 5)); 5 | -------------------------------------------------------------------------------- /functions/05-showStars.js: -------------------------------------------------------------------------------- 1 | showStars(2); 2 | 3 | function showStars(rows) { 4 | for (let row = 1; row <= rows; row++) { 5 | let pattern = ''; 6 | for (let i = 0; i < row; i++) 7 | pattern += '*'; 8 | console.log(pattern); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /functions/06-promises.js: -------------------------------------------------------------------------------- 1 | let d = new Promise((resolve, reject) => { 2 | setTimeout(() => { 3 | if (true){ 4 | resolve('hello world') 5 | } else{ 6 | reject('noooooo') 7 | } 8 | }, 1000); 9 | }); 10 | 11 | d.then((data) => console.log('success: ', data)); 12 | 13 | d.catch((error) => console.error('error ', error)); 14 | -------------------------------------------------------------------------------- /functions/07-generators.js: -------------------------------------------------------------------------------- 1 | function * greet() { 2 | console.log(`You called 'next()'`); 3 | yield 'hello there'; 4 | } 5 | 6 | let greeter = greet(); 7 | 8 | let next = greeter.next(); 9 | console.log(next); 10 | 11 | let done = greeter.next(); 12 | console.log(done); 13 | 14 | // ---------------------------------------------------------------------------------------- 15 | 16 | function * generatorFunction() { // Line 1 17 | console.log('This will be executed first.'); 18 | yield 'Hello, '; // Line 2 19 | console.log('I will be printed after the pause'); 20 | yield 'World!'; 21 | yield 'hi'; 22 | } 23 | const generatorObject = generatorFunction(); // Line 3 24 | console.log(generatorObject.next().value); // Line 4 25 | console.log(generatorObject.next().value); // Line 5 26 | console.log(generatorObject.next().value); // Line 6 27 | // This will be executed first. 28 | // Hello, 29 | // I will be printed after the pause 30 | // World! 31 | // undefined 32 | 33 | -------------------------------------------------------------------------------- /functions/08-mapsAndWeakMaps.js: -------------------------------------------------------------------------------- 1 | //Maps and WeakMaps with ES6 2 | 3 | let myMap = new Map(); 4 | 5 | //API 6 | /* 7 | set() 8 | get() 9 | size 10 | clear() 11 | has() 12 | */ 13 | 14 | let myObj = {}; 15 | let myFunc = function(){}; 16 | 17 | myMap.set(myObj, 'bar'); 18 | myMap.set(myFunc, 'world'); 19 | myMap.set('string', 2); 20 | 21 | console.log('get on myMap = ' + myMap.get(myObj)); 22 | 23 | //myMap.clear(); 24 | 25 | console.log('has on non-existing key = ' + myMap.has('qwerty')); 26 | 27 | //Iterators 28 | //keys() 29 | //entries() 30 | //values 31 | 32 | for(let [key, value] of myMap.entries()){ 33 | console.log(key + ' = ' + value); 34 | } 35 | 36 | //WeakMap Restrictions 37 | /* 38 | Because no references to keys are stored we do not have access to methods that require the ability to iterate the map such as: 39 | keys() 40 | values() 41 | entries() 42 | AND 43 | clear() 44 | */ 45 | let myWeakMap = new WeakMap(); 46 | 47 | let myObj2 = {}; 48 | let myFunc2 = function(){}; 49 | 50 | myMap.set(myObj2, 'bar'); 51 | myMap.set(myFunc2, 'world'); 52 | 53 | console.log(myMap.get(myObj)); 54 | -------------------------------------------------------------------------------- /functions/es6Modules/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | ES6 Modules 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /functions/es6Modules/index.js: -------------------------------------------------------------------------------- 1 | //imports the math functions from ./math.js 2 | // Detailed guide on es6 modules import/export: 3 | // https://www.sitepoint.com/understanding-es6-modules/ 4 | 5 | import * as math from './math.js'; 6 | 7 | console.log(math.sumAll(50, 10)); 8 | console.log(math.subtractAll(50, 10)); 9 | console.log(math.multiplyAll(50, 10)); 10 | console.log(math.divideAll(50, 10)); 11 | console.log(math.findModulus(50, 15)); 12 | -------------------------------------------------------------------------------- /functions/es6Modules/math.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | sumAll: (a, b) => { 3 | return a + b; 4 | }, 5 | subtractAll: (a, b) => { 6 | return a - b; 7 | }, 8 | multiplyAll: (a, b) => { 9 | return a * b; 10 | }, 11 | divideAll: (a, b) => { 12 | return a / b; 13 | }, 14 | findModulus: (a, b) => { 15 | return a % b; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /functions/math/addition.js: -------------------------------------------------------------------------------- 1 | function sumAll(a, b) { 2 | return a + b; 3 | } 4 | 5 | export { sumAll }; 6 | -------------------------------------------------------------------------------- /functions/math/division.js: -------------------------------------------------------------------------------- 1 | function divideAll(a, b) { 2 | return a / b; 3 | } 4 | 5 | export { divideAll }; 6 | -------------------------------------------------------------------------------- /functions/math/modulus.js: -------------------------------------------------------------------------------- 1 | function modulus(a, b) { 2 | return a % b; 3 | } 4 | 5 | export { modulus }; 6 | -------------------------------------------------------------------------------- /functions/math/multiplication.js: -------------------------------------------------------------------------------- 1 | function multiplyAll(a, b) { 2 | return a * b; 3 | } 4 | 5 | export { multiplyAll }; 6 | -------------------------------------------------------------------------------- /functions/math/subtraction.js: -------------------------------------------------------------------------------- 1 | function subtractAll(a, b) { 2 | return a - b; 3 | } 4 | 5 | export { subtractAll }; 6 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Js Code Snippets 9 | 10 | 11 | 12 | 13 |

    Js Code Snippets

    14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BolajiAyodeji/js-code-snippets/b23d54e6aa02d6e9956b65f8f54eab4af7ad60b5/index.js -------------------------------------------------------------------------------- /objects/01-maxOfTwo.js: -------------------------------------------------------------------------------- 1 | let numbet = max(1, 2); 2 | console.log(number); 3 | 4 | function max(a, b) { 5 | return (a > b) ? a : b; 6 | } 7 | -------------------------------------------------------------------------------- /objects/02-landscape.js: -------------------------------------------------------------------------------- 1 | console.log(isLandscape(300, 600)); 2 | 3 | function isLandscape(width, height) { 4 | return (width > height); 5 | } 6 | -------------------------------------------------------------------------------- /objects/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 | const input = prompt('enter number') 9 | let fizzBuzz = function (input) { 10 | if (typeof input !== 'number') 11 | return 'Not a number!'; 12 | 13 | if ((input % 3 === 0) && (input % 5 === 0)) 14 | return 'FizzBuzz'; 15 | 16 | if (input % 3 === 0) 17 | return 'Fizz'; 18 | 19 | if (input % 5 === 0) 20 | return 'Buzz'; 21 | 22 | if (input % 3 !== 0 && input % 5 !== 0) 23 | return input; 24 | 25 | return input; 26 | } 27 | 28 | try { 29 | let output = fizzBuzz(Hello); 30 | console.log(output); 31 | } catch (e) { 32 | if (e instanceof ReferenceError) { 33 | console.log("Not a number!") 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /objects/04-checkSpeed.js: -------------------------------------------------------------------------------- 1 | // Check driver's driving speed 2 | // Speed limit == 70km/hr ==> Speed OK 3 | // Speed limit < 70km/hr ==> Speed OK 4 | // For every 5km > Speed limit ==> One point++ 5 | // Speed limit >= (12 points) ==> License suspended 6 | 7 | function checkSpeed(speed) { 8 | const speedLimit = 70; 9 | const kmPerPoint = 5; 10 | const points = Math.floor((speed - speedLimit) / kmPerPoint); 11 | 12 | if (speed < speedLimit + kmPerPoint) { 13 | console.log('Speed OK'); 14 | return; 15 | } 16 | 17 | if (points >= 12) 18 | console.log('License suspended'); 19 | 20 | else 21 | console.log(points + ' points'); 22 | } 23 | 24 | checkSpeed(130); 25 | -------------------------------------------------------------------------------- /objects/05-showNumbers.js: -------------------------------------------------------------------------------- 1 | // check if number is ODD or even 2 | // Display all number count from 0 > limit and number status 3 | // e.g 2 "EVEN" 4 | 5 | function showNumber(limit) { 6 | for (let i = 0; i <= limit; i++) { 7 | const response = (i % 2 === 0) ? 'EVEN' : 'ODD'; 8 | console.log(i, response); 9 | } 10 | } 11 | showNumber(10); 12 | -------------------------------------------------------------------------------- /objects/06-countTruthy.js: -------------------------------------------------------------------------------- 1 | const array = [0, null, undefined, '', 2, 3]; 2 | 3 | console.log(countTruthy(array)); 4 | 5 | function countTruthy(array) { 6 | let count = 0; 7 | for (let value of array) 8 | if (value) 9 | count++; 10 | return count; 11 | } 12 | -------------------------------------------------------------------------------- /objects/07-showProperties.js: -------------------------------------------------------------------------------- 1 | const movie = { 2 | title: 'a', 3 | releaseYear: 2018, 4 | rating: 4.5, 5 | director: 'b' 6 | }; 7 | 8 | showProperties(movie); 9 | 10 | function showProperties(obj) { 11 | for (let key in obj) { 12 | if (typeof obj[key] === 'string') 13 | console.log(key, obj[key]); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /objects/08-sum.js: -------------------------------------------------------------------------------- 1 | console.log(sum(10)); 2 | 3 | function sum(limit) { 4 | let sum = 0; 5 | for (let i = 0; i <= limit; i++) 6 | if (i % 3 === 0 || i % 5 === 0) 7 | sum += i; 8 | 9 | return sum; 10 | } 11 | -------------------------------------------------------------------------------- /objects/09-grade.js: -------------------------------------------------------------------------------- 1 | function calculateGrade(marks) { 2 | const average = calculateAverage(marks); 3 | if (average < 60) return 'F'; 4 | if (average < 70) return 'D'; 5 | if (average < 80) return 'C'; 6 | if (average < 90) return 'B'; 7 | return 'A'; 8 | } 9 | 10 | function calculateAverage(array) { 11 | let sum = 0; 12 | for (let value of array) 13 | sum += value; 14 | return sum / array.length; 15 | } 16 | -------------------------------------------------------------------------------- /objects/10-showPrimes.js: -------------------------------------------------------------------------------- 1 | function showPrimes(limit) { 2 | for (let number = 2; number <= limit; number++) 3 | if (isPrime(number)) console.log(number); 4 | } 5 | 6 | function isPrime(number) { 7 | for (let factor = 2; factor < number; factor++) 8 | if (number % factor === 0) 9 | return false; 10 | 11 | return true; 12 | } 13 | -------------------------------------------------------------------------------- /objects/11-methodsInObjects.js: -------------------------------------------------------------------------------- 1 | // OOP 2 | // Object Oriented Programming 3 | 4 | const circle = { 5 | radius: 1, 6 | location: { 7 | x: 1, 8 | y: 1 9 | }, 10 | isVisible: true, 11 | draw: function() { 12 | console.log('draw'); 13 | } 14 | } 15 | circle.draw(); // Here the draw function is a Method in this Object 16 | 17 | // If a function is part of an Object, in OOP it is called a Method 18 | -------------------------------------------------------------------------------- /objects/12-factoryFunctions.js: -------------------------------------------------------------------------------- 1 | function createCircle(radius) { 2 | return { 3 | radius, 4 | draw () { 5 | console.log('draw'); 6 | } 7 | } 8 | circle.draw(); 9 | } 10 | 11 | const circle1 = createCircle(1); 12 | console.log(circle1); 13 | 14 | const circle2 = createCircle(2); 15 | console.log(circle2); 16 | -------------------------------------------------------------------------------- /objects/13-constructorFunctions.js: -------------------------------------------------------------------------------- 1 | // Constructor function 2 | // Constructs or creates an Object 3 | // By convention, constructor functions are named with "Pascal Notation" 4 | // camel notation ==> oneTwoThree 5 | // pascal notation ==> OneTwoThree 6 | 7 | function Circle(radius) { 8 | this.radius = radius; 9 | this.draw = function() { 10 | console.log('draw'); 11 | } 12 | } 13 | 14 | const circle = new Circle(1) 15 | console.log(circle); 16 | -------------------------------------------------------------------------------- /objects/14-constructorVsFactory.js: -------------------------------------------------------------------------------- 1 | // Factory Function 2 | function createCircle(radius) { 3 | return { 4 | radius, 5 | draw () { 6 | console.log('draw'); 7 | } 8 | } 9 | } 10 | 11 | const circleFactory = createCircle(1); 12 | console.log(circleFactory); 13 | 14 | // Constructor Function 15 | function CreateCircle(radius) { 16 | this.radius = radius; 17 | this.draw = function() { 18 | console.log('draw'); 19 | } 20 | } 21 | 22 | const circleConstructor = new CreateCircle(1); 23 | console.log(circleConstructor); 24 | -------------------------------------------------------------------------------- /objects/15-dynamicObjects.js: -------------------------------------------------------------------------------- 1 | const circle = { 2 | radius: 1 3 | }; 4 | console.log(circle); 5 | 6 | // circle = {}; will result in error 7 | // You cannot assign new properties to the const variable, but you can change or modify the object inside the variable 8 | 9 | // Adds more properties to the circle object 10 | circle.color = 'yellow'; 11 | circle.draw = function () { 12 | console.log('drawing'); 13 | } 14 | circle.large = true; 15 | 16 | // Deletes properties from the object 17 | delete circle.color; 18 | delete circle.draw; 19 | delete circle.large; 20 | // Now the object only contains the initial property 21 | // Try adding new properties, view them in the console first before you delete 22 | -------------------------------------------------------------------------------- /objects/16-callFunctions.js: -------------------------------------------------------------------------------- 1 | let person = { 2 | fullName: function() { 3 | return this.firstName + ' ' + this.lastName; 4 | } 5 | } 6 | let person1 = { 7 | firstName:'Bolaji', 8 | lastName: 'Ayodeji', 9 | } 10 | let person2 = { 11 | firstName:'Mary', 12 | lastName: 'Ayodeji', 13 | } 14 | person.fullName.call(person1); // Will return 'Bolaji Ayodeji' 15 | person.fullName.call(person2); // Will return 'Mary Ayodeji' 16 | 17 | 18 | // The call method with arguments 19 | let person = { 20 | fullName: function(city, country) { 21 | return this.firstName + ' ' + this.lastName + ',' + city + ',' + country; 22 | } 23 | } 24 | let person1 = { 25 | firstName:'Bolaji', 26 | lastName: 'Ayodeji', 27 | } 28 | person.fullName.call(person1, 'Kogi', 'Nigeria'); 29 | 30 | -------------------------------------------------------------------------------- /objects/17-applyFunctions.js: -------------------------------------------------------------------------------- 1 | let person = { 2 | fullName: function(city, country) { 3 | return this.firstName + ' ' + this.lastName + ',' + city + ',' + country; 4 | } 5 | } 6 | let person1 = { 7 | firstName:'Bolaji', 8 | lastName: 'Ayodeji', 9 | } 10 | person.fullName.apply(person1, ['Kogi', 'Nigeria']); 11 | -------------------------------------------------------------------------------- /objects/18-objectsProperties.js: -------------------------------------------------------------------------------- 1 | const circle = { 2 | radius: 1, 3 | draw() { 4 | console.log('draw'); 5 | } 6 | }; 7 | 8 | // Loop through objects 9 | for (let key in circle) 10 | console.log(key, circle[key]); 11 | 12 | // Loop through using "for of loop" with ".keys method" 13 | for (let key of Object.keys(circle)) 14 | console.log(key); 15 | 16 | // Loop through using "for of loop" with ".entries method" 17 | for (let key of Object.entries(circle)) 18 | console.log(key); 19 | 20 | // Check if object contains some property 21 | let check = ('radius' in circle) ? 'yes' : 'no'; 22 | console.log(check); 23 | -------------------------------------------------------------------------------- /objects/19-cloneObject.js: -------------------------------------------------------------------------------- 1 | const circle = { 2 | radius: 1, 3 | draw() { 4 | console.log('draw'); 5 | } 6 | }; 7 | 8 | // One way to clone (Not cool :() 9 | const circle2 = {}; 10 | for (let key in circle) 11 | circle2[key] = circle[key]; 12 | console.log(circle2); 13 | 14 | // Another way! 15 | circle3 = Object.assign({}, circle); 16 | console.log(circle3) 17 | 18 | // The initiated object in method two does not have to be empty 19 | circle4 = Object.assign({color: 'green'}, circle); 20 | console.log(circle4) 21 | 22 | // Simplest method. (The spread operator) 23 | const circle5 ={ ...circle}; 24 | console.log(circle5); 25 | -------------------------------------------------------------------------------- /objects/20-typeOfStrings.js: -------------------------------------------------------------------------------- 1 | // String primitive 2 | const message = 'hello'; 3 | console.log(typeof(message)); 4 | 5 | // String object 6 | const response = new String('Howdy?'); 7 | console.log(typeof(response)); 8 | 9 | // A String object can always be converted to its primitive counterpart with the valueOf() method. 10 | // All string methods can be found Here 11 | // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String 12 | -------------------------------------------------------------------------------- /objects/21-templateLiterals.js: -------------------------------------------------------------------------------- 1 | const name = 'Bolaji'; 2 | const email = 'hi@bolajiayodeji.com'; 3 | const password = 'h3lloworld'; 4 | 5 | const message = 6 | `Hello ${name} 7 | Thank you for signing up on our platform 8 | 9 | Here are your login details 10 | email: ${email} 11 | password: ${password}`; 12 | 13 | console.log(message); 14 | -------------------------------------------------------------------------------- /objects/22-dateObject.js: -------------------------------------------------------------------------------- 1 | const today = new Date() 2 | // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date 3 | -------------------------------------------------------------------------------- /objects/23-addressObject.js: -------------------------------------------------------------------------------- 1 | const address = { 2 | street: 'Heaven', 3 | city: 'lokoja', 4 | zipCode: 1100 5 | }; 6 | 7 | function showAddress(address) { 8 | for (let key in address) 9 | console.log(key, address[key]); 10 | } 11 | showAddress(address); 12 | 13 | // Factory function method 14 | function createAddress(street, city, zipCode) { 15 | return { 16 | street, 17 | city, 18 | zipCode 19 | }; 20 | } 21 | const address = createAddress('heaven', 'lokoja', 1100); 22 | console.log(address); 23 | 24 | // Constructor function method 25 | function CreateAddress2(street, city, zipCode) { 26 | this.street = street; 27 | this.city = city; 28 | this.zipCode = zipCode; 29 | } 30 | const address2 = new CreateAddress2('earth', 'lokoja', 1001); 31 | console.log(address2); 32 | -------------------------------------------------------------------------------- /objects/24-objectEquality.js: -------------------------------------------------------------------------------- 1 | // Check if two objects have qual properties and equal refrence types 2 | 3 | let address1 = new Address('earth', 'lokoja', 1001); 4 | let address2 = new Address('earth', 'lokoja', 1001); 5 | let address3 = address1; 6 | 7 | function Address(street, city, zipCode) { 8 | this.street = street; 9 | this.city = city; 10 | this.zipCode = zipCode; 11 | } 12 | 13 | function areEqual(address1, address2) { 14 | return address1.street === address2.street && 15 | address1.city === address2.city && 16 | address1.zipCode === address2.zipCode; 17 | } 18 | 19 | function areSame(address1, address2) { 20 | return address1 === address2; 21 | } 22 | 23 | console.log(areEqual(address1, address2)); 24 | console.log(areSame(address1, address2)); 25 | console.log(areSame(address1, address3)); 26 | -------------------------------------------------------------------------------- /objects/25-blogPost.js: -------------------------------------------------------------------------------- 1 | // title 2 | // body 3 | // author 4 | // views 5 | // comments 6 | // (author, body) 7 | // isLive 8 | 9 | 10 | let post = { 11 | title: 'lorem ipsum', 12 | body: 'hello world', 13 | author: 'bolaji ayodeji', 14 | views: 100, 15 | comments: [ 16 | {author: 'daniel', body: 'nice!'}, 17 | {author: 'rachel', body: 'cool'}, 18 | ], 19 | isLive: true 20 | } 21 | 22 | console.log(post); 23 | -------------------------------------------------------------------------------- /objects/26-blogSetup.js: -------------------------------------------------------------------------------- 1 | 2 | function Post(title, body, author) { 3 | this.title = title; 4 | this.body = body; 5 | this.author = author; 6 | this.views = 0; 7 | this.comments = []; 8 | this.isLive = false; 9 | } 10 | 11 | let post = new Post('lorem ipsum', 'hi', 'bolaji'); 12 | console.log(post); 13 | -------------------------------------------------------------------------------- /objects/27-priceRange.js: -------------------------------------------------------------------------------- 1 | let priceRanges = [ 2 | { label:'$', tooltip:'Inexpensive', minPerPerson:0, maxPerPerson:10 }, 3 | { label:'$$', tooltip:'Moderate', minPerPerson:11, maxPerPerson:20 }, 4 | { label:'$$$', tooltip:'Expensive', minPerPerson:21, maxPerPerson:50 }, 5 | ] 6 | 7 | let restaurants = [ 8 | { averagePerson: 5 } 9 | ] 10 | -------------------------------------------------------------------------------- /objects/28-paramObjectDestructure.js: -------------------------------------------------------------------------------- 1 | console.clear(); 2 | 3 | function ajax({ 4 | type = "get", 5 | url = requiredParameter("url"), 6 | data = {}, 7 | success = requiredParameter("success"), 8 | error = () => {}, 9 | isAsync = true } = {}) { 10 | console.log(JSON.stringify({ type, url, data, success, error, isAsync }, null, 2)); 11 | } 12 | 13 | function requiredParameter(name) { 14 | throw new Error(`Missing parameter "${name}"`); 15 | } 16 | 17 | try { 18 | ajax({ 19 | url: "https://my.api.io", 20 | success: () => {} 21 | }); 22 | } catch (e) { console.warn(e.message)} 23 | -------------------------------------------------------------------------------- /objects/29-restParameter.js: -------------------------------------------------------------------------------- 1 | // rest parameter vs arguments keyword 2 | 3 | function Store() { 4 | let aisle = { 5 | fruit: [], 6 | vegetable: [] 7 | } 8 | return { 9 | //Store().add('category', 'item1', 'item2'); 10 | add: function(category, ...items) { 11 | //let items = [].splice.call(arguments, 1); 12 | console.log(items); 13 | items.forEach(function(value, index, array) { 14 | aisle[category].push(value); 15 | }); 16 | }, 17 | aisle: aisle 18 | } 19 | } 20 | 21 | let myGroceryStore = new Store(); 22 | 23 | myGroceryStore.add('fruit', 'apples', 'oranges'); 24 | console.log(myGroceryStore.aisle); 25 | -------------------------------------------------------------------------------- /operators/conversion.js: -------------------------------------------------------------------------------- 1 | // Converting Integer to String 2 | let age = 34; 3 | let ageToString = '' + age; 4 | console.log(ageToString); 5 | console.log(typeof ageToString); 6 | 7 | // Converting String to Integer 8 | let length = '785'; 9 | let lengthToInt = +length; 10 | console.log(lengthToInt); 11 | console.log(typeof lengthToInt); 12 | -------------------------------------------------------------------------------- /operators/swap.js: -------------------------------------------------------------------------------- 1 | let a = 'red'; 2 | let b = 'blue'; 3 | let c = a; 4 | 5 | a = b; 6 | b = c; 7 | 8 | console.log(a); 9 | console.log(b); 10 | -------------------------------------------------------------------------------- /operators/tenary.js: -------------------------------------------------------------------------------- 1 | //Check points 2 | let points = 200; 3 | let type = points > 110?'gold':'silver'; 4 | console.log(type); 5 | 6 | //Checks max number 7 | const num = [3, 5] 8 | console.log(num); 9 | 10 | let max = num[0] > num[1] ? 'yes':'no'; 11 | console.log(max); 12 | 13 | --------------------------------------------------------------------------------