- Notifications
You must be signed in to change notification settings - Fork56
dinanathsj29/javascript-exercise-beginners
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
- JavaScript is a programming language that adds interactivity to Web pages
- JavaScript is a scripting language
- A JavaScript script is a program that is included on an HTML page
- JavaScript scripts are text on Web pages that are interpreted and run by Web browsers
- JavaScript is initially named and developed as
LiveScript
at Netscape Navigator Corporation - JavaScript is
not Java
- Due to Java wave or Java popularity and buzz,
LiveScript
renamed toJavaScript
- Create an active User Interface
- Control the user experience based on Day, Date, Time and Browser, etc
- Validate user input on forms
- Create custom HTML pages on the fly/dynamically
- Control Web browsers interactivity and behaviors
- JavaScript can't talk to a Database (Its possible with NodeJs)
- JavaScript can't write to files (Its possible with NodeJs)
- Keep track of state (except with cookies)
- Example 1 - swapping variables
- Example 2 - max number
- Example 3 - Landscape Portrait
- Example 4 - FizzBuzz Algorithms
- Example 5 - Speed Limits
- Example 6 - Odd Even Number Loop
- Example 7 - Count Truthy Falsy Values
- Example 8 - Object String Properties Key
- Example 9 - Sum of Multiples
- Example 10 - Netsted Loop Star Pattern
- Example 11 - Marks Average Grade
- Example 12 - Random Bingo Card
- Example 13 - Show Prime Numbers
- Example 14 - Sum Of Arguments
- Example 15 - Sum Of Arguments Array
- Example 16 - Circle Area Object Read Only Property
- Example 17 - Create Array From Argument Range
- Example 18 - Array Includes Element Exists
- Example 19 - Array Excludes Value To New Array
- Example 20 - Array Count Search Occurances
- Example 21 - Array Get Max Largest Number
- Example 22 - Array Filter Sort Map
- Example 23 - Object Create Students and Address Object
- Example 24 - Object Create Object Factory Constructor Function
- Example 25 - Object Equality
Syntax & Example:
1-swapping-variables.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>swapping-variables</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>1-swapping-variables!</h1><h3>Swap the values of variable</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('1-swapping-variables');letvalue1='one';letvalue2='two';// original valuesconsole.log('original',value1);console.log('original',value2);// swapping valuesletvalue3=value1;value1=value2;value2=value3;console.log('swap',value1);console.log('swap',value2);
Syntax & Example: global
style.css
body{font-family:'Lucida Sans','Lucida Sans Regular','Lucida Grande','Lucida Sans Unicode', Geneva, Verdana, sans-serif;}h1,th{font-family:'Trebuchet MS','Lucida Sans Unicode','Lucida Grande','Lucida Sans', Arial, sans-serif;}table{/* border: 2px solid #696969; border-collapse: collapse; */font-size:18px;}th{width:20%;}th,td{padding:10px;border:2px solid#696969;text-align: center;}#freeSquare{background-color: coral;}
Syntax & Example:
2-max-number.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>max-number</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>2-max-number!</h1><h3>Write a function which returns the maximum of two number</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('2-max-number');functionfindMaxNumber(num1,num2){// 1. long syntax/* if(num1 > num2){ return num1 } else { return num2 } */// 2. short syntax/* if(num1 > num2) return num1; else return num2; */// 3. ternary short syntaxreturn(num1>num2) ?num1 :num2;}letcheckMax1=findMaxNumber(10,5);console.log('Max Number:',checkMax1);letcheckMax2=findMaxNumber(10,15);console.log('Max Number:',checkMax2);letcheckMax3=findMaxNumber(100,100);console.log('Max Number:',checkMax3);
Syntax & Example:
3-landscape-portrait.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>landscape-portrait</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>3-landscape-portrait!</h1><h3>Write a function which checks given width and height, returns true (landscape) if width is greater than height and vice versa</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('3-landscape-portrait');functionisLandscape(width,height){// 3. ternary short syntaxreturn(width>height);}letcheckWidthHeight1=isLandscape(800,600);console.log('Landscape:',checkWidthHeight1);letcheckWidthHeight2=isLandscape(600,800);console.log('Landscape:',checkWidthHeight2);letcheckWidthHeight3=isLandscape(1024,768);console.log('Landscape:',checkWidthHeight3);
Syntax & Example:
4-fizzbuzz-algorithms.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>fizzbuzz-algorithms</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>4-fizzbuzz-algorithms!</h1><h3>Write a function which checks given input/parameter:</h3><ul><li>If input/parameter is divisible by 3 print => Fizz</li><li>If input/parameter is divisible by 5 print => Buzz</li><li>If input/parameter is divisible by 3 or 5 print => FizzBuzz</li><li>If input/parameter is NOT divisible by 3 or 5 print => given Input Number/Value</li><li>If input/parameter is other than Number/Value print => 'Nan - Not a Number! Please Input Number'</li></ul><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('4-fizzbuzz-algorithms');/*<h3>Write a function which checks given input/parameter:</h3><ul> <li>If input/parameter is divisible by 3 print => Fizz</li> <li>If input/parameter is divisible by 5 print => Buzz</li> <li>If input/parameter is divisible by 3 or 5 print => FizzBuzz</li> <li>If input/parameter is NOT divisible by 3 or 5 print => given Input Number/Value</li> <li>If input/parameter is other than Number/Value print => 'Nan - Not a Number! Please Input Number' </li></ul>*/functionisfizzBuzz(arg){if(typeofarg!=='number'){return('Nan - Not a Number! Please Input Number');}if((arg%3===0)&&(arg%5===0)){return'FizzBuzz';}if(arg%3===0){return'Fizz';}if(arg%5===0){return'Buzz';}else{return'Some odd number entered: '+arg;}}letcheckFizzBuzz1=isfizzBuzz('one');console.log(checkFizzBuzz1);letcheckFizzBuzz2=isfizzBuzz(true);console.log(checkFizzBuzz2);letcheckFizzBuzz3=isfizzBuzz(9);console.log(checkFizzBuzz3);letcheckFizzBuzz4=isfizzBuzz(10);console.log(checkFizzBuzz4);letcheckFizzBuzz5=isfizzBuzz(30);console.log(checkFizzBuzz5);letcheckFizzBuzz6=isfizzBuzz(11);console.log(checkFizzBuzz6);
Syntax & Example:
5-speed-limits.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>speed-limits</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>5-speed-limits!</h1><h3>Write a function which checks given input/parameter:</h3><ul><li>If input/parameter is below speedlimit of 70 print => 'Good Safe Driving'</li><li>If input/parameter is above speedlimit of 70, every 5 kilometers is Penalty Point, print => 'Speed Limit Crossed by Penalty Point' + Point</li><li>If Driver gets more than 10 penalty points ie. above the speed limit 120, print => 'License Suspended'</li></ul><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('5-speed-limits');/*<h3>Write a function which checks given input/parameter:</h3><ul> <li>If input/parameter is below speedlimit of 70 print => 'Good Safe Driving'</li> <li>If input/parameter is above speedlimit of 70, every 5 kilometers is Penalty Point, print => 'Speed Limit Crossed by Penalty Point' + Point </li> <li>If Driver gets more than 10 penalty points ie. above the speed limit 120, print => 'License Suspended'</li></ul>*/constSPEEDLIMIT=70;constKMPERPOINT=5;functioncheckSpeedLimit(curSpeed){if(curSpeed<=SPEEDLIMIT){return('Good Safe Driving!');}else{letpenaltyPoint=Math.floor((curSpeed-SPEEDLIMIT)/KMPERPOINT);if(penaltyPoint<10){return('Speed Limit Crossed by Penalty Point: '+penaltyPoint);}else{return('License Suspended!');}}}letcheckPoin1=checkSpeedLimit(40);console.log(checkPoin1);letcheckPoin2=checkSpeedLimit(70);console.log(checkPoin2);letcheckPoin3=checkSpeedLimit(75);console.log(checkPoin3);letcheckPoin4=checkSpeedLimit(99);console.log(checkPoin4);letcheckPoin5=checkSpeedLimit(120);console.log(checkPoin5);
Syntax & Example:
6-odd-even-number-loop.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>odd-even-number-loop</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>6-odd-even-number-loop!</h1><h3>Write a function which checks number till given input/parameter is odd or even</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('6-odd-even-number-loop');functionisOddEvenNumber(curLimit){for(leti=0;i<=curLimit;i++){/* if (i % 2 === 0) { console.log(i , 'EVEN'); } else { console.log(i , 'ODD'); } */constalertMessage=(i%2===0) ?'EVEN' :'ODD';console.log(i,alertMessage);}}isOddEvenNumber(10);// isOddEvenNumber(17);
Syntax & Example:
7-count-truthy-falsy-values.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>count-truthy-falsy-values.html</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>7-count-truthy-falsy-values!</h1><h3>Write a function which checks and count the truthy values from an array</h3> Falsy values in JavaScript are:<ul><li>false</li><li>0 (zero)</li><li>undefined</li><li>null</li><li>''</li><li>NaN</li></ul><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('7-count-truthy-falsy-values');/*<h3>Write a function which checks and count the truthy values from an array</h3>Falsy values in JavaScript are:<ul> <li>false</li> <li>0 (zero)</li> <li>undefined</li> <li>null</li> <li>''</li> <li>NaN</li></ul>*/constvaluesArray=[0,1,'',undefined,false,true];functioncheckCountTruthyFalsy(curArray){lettruthyCount=0;for(letvalueofcurArray){// no need to check if(value !== false || value !== 0 || value !== '' or ...)if(value){truthyCount++;}}returntruthyCount;}console.log(checkCountTruthyFalsy(valuesArray));
Syntax & Example:
8-object-string-properties-key.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>object-string-properties-key</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>8-object-string-properties-key!</h1><h3>Write a function which checks and prints only the string type properties of an object</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('8-object-string-properties-key');functionshowStringProperties(curObj){for(letkeyincurObj){// console.log('key/prop:', key);if(typeof(curObj[key])==='string'){console.log(key,':',curObj[key]);}}}constPerson={name:'Dinanath',age:40,height:5.6,country:'India',designation:'UI Developer'}showStringProperties(Person);console.log('----------');constTechnology={name:'JavaScipt',version:6,purpose:'Scripting language for Web',developer:'Netscape Corporation'}showStringProperties(Technology);console.log('----------');
Syntax & Example:
9-sum-of-multiples.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>sum-of-multiples</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>9-sum-of-multiples!</h1><h3>Write a function which Calculate the sum of multiples of 3 and 5 for a given limit</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('9-sum-of-multiples');functionsumOfMultiples(curLimit){letsumOfMultipleValue=0;for(leti=0;i<=curLimit;i++){if(i%3===0||i%5===0){// console.log(i);sumOfMultipleValue+=i;}}// return sumOfMultipleValue;console.log(`sumOfMultipleValue of 3 & 5 upto${curLimit} digit is:`,sumOfMultipleValue);}sumOfMultiples(10);
Syntax & Example:
10-netsted-loop-star-pattern.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>10-netsted-loop-star-pattern</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>10-netsted-loop-star-pattern!</h1><h3>Write a function which Prints/Shows star-aestrikes (or any pattern) for the number of times and rows provided</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('10-netsted-loop-star-pattern');functionshowPattern(totalRowsPatternCount){for(letcurRow=1;curRow<=totalRowsPatternCount;curRow++){// console.log(curRow);letpatternDesign='';for(leti=0;i<curRow;i++){patternDesign+='*'}console.log(patternDesign);}}showPattern(5);
Syntax & Example:
11-marks-average-grade.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>marks-average-grade</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>11-marks-average-grade!</h1><h3>Write a function which Calculate the sum of marks provided in an array, average it and also show Grade</h3> Grade criteria/mechanism is:<ul><li>0% to 70% => D Grade</li><li>71% to 79% => C Grade</li><li>81% to 89% => B Grade</li><li>91% to 100% => A Grade</li></ul><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('11-marks-average-grade');// approach 1/* const MARKSARRAY = [55, 85, 55, 65];function calculateAverageGrade(currentMarks) { let totalMarks = 0; let averageMarks = 0; let grade; for(let mark of currentMarks) { totalMarks += mark; } // console.log('totalMarks:', totalMarks); averageMarks = (totalMarks/currentMarks.length); // console.log('averageMarks:', averageMarks); if(averageMarks < 70) return grade = 'D'; if(averageMarks < 80) return grade = 'C'; if(averageMarks < 90) return grade = 'B'; if(averageMarks <= 100) return grade = 'A';}console.log('Grade:', calculateAverageGrade(MARKSARRAY)); */// approach 2 - create two different functions with single responsibility principleconstMARKSARRAY=[55,85,55,65];functioncalculateAverage(currentArray){lettotal=0;for(letcurValueofcurrentArray){total+=curValue;}// console.log('total:', total);return(total/currentArray.length);}// console.log(calculateAverage(MARKSARRAY));functioncalculateGrades(_currentArray){constaverage=calculateAverage(_currentArray);// console.log('average:', average);if(average<70)returngrade='D';if(average<80)returngrade='C';if(average<90)returngrade='B';if(average<=100)returngrade='A';}console.log('Grade:',calculateGrades(MARKSARRAY));
Syntax & Example:
12-random-bingo-card.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>random-bingo-card</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>12-random-bingo-card!</h1><h3>Write a function to create a Bingo Card with Random numbers upto 75</h3><table><thead><tr><thclass="heading">B</th><thclass="heading">I</th><thclass="heading">N</th><thclass="heading">G</th><thclass="heading">O</th></tr></thead><tbody><tr><tdid="Square1"> </td><tdid="Square2"> </td><tdid="Square3"> </td><tdid="Square4"> </td><tdid="Square5"> </td></tr><tr><tdid="Square6"> </td><tdid="Square7"> </td><tdid="Square8"> </td><tdid="Square9"> </td><tdid="Square10"> </td></tr><tr><tdid="Square11"> </td><tdid="Square12"> </td><tdid="freeSquare">Free</td><tdid="Square13"> </td><tdid="Square14"> </td></tr><tr><tdid="Square15"> </td><tdid="Square16"> </td><tdid="Square17"> </td><tdid="Square18"> </td><tdid="Square19"> </td></tr><tr><tdid="Square20"> </td><tdid="Square21"> </td><tdid="Square22"> </td><tdid="Square23"> </td><tdid="Square24"> </td></tr></tbody></table><h3><ahref="">Click here</a> (Reload/Refresh) to create Random Bingo Card!</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('12-random-bingo-card');window.onload=createBingoCard;functioncreateBingoCard(){// console.log('in createBingoCard');for(vari=1;i<=24;i++){varnewRandomNum=Math.floor(Math.random()*75);// console.log('newRandomNum', newRandomNum);document.getElementById('Square'+i).innerHTML=newRandomNum;}}
Syntax & Example:
13-show-prime-numbers.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>show-prime-numbers</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>13-show-prime-numbers!</h1><h3>Write a function which show or print Prime Number upto provided range</h3><ul><li>Prime Numbers are those numbers whose factors are only `1` and `the number itself`</li><li>In simple language Prime Numbers are divisible by only `1` and `the number itself/himself`</li><li>Prime Numbers have only two factors: `1` and `the number itself/himself`</li><li>Example: 2, 3, 5, 7, 11, 13, 17, 19 and so on...</li></ul><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('13-show-prime-numbers');// approach 1/* function showPrimeNumbers(numberLimit) { for (let curNum = 2; curNum <= numberLimit; curNum++) { // console.log('curNum', curNum); let isPrime = true; for (let factor = 2; factor < curNum; factor++) { // console.log('factor', factor); if (curNum % factor === 0) { isPrime = false; break; } } if (isPrime) { console.log('Prime Number', curNum); } }}showPrimeNumbers(20);*/// approach 2functionshowPrimeNumbers(numberLimit){for(letcurNum=2;curNum<=numberLimit;curNum++){// console.log('curNum', curNum);if(isPrimeNumber(curNum)){console.log('Prime Number:',curNum);}}}functionisPrimeNumber(_number){for(letfactor=2;factor<_number;factor++){// console.log('factor', factor);if(_number%factor===0){returnfalse;}}returntrue;}showPrimeNumbers(20);
Syntax & Example:
14-sum-of-arguments.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>sum-of-arguments</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>14-sum-of-arguments!</h1><h3>Write a function which show or print Sum of Arguments passed</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('14-sum-of-arguments');functionsumOfArguments(...items){// rest operator converts anything passed as an arrayconsole.log('current items/values to add:',items);returnitems.reduce((n1,n2)=>n1+n2);}console.log('Sum:',sumOfArguments(10,2,8,4,6));// console.log('Sum:', sumOfArguments([10, 2, 8, 4, 6]));
Syntax & Example:
15-sum-of-arguments-array.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>sum-of-arguments-array</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>15-sum-of-arguments-array!</h1><h3>Write a function which show or print Sum of Arguments passed as an Array</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('15-sum-of-arguments-array');functionsumOfArguments(...items){// as rest operator converts anything passed as an array check followingif(items.length===1&&Array.isArray(items[0])){// reset item as a new arrayitems=[...items[0]]console.log('current items/values to add:',items);returnitems.reduce((n1,n2)=>n1+n2);}}// pass arguments as an array// console.log('Sum:', sumOfArguments([10, 2, 8, 4, 6]));console.log('Sum:',sumOfArguments([10,2,8,4,6]));
Syntax & Example:
16-circle-area-object-read-only-property.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>circle-area-object-read-only-property</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>16-circle-area-object-read-only-property!</h1><h3>Create an object with read only propety named 'area'</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('16-circle-area-object-read-only-property');constCIRCLE={name:'mainCircle',lineColor:'red',bgColor:'gray',radius:1,getarea(){returnMath.PI*this.radius*this.radius;}}console.log('CIRCLE.area:',CIRCLE.area);
Syntax & Example:
17-create-array-from-argument-range.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>create-array-from-argument-range</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>17-create-array-from-argument-range!</h1><h3>Create an array of the values from the 'min' and 'max' (start & end) range provided</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('17-create-array-from-argument-range');functiongenerateArrayFromRange(startNum,endNum){constrangeArray=[];for(letcurNum=startNum;curNum<=endNum;curNum++){// console.log('curNum: ', curNum);rangeArray.push(curNum);// console.log('rangeArray: ', rangeArray);}returnrangeArray;}constrange1=generateArrayFromRange(1,5);console.log(range1);console.log('----------');constrange2=generateArrayFromRange(-5,0);console.log(range2);
Syntax & Example:
18-array-includes-element-exists.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>array-includes-element-exists</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>18-array-includes-element-exists!</h1><h3>Create a method named 'includes' which checks an element exists in an array</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('18-array-includes-element-exists');functionincludes(arrayToSearch,elementToSearch){console.log('arrayToSearch: ',arrayToSearch);console.log('elementToSearch: ',elementToSearch);for(letcurElementofarrayToSearch){if(curElement===elementToSearch){returntrue;}}returnfalse;}constversionArray=[1,2,5,7,2];console.log(includes(versionArray,2));console.log('---------');constageArray=[21,22,25,27,25];console.log(includes(ageArray,30));
Syntax & Example:
19-array-excludes-value-to-new-array.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>array-excludes-value-to-new-array</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>19-array-excludes-value-to-new-array!</h1><h3>Create a method named 'excludes' which cut/excludes values from existing array and push to new array</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('19-array-excludes-value-to-new-array');functionexcludes(arrayToExclude,elementsToExcluded){console.log('arrayToExclude: ',arrayToExclude);console.log('elementsToExcluded: ',elementsToExcluded);constoutputArray=[];for(letcurElementofarrayToExclude){if(!elementsToExcluded.includes(curElement)){outputArray.push(curElement)}}returnoutputArray;}constversionArray=[1,2,5,7,2];constnewVesionArray=(excludes(versionArray,[2]));console.log('newVesionArray: ',newVesionArray);console.log('---------');constageArray=[21,25,22,25,30,25,30];constnewAgeArray=(excludes(ageArray,[25,30]));console.log('newAgeArray: ',newAgeArray);
Syntax & Example:
array-count-search-occurances.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>array-count-search-occurances</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>20-array-count-search-occurances!</h1><h3>Create a function which counts the search occurances from an array</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('20-array-count-search-occurances');// approach 1/* function countSearchOccurances(arrayToSearch, elementsToSearch) { // console.log('arrayToSearch: ', arrayToSearch); // console.log('elementsToSearch: ', elementsToSearch); let count = 0; for(let curElement of arrayToSearch) { if(curElement === elementsToSearch) { count++; } } // console.log('search count:', count); return count;} */// approach 2functioncountSearchOccurances(arrayToSearch,elementsToSearch){returnarrayToSearch.reduce((countAccumulator,curentSearchElement)=>{letcountOccurances=(curentSearchElement===elementsToSearch) ?1 :0;// console.log('countAccumulator', countAccumulator, 'arrayToSearch', arrayToSearch, 'elementsToSearch', elementsToSearch,);returncountAccumulator+countOccurances;},0)}constversionArray=[1,2,5,7,2];constversionCount=(countSearchOccurances(versionArray,2));console.log('versionCount: ',versionCount);console.log('---------');constageArray=[21,25,22,25,30,25,30];constageCount=(countSearchOccurances(ageArray,-25));console.log('ageCount: ',ageCount);
Syntax & Example:
21-array-get-max-largest-number.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>array-get-max-largest-number</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>21-array-get-max-largest-number!</h1><h3>Create a function which returns the maximum ie. largest number from an array</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('21-array-get-max-largest-number');// approach 1/*function getLargestNumber(arrayToSearch) { if (arrayToSearch.length <= 0) return 'Array is Empty! Nothing to search!!'; let largetNumber = arrayToSearch[0]; for (let i = 1; i < arrayToSearch.length; i++) { if (arrayToSearch[i] > largetNumber) { largetNumber = arrayToSearch[i]; } } return largetNumber;}const versionArray = [5, 2, 3, 4, 7];const largestVersion = (getLargestNumber(versionArray));console.log('largestVersion: ', largestVersion);console.log('---------');const ageArray = [21, 25, 22, 25, 30, 25, 30];const maxAge = (getLargestNumber(ageArray));console.log('maxAge: ', maxAge); */// approach 2functiongetLargestNumber(arrayToSearch){if(arrayToSearch.length<=0)return'Array is Empty! Nothing to search!!';returnarrayToSearch.reduce((largetNumber,curentSearchElement)=>{return(curentSearchElement>largetNumber) ?curentSearchElement :largetNumber;})}constversionArray=[5,2,3,4,7];constlargestVersion=(getLargestNumber(versionArray));console.log('largestVersion: ',largestVersion);console.log('---------');constageArray=[21,25,22,25,30,25,30];constmaxAge=(getLargestNumber(ageArray));console.log('maxAge: ',maxAge);
Syntax & Example:
22-array-filter-sort-map.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>array-filter-sort-map</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>22-array-filter-sort-map!</h1><h3>Array: Filter the array of students with Higest Ranking, Sort on Ranking, finally Show the Names</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('22-array-filter-sort-map');conststudentsArray=[{name:'Suraj',year:2019,ranking:4},{name:'Amit',year:2019,ranking:5},{name:'Akash',year:2018,ranking:4},{name:'Dinanath',year:2019,ranking:7},{name:'Sagar',year:2017,ranking:3},]console.log('Higest Rank Holders:',studentsArray.filter(student=>student.year===2019&&student.ranking>=5).sort((n1,n2)=>n1.ranking-n2.ranking).reverse().map(student=>student.name));
Syntax & Example:
23-object-create-students-and-address-object.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>object-create-students-and-address-object</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>23-object-create-students-and-address-object!</h1><h3>Create an Object for Students and Address with various Properties and Methods</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('23-object-create-students-and-address-object');constStudents={name:'Dinanath',age:35,rank:5,country:'India',}constAddress={street:'Sir DJ Road',city:'Mumbai',pinCode:401209,state:'MH',country:'India',}functionshowObjectDetails(obj){for(letkeyinobj){console.log(key,' : ',obj[key]);}}showObjectDetails(Students);console.log('----------');showObjectDetails(Address);
Syntax & Example:
24-object-create-object-factory-constructor-function.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>object-create-object-factory-constructor-function</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>24-object-create-object-factory-constructor-function!</h1><h3>Create an Object of Students by using Factory and Constructor methods</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('24-object-create-object-factory-constructor-function');// Factory function/method - camelCasing - camel notation - use return keywordfunctioncreateObjFactoryMethod(name,age,rank,country){return{ name, age, rank, country}}letStudents1=createObjFactoryMethod('Dinanath',35,5,'India');console.log('Students1',Students1);// Constructor function/method - pascalCasing - pascal notation - use this keywordfunctionStudent(name,age,rank,country){this.name=name;this.age=age;this.rank=rank;this.country=country;}letStudents2=newStudent('Amit',30,4,'Hindustan');console.log('Students2',Students2);
Syntax & Example:
25-object-equality.html
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>object-equality</title><linkrel="stylesheet"type="text/css"href="../style.css"/></head><body><h1>25-object-equality!</h1><h3>Write function to check object equality</h3><scripttype="text/javascript"src="script.js"></script></body></html>
Syntax & Example:
script.js
console.log('25-object-equality');// Constructor function/method - pascalCasing - pascal notation - use this keywordfunctionStudent(name,age,rank,country){this.name=name;this.age=age;this.rank=rank;this.country=country;}letStudents1=newStudent('Dinanath',35,5,'India');console.log('Students1',Students1);letStudents2=newStudent('Dinanath',35,5,'India');console.log('Students2',Students2);console.log('----------');// Objects are reference type, objects can have same properties but they are from different memeory location, they can be equal if both objects have same propertiesfunctionisObjectEqual(obj1,obj2){returnobj1.name===obj2.name&&obj1.age===obj2.age&&obj1.rank===obj2.rank&&obj1.country===obj2.country}console.log('isEqual',isObjectEqual(Students1,Students2));console.log('----------');// Objects are same if both are pointed to same objectfunctionisObjectPointSame(obj1,obj2){returnobj1===obj2;}letisSame1=isObjectPointSame(Students1,Students2);console.log('isSame1',isSame1);letStudents3=Students2;letisSame2=isObjectPointSame(Students2,Students3);console.log('isSame2',isSame2);
About
Lets go-through, learn and understand different logical Javascript exercises and algorithms for beginners.
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.