The let keyword was added to the JavaScript language in 2015. It was added as a replacement to the use of the var keyword because there are some problems with the var keyword.
Variables declared with the var keyword do not obey scope rules. Any variable declared with the var keyword is considered to be a global variable, except in the case when it is declared within a function.
The take-away is that you should always use let (or const) to declare your variables instead of var.
for (var i =0; i<array.length; ++i) {console.log(i);}// i is valid outside of the for loopconsole.log(i);
if (3>2) {var i =0;console.log(i);}// i is valid outside of the if loopconsole.log(i);
functiontest() {var i =0;}// i is not defined outside of a function. this// is the only case the follows expected scope rulesconsole.log(i):
Functions
We worked through several functions to practice basic setup and executing expressions using best-practices.
functionmax(a,b) {if (a>b) {return a; }else {return b; }}// the body block begin/end braces, {} are not necessary// when there is a single functionmax(a,b) {if (a>b) return a;elsereturn b;}
functionisLandscape(width, height) {if (width>height) returntrue;returnfalse;}// the return true and return false are not necessaryfunctionisLandscape(width, height) {return (width>height);}
// using a for loop to generate a string of start// num=3 => ***// num=10 => **********functionstars(num) {let answer ="";for (let i=1; i<=num;++i) { answer+="*"; }return answer;}
// divisible by 3 ==> Fizz// divisible by 5 ==> Buzz// divisible by both 3 and 5 ==> FizzBuzz// not divisible by 3 or 5 ==> inputfunctionfizzBuzz(num) {constdivisibleBy3= num%3===0;constdivisibleBy5= num%5===0// this test needs to happen first to// catch the case because a number lik 15// will also match the other cases and // you want it to match this case.if (divisibleBy3 && divisibleBy5) {return"FizzBuzz"; }elseif (divisibleBy3) {return"Fizz"; }elseif (divisibleBy5 ) {return"Buzz"; }else {return num; }}// this is also allowed// some style-guides say they want you to always// use {} for code blocks, even if there is a single// statement in the block. the exception// would be when the condition is very small,// so the overall line is very small and it makes// it more readable.// in this case it's kind of borderline. the// first line is getting a little long, but the overall// code is pretty readable in the condensed version.functionfizzBuzz(num) {constdivisibleBy3= num%3===0;constdivisibleBy5= num%5===0if (divisibleBy3 && divisibleBy5) return"FizzBuzz";elseif (divisibleBy3) return"Fizz";elseif (divisibleBy5) return"Buzz";elsereturn num;}
Passing Functions to Functions
Functions in JavaScript are objects, just like an array or a string is an object. You can pass a function as an argument to another function, allowing the function that is receiving it as a parameter to execute the function.
// this function accepts a function as a parameterfunctiondoThis(func) {// to execute the function, it needs to be calledfunc();}functionsayHello() {console.log(sayHello);}// sayHello is being passes as a function, it is not// being called. To call a function you must use// the (), i.e. sayHello()doThis(sayHello);// you can also pass in the function directly without having// to declare itdoThis(functionsayHello() {console.log(sayHello);});// and it can be further shortened todoThis(() => {console.log(sayHello);});// in all these cases, the function sayHello isn't being called until // inside the doThis function when it is called like func();
Array forEach
The forEach method takes a function as a parameter and the function will be called for each element in the array and the function will be passed the current element.
numbers = [1,2,3,4];functionforEach(array, func) {for (let i=0;i<array.length; i++) {func(array[i]); }}// we can pass in a function to the Array.forEach methodfunctionlogNum(num) {console.log(num);}numbers.forEach(logNum);// or an annonymous arrow functionnumbers.forEach(num=>console.log(num));let total =0;numbers.forEach(num=>total+=num);console.log(total);let maxNum =0;numbers.forEach(num=> {if (num>maxNum) { maxNum = num; }}console.log(maxNum);
Practice
I've provided a bunch of sample functions to practice. You should be starting to feel more comfortable with understanding what the function is asking you to do and thinking about how to approach solving the problem. You don't need to solve all of these, but push yourself to solve some that are beyond your comfort level.
For any of the problems that require looping you can create your own for loop or use the Array.forEach method.
write a functioncalledsumthatacceptsthreeparameters, allnumbers,andreturnsthesumofthethreenumbers.callthefunctionalogtheresulttotheconsole.
write a functioncalledfindElement, thatacceptsanarrayofnumbersandanumbertosearchforinthearray.if the number is in the array,returntrue. otherwise return false;sample callconsole.log(findElement([1,2,5],2)); // returns trueconsole.log(findElement([1,2,5],3)); // returns false
write a functioncalledlogMessagethatacceptstwoparameter,firstNameandlastName, andcreatesamessagebyconcatenatingtheinputparameterstogethertoformanewstringandreturnsthenewstring.samplecall (note the spaces between the words)logMessage("Anne","Chinn") shouldreturn "HelloAnneChinn".logthereturnvaluetotheconsole.
These ones are more challenging, using several different things we've been learning to build a larger series of steps.
write a functionnumsInRangethatacceptsanarrayofnumbersandaminandmaxvalue. Thefunctionshouldreturnanewarraythatcontainsallofthenumbersintheinputarraythatarebetweenminandmax (including min and max).youcanusetheArray.filtermethodforthis. Wedidn'tusefilterintoday'sclass, butdidinlastWedneday'sclass. Youcanalsosearchfor it on google to see how to use it. You can also write your ownfor loop.sample callsconsole.log(numbsInRange([ 1,2,3,5,8],1,5)); // rturns [1,2,3,5];console.log(numbsInRange([ 1,2,3,5,4],2,5)); // rturns [2,3,4,5];
write a functioncalledcalculateGrade, thattakesanarrayofgrades,suchas [80, 86, 75, 90], andcalculatestheaverageofthegrades.NOTE: average = sumofallofthegrades/numberofgrades.afteryouhavecalculatedtheaverage, determinethelettergradefor that corresponds to the classaverage. Sowewanttoreturntheaveragelettergradeforthetest.0-59: F60-69: D70-79:C80-89: B90-100:AHints: You'llneedtouseanif/elseifblocktotestwhethertheaveragegradeis>= thelowernumberand <=thehighernumberineachrange.console.log(calculateGrade([23,56,78,89,90])); // "D"
write a functioncalledlongestWordthatacceptsastringandreturnsthelongestwordinthestring.samplecallconsole.log(longestWord ("the cow jumped over the moon")); // return "jumped"hints:enter the string in the console and see what it returns. you canalso look up the String.split method on google>"the cow jumped over the moon".split(" ")the functionyouneedtowriteisverysimilartotheonewedidtoreturn the maximum number in an array of numbers. Re-watch that section of the classvideotoseehowwecalculatedthemaxNuminanarrayofnumber.inthiscaseyouneedtostorethelongestwordyou'veseensofarandupdatethatvaluewhenthelengthofthenextwordinthelongestseensofar.