Ebook Exploring Javascript Array Methods

Download as pdf
Download as pdf
You are on page 1of 34
Your guide to JavaScript's most common array methods: ForEach Map Filter Reduce Some Every Find vein CONTENTS 1 € Google Developer Expert Hithere! I'm Todd Motto? - author of this eBook and founder of Ultimate Courses’ ‘This eBook is my minimal guide for you to learn some of JavaScript’s most popular array methods: + ForEach + Map + Filter + Reduce + Some + Every + Find You're about to explore the syntax, function signatures, use cases, how to remember, my tips and tricks - sprinkled amongst examples that will teach you the fundamentals you need to master these array methods and remember them forever. Whether you're a beginner or senior JavaScript developer, I’m sure you'll find lots of useful content inside. Please tweet me and let me know? you enjoy the eBook! PS. I would highly encourage you to check out my expert JavaScript courses* 'm building over on Ultimate Courses - they'll teach you so much more! the right way! Sed Learn JavaScript at hitpe:/altimstecourses.com "pel tetarcon/tadaaoto °bttpedtuzateconree com 2attped/twittercom/teddenotto “tpe/atuastcoueercom/oouseedvarcipt Contents Array ForEach . . . What is Array ForEach? Using Array ForEach Bonus: ForEach-ing without ForEach Summary Array Map... . What is Array Map? Using Array Map Bonus: Map-ing without Map Summary Array Filter... . What is Array Filter? Using Array Filter Bonus: Filter-ing without Filter Summary Array Reduce ... What is Array Reduce? Using Array Reduce Reducing an Array of Numbers Reducing an Array of Objects Bonus: Reduce-ing without Reduce Summary Array Some . What is Array Some? Using Array Some Bonus: Some-ing without Some Summary Array Every... . What is Array Every? Using Array Every wards u 12 1B 3B 15 6 7 7 18 18 19 20 20 an 22 23 24 24 5 CONTENTS Bonus: Every-ing without Every Summary Array Find... What is Array Find? Using Array Find Bonus: Find-ing without Find Summary 26 27 28 28 30 31 Array ForEach the right way! Sed Learn JavaScript at hitpe:/ultimstecourses.com What is Array ForEach? Array ForEach is a method that exists on the Array prototype that was introduced in ECMAScript 5 (ES5) and is supported in all modern browsers. Array ForEach is the entry-level loop tool that will iterate over your array and pass you each value (and its index). You could render the data to the DOM for example. ForEach, unlike other array methods, does not return any value ‘Think of Array ForEach as: “I want to access my array values one-by-one so I can do something with then” Here's the syntax for Array ForEach: array forEach((value, index, array) => {...}, thieArg); ForEach is also considered a “modern for...in loop” replacement, despite behaving differently and having less flexibility. ForEach doem’t allow us to break the loop or even loop backwards, which may be a common scenario you'll run into - so it’s certainly not a flat-out replacement. However, i’s a pretty standard approach nowadays. Array ForEach syntax deconstructed: «+ ForEach’s first argument is a callback function that exposes these parameters: ~ value (the current element) ~ index (the element’s index - fairly commonly used) ~ array (the array we are looping - rarely used) Asrty ForBach 3 ~ Inside the body of the function we would access value and do something with us, sum values, inject template into the DOM, anything you like + Every’s second argument thisArg allows the this context® to be changed See the ECMAScript Array ForEach specification In its simplest form, here is how ForEach behaves: [lat (bt, to! 'a!] forEach( function(item, index) { console.log(item, index); Ys We would then see something like this being printed out in the console (note the index number too) Accessing each array clement, and its index, couldn't be easier! Once your array has been ‘looped’, ForEach will exit and your JavaScript program will continue. Using Array ForEach Here's our data structure that we'll be using Array ForEach with (we'll be using this same array throughout this series) const iteme = [ (id | mame: ‘Super Burger’, price (id | name: ‘Jumbo Fries', price: {ia | name: ‘Big Slurp’, price Li Let’s move to a more realistic scenario - we want to display the details of each array object to the user, the id, nane and price! We can construct a new <1i> template for each array element, and inject it into the DOM: "iatpe itasteconees con/ blog wadersanding the thie keyword- im javascript “eatped/ta®euecrnasa/ osc array prototype foreach Asrty ForBach 4 const app = document .querySelector('#app" ); items. forEach( item = { app. innerHIM. + ar S{item.id) ${item.nane) - ${(item.price / 100).tFixed(2)} sp Ys Nicely done, Rendering the data to the DOM is a great use case for ForEach, notice how we also do not return anything as well (which we will have to with most other array methods in this series) Give the live Array ForEach demo’ a try. Bonus: ForEach-ing without ForEach Let’s check out a for. .in loop example that mimics the behaviour of Array ForEach: const app = document .querySelector( app" ); for (let i = 0; i < items length; i++) { const item = items[i]; sep. innerHIML += ~ ar S{item id) ${item name) - ${(item-price / 100).toFixed(2)} “ap; } Both achieve the identical output, it’s merely how we compose the code. Whilst technically the ForEach method on JavaScript arrays is more “fimctional” style, it does not retu anything - therefore cannot be chained as part of a series of operators that transform data, for example .nap())-filter() which we'll learn about shortly. ForEach is a nice and clean API and should be thought about as a one-way street. Here, I'm simply using it to render, there is no further action taking place and I get no return value from the method call. We can also loop backwards and have the flexibility to break with the for. . .in loop. Using ForEach or the newer for. .of is preferred for simple looping. Tipeacicoaleie nase Asrty ForBach 5 Summary You've now leamed how to use Array ForEach to loop over your array elements and render some data. ForEach is a great place to get started with JavaScript loops. Moving from a traditional for... in loop, the ForEach method can be introduced to bring a more functional approach and style to your programming, If you're enjoying this series, please keep following! To learn more JavaScript practices at this level and comprehensively, I've put together some online videos that explore the entire JavaScript language and the DOM - I'd encourage you to check them out if you are serious about JavaScript Further tips and tricks: + ForEach is great for simple looping as it doesn’t return any values + You cannot break or continue items inside a ForEach + You cannot ForEach in reverse, use for... in or for. ..of + You can access the array you're looping in the third argument of the callback + You can change the this context via a second argument to . farEach(cal back, thisArg) s0 that any references to thie inside your callback point to your object + You can use arrow functions with ForEach but remember that this will be incorrect if you also supply a thisArg due to arrow functions not having a thie context + Using ForEach will skip empty array slots + You shouldn’t need to in this day and age of evergreen browsers, but use a polyfill for older browsers if necessary "ped tumatecoures con/coumealeraacap Array Map the right way! Sey Learn JavaScript at hitpe:/ultimstecourses.com What i Array Map? Array Map is a method that exists on the Array.prototype that was introduced in ECMAScript 5 (ES5) and is supported in all modem browsers. Array Map allows us to loop our array, access each value and return a new value for each iteration - which in tum creates a new array. ‘Think of Array Map as: “I want a new array containing new copies, or changes, of each array clement” You could, for example, use Map to return a specific property from an object, which would result in an array of just those properties in the order your looped them. Here's the syntax for Array Map: const returnValue = array.map((value, index, array) => {...}, thisArg); Our returniVaiue will contain our new array of, potentially new, retum values. Array Map syntax deconstructed: + Map'sfirt argument is 4 callback function that expotes these parameters: ~ index (the element’s index - sometimes used with Map) ~ array (the array we are looping - rarely used) ~ Inside the body of the function weneed to return a value, this could be your array element, a modified version of it, or a completely new calculated value, this will then tell Map what Jo retumy after completing theo + Map! SOd AS Sea ee IMSTSER the this context to be changed See the ECMAScript Array Map specification”! "atpe atteconees con blog wadersanding the thie keyword- tm javascript AMatpe/ toe alecnatea oee- aay PONY MAD Ansty Map 7 In its simplest form, here is how Map behaves const mapped = [1, map((x) => x * 2); // (2, 4, 6, 8, 10} console. log( mapped); Ym using x to identify whatever the value is and simply multiplying it by 2, giving us a new array of exactly each number doubled from the previous array. The original array would remain untouched and stil accessible. W's common to deal with all kinds of data with Map, as Arrays allow any value type, from primitive values through to Objects - giving us great programming flexibility. So that’s the basics of Map, let’s take a look at a more real-world scenario where we've tasked with mapping an Array of Objects. Using Array Map Here’s our data structure that we'll be using Array Map with: const iteme = [ (id | mame: ‘Super Burger’, price: 399 }, {ia | name: ‘Jumbo Fries', price: (id: 4", name: ‘Big Slurp', price hs Let’s assume we've just applied a coupon which applies HALF OFF our ‘Jumbo Fries’. We'd need to loop through our data and update that specific object Here’show we could solve that via Map by conditionally retuming a new representation of the item object, with an updated price, otherwise we just return the item bo a 12 Ansty Map 8 const hal fOffFries = items.map(item => { if (itemid === '@") { return { item, price: item.price / 2 h } return item; Ys Jog the return value console. log(hal f0f#Fries); Using Array Map is an immutable pattern as it creates anew array from an existing array. We are also using the ... spread operator to return a new object instead of mutating the existing one, Both operations do not mutate existing data structures and are considered immutable ways of achieving state change. ‘This would then give us some half price fries (which can only be good news) fe (id | mame: ‘Super Burger’, price (id | name: ‘Jumbo Fries', price: (id: 'g', name: 'Big Slurp', price } Interestingly, our original itens array remains unmodified, and we have a new collection to deal with now in our hal 0¢¢Fries variable. This practice is called an immutable operation as we don’t mutate the initial array. Give the live Array Map demo" a try. Bonus: Map-ing without Map Let’s check out a for...in loop example that mimics the behaviour of Array Map: ack cee const hal f0f¢Frie 1 us for (let i = 0; i < items length; i++) { 4 const item = items[i]; 5 if (item id === '@') { 6 hal f0ffFries.push({ 1 item, 8 price: item.price / 2 9 Yd; 10 J else { 4 hal fOFfFries.push(item); 2) 1} First we dedlarehal for¢Fries as an empty array. Inside the loop we use pretty much the same logic, but instead of a return statement we use the Array prototype push method which adds each item to the new hal f0¢¢Fries array. Once the loop as finished, you're free to work with your new hal £0¢¢Fries array. This also demonstrates us the power and flexibility of using Map and other array prototype methods ‘The code is far smaller, promotes beiter practices, is easier to read and far more contained Summary You've now leamed how to use Array Map to map your array to anew set of values. Map is the next best place to begin after getting started with aay ForEach, Moving from a traditional for... in loop, the Map method can be introduced to bring a more functional approach and style to your programming, If you are serious about your JavaScript skills, your next step is to take a look at my JavaScript courses", they will teach you the full language, the DOM, the advanced stuff and much more! Further tips and tricks: + Use Map to create a new collection with changed values of your initial collection + Don’t forget to return or your values will be undefined + Map will shallow copy your object references into the new array + Don’t encourage bad habits by using -map() over -forEach( ) just because it can have the same effect and is ‘shorter’ - use the right tool for the right job or you will confuse people! "ped umateconres com/cowmeal avait Ansty Map 10 + You can access the array you're looping in the third argument of the callback + You can change the this context via a second argument to .nap(cal lback, thisArg) so that any references to thie inside your callback point to your object + You can use arrow functions with Map but remember that this will be incorrect if you also supply a thisArg due to arrow functions not having a thie context + Like ForEach and friends, you cannot Map in reverse or break a Map, use for... .in or for...of + Using Map will skip empty array slots + You shouldn’t need to in this day and age of evergreen browsers, but use a polyfill for older browsers if necessary Array Filter the right way! Sey Learn JavaScript at bitpr/fltimatecourses.com What is Array Filter? Array Filter is a method that exists on the Array prototype that was introduced in ECMAScript 5 (ES5) and is supported in all modern browsers. Array Filter allows us to conditionally retum certain elements fom our array, into a new array. I's commonly used to remove items from an array by excluding them from the result. ‘Think of Array Filter as: “Iwant a new array containing just the items Ineed” With each iteration of a Filter loop, you will need to return an expression that Filter evaluates either true oF fales. ‘The key to understanding Filter is to realise your callback is returning an expression that will evaluate to true or falee. Array elements that evaluate to true are stored in a new array - and items that evaluate to false are excluded. Once Filter has completed, you can access the new array of your values. Here's the syntax for Array Filter: const returnValue = array.filter((value, index, array) => {...}, thistra): Our returnValue will contain our new array of filtered retum values. Array Filter syntax deconstructed: + Filter’s first argument is a callback fimction that exposes these parameters: ~ value (the current element) ~ index (the element’s index - sometimes used with Filter) Arty Filter 2 ~ array (the array we are looping - rarely used) ~ Inside the body of the fimction we need to return an expression which will evaluate to a Boolean (true or false) «+ Filter’s second argument thieArg allows the this context" to be changed See the ECMAScript Array Filter specification In its simplest form, here is how Filter behaves: const array = [true, true, false]; // ftrue, true] console. log( array. filter(Boolean)); Array Filter expects us to return an expression that will evaluate true or false, we can go straight to the finish line and make it easier by supplying literally true and false array values. Tm using JavaScript’s Boolean object to coerce the array clement to a Boolean. As our array already contains Boolean values, any false values are omitted. Notice how Filter is also returning multiple values, compared to its closely related sibling method Array Find. Using Array Filter Here’s our data structure that we'll be using Array Filter with: comt ites = [ { id) '@", name: ‘Super Burger’, price {ia {ia 1: ane: ‘Jumbo Fries', price: ane: 'Big Slurp’, price. Here let’s assume we want to create a new array of more expensive items in this array, we can consider “expensive” to be 199 and above. Let’s return an expression now that compares each item’s price property with greater than > 199, which aims to filter out values that aren’t considered expensive "tps ltataconees col bog walaraanding the thie keyword- in javascript ‘Muttpe//to alecratsaoec-azay prototype Aer Arty Filter 1B const expensiveltems = items filter(iten => item.price > ‘This would then give us the two items that are considered “expensive” based on our 199 threshold value: | mame: ‘Super Burger’, price | name: 'Big Slurp’, price Interestingly, our original itens array remains unmodified, and we have a new collection to deal with now in our expeneiveltens variable, This practice is called an immutable operation as we don’t mutate the initial array. Give the live Array Filter demo" a try. Bonus: Filter-ing without Filter Let’s check out a for...in loop example that mimics the behaviour of Array Filter: const expensiveltens = []; for (let i const item 5 i < items length; i++) { toms[i]; 4 expensiveltems.push( item); } } if (item.price > 199: First we declare expensiveltens as an empty array. Inside the loop we use pretty much the same logic, but instead of a return statement we use the Array .prototype.push method which adds each item to the new expensiveltons array. Once the loop as finished, you're free to work with your new filtered array. Summary You've now leaned how to use Array Filter to filter your array to a specific set of values. You can think of Filter of like a functional “if statement”, If my array clement meets my criteria - give it to us... Ese, we don’t want it "pel etackbita com itje Bias Arty Filter 4 If you are serious about your JavaScript skills, your next step is to take a look at my JavaScript courses", they will teach you the full language, the DOM, the advanced stuff and much more! Further tips and tricks: «+ Filter can be used to return specific values from a source array + Don’t forget to return or your values will be undefined which coerces to false (60 an undetected bug could be introduced!) + The easiest way to get all truthy values in the array is by using . fi 1ter(Boolean) + Don’t forget to return or your values will be undefined + Filter will shallow copy your object references into the new array + Filter is also similar to Find, but for multiple items! + You can access the array you're looping in the third argument of the callback + You can change the thie context via a second argument to . filter(cal lback, thistrg) £0 that any references to thie inside your callback point to your object + You can use arrow functions with Filter but remember that this will be incorrect if you also supply a thisArg due to arrow functions not having a thie context, + Using Filter will skip empty array slots + You shouldn’t need to in this day and age of evergreen browsers, but use a polyfill for older browsers if necessary Array Reduce the right way! Sed Learn JavaScript at hitpe:/altimstecourses.com What is Array Reduce? Array Reduce is a method that exists on the Array prototype that was introduced in ECMAScript 5 (ES5) and is supported in all modem browsers. Array Reduce is the most misunderstood array method and a headache for many developers - if only they'd read this article! Pay close attention to the little details and you'll succeed with Reduce. The concept of Reduce itself isn’t complex, but the method is just a little different to others that we're used to. ‘Think of Array Reduce as: “Iwant to reduce my array to just a single value” Array Reduce is commonly used for performing things such as math expressions and equations, for instance calculating the total of a numbers array. You'll have likely heard the term “Reducer” before when dealing with things such as Redux” or NGRK", a Reducer also is a “Reduce”, returning a single value inside a snitch statement. Here's the syntax for Array Reduce: const redusedValue = array.reduce((prev, next, index, array) => {...}, initialValue); Our reducedVaiue will contain our reduced value, this is typically a number - however you can compose objects and arrays inside your Reduce, that’s more of an advanced use case though. Tpeliedaceorg Matpe//taatecores comers ore effecte Arty Reduce 16 + Reduce’s first argument is a callback function that exposes these parameters: ~ prev (sometimes called ace for “accumulator” as the value is dynamic, it accumulates the callback’s value and is returned on the next iteration as prev) ~ next (the current clement, sometimes called value) ~ index (the element’s index - not commonly used with Find) ~ array (the array we are looping - rarely used) ~ Inside the body of the fimction we need to return an expression which is then passed to the next iteration as prev - Reduce essentially remembers the value from each iteration and Keeps providing you it until your array completes + Reduce’s second argument is different to other Array method counterparts we've explored so far, instead of thieArg it’s initial Value - allowing us to specifiy an optional initial value for theloop to begin (which gets passed in asprev on the first iteration of the loop, with next being the first array value) + IMPORTANT: Ifno initial Value is set, Reduce will use your first array value as the prev on the first iteration - technically starting the loop on the second array element See the ECMAScript Array Reduce specification"! In its simplest form, here is how Reduce behaves: const reduced 46 reduce((prev, next) => prev + next, 0); console. log( reduced); Simple enough, right? Even if we don’t “get it” right away, we can add up 4, 2,3, 4, 6 to reach a comfortable 16 - so we're half way there to understanding Reduce. When Reduce begins the initialValue (here it’s 0) becomes the first prev value and next is our first aay value of 1. If there was no initial value then prev would be (first array value) and next would be2 (second array value). ‘These small differences in how Reduce behaves with and without an initialValue likely also contributes to reasons to not fully understanding Reduce Developers, like I did, struggled at first with this whole prev and next thing. So let’s use a really simple demonstration to make sure we get it "pelea alacant dome aay rotype sete Arty Reduce 7 const reduced 1, 2, 3, 4, 8] reduce((prev, next) => { console. log(prev, next); return prev + next; }, 0; Outputs in the console (each iteration): eo 4 initial value, 4 = first array item 12 previous result (0+ 1) 2 = second array item a4 previous result (1 +2) 3 = third array item 64 previous result (3+ 3) 4 = fourth array item 10 6 previous result (6+ 4) 6 = fifth array item ‘This now explains why we get 15 as a return value (10 + 6)- there is no next value in our array so Reduce will exit and return that final value to our recuoed variable. We've only considered numbers at this point, however as Reduce retumns any value type, it has very flexible use cases! You could retum flattened Arrays, concatenated Strings, new or merged Objects - or whatever else you can come up with! ‘That’s the basics of Reduce, let’s take a look at a more real-world scenario where we've tasked with calculating the sum from Objects - there are multiple approaches I'm also going to show you. Using Array Reduce Here's our data structure that we'll be using Array Find with: const iteme = [ { id: 'Q", name: ‘Super Burger’, price: 399 }, { id: '@", nme: ‘Jumbo Fries', price: 199 }, {id 4") name: ‘Big Slurp’, price: 299 } Ih; Let’s calculate the total price of all price properties. Reducing an Array of Numbers A basic Reduce will sum an array of numbers, so let’s add an Array Map before to return us just each price property - giving us an array of numbers to then Reduce Arty Reduce 18 const reduced = items map(iten => item.price) reduce((prev, next) => prev + next); / Total: 8.97 console. log( found); ‘This is a perfectly decent example, and completes the mission we set out to achieve to calculate the total price, However, Reduce offers us a really nice way to work with Objects - which involves the use of the initial Value property. Reducing an Array of Objects By supplying an initialValue the prev value becomes 0 to begin the Reduce, This works nicely when adding + to our next. price: const reduced = items reduce((prev, next) => prev + next.price, 0); // Total: 8.97 console. log( reduced); If we didn’t supply @ we would log Total: NaN because we'd be attempting to add an Object to a number property! It also saves us another Array Map, keep the code alittle deaner and more efficient Give the live Array Reduce demo a try. Bonus: Reduce-ing without Reduce Let’s check out a for...in loop example that mimics the behaviour of Array Reduce: Tape ack comledije exbaad Arty Reduce 19 let reduced; let prev initialValue for (let i const next O; i < items length; i+) { toms[i]; prev = prev + next.price; } reduced = prev; First we dedare recuoed and prev to assign an initialValue of @ just like Reduce, From there, ‘welll loop our itens and create a next variable, We then re-assign prev each time and add + our ext price to it Once the loop as finished, I've assigned prev to reduced to act like Reduce’s final return value. Summary You've now leamed how to use Array Reduce to reduce your array to just a single value, Array Reduce is a nice and compact way that we can dedaratively reduce an array and return any kind of value we'd like, More advanced use cases include composing Objects and Arrays inside your Reduce, but welll save them for another time. If you are serious about your JavaScript skills, your next step is to take a look at my JavaScript courses”, they will teach you the full language, the DOM, the advanced stuff and much more! Further tips and tricks: + Remember to specify an initialValue when dealing with an Array of Objects + Reducing Arrays of Numbers is nice and clean, try not to overcomplicate your Reduce functions - this is a common pattern I've seen + Don’t forget to return inside your callback, or your values will be undefined and evaluate to falee - avoid undetected buge! + You can access the array you're looping in the third argument of the callback + You can change the thie context via a second argument to .reduce(cal lback, thistrg) s0 that any references to thie inside your callback point to your object + You can use arrow functions with Every but remember that thie will be incorrect if you also supply a thisArg due to arrow functions not having a thie context + Using Find will skip empty array slots as if it were a falsy value + You shouldn’t need to in this day and age of evergreen browsers, but use a polyfill for older browsers if necessary Tip tumatecoures com/coumea avast Array Some the right way! Sey Learn JavaScript at hitpe:/altimstecourses.com What is Array Some? Array Some is a method that exists on the Array prototype that was introduced in ECMAScript 5 (ES5) and is supported in all modern browsers. Array Some tells you whether any element in your array passes your test. If one element passes then Array Some retums true. Some will return false ifno elements pass the test. ‘As soon as Some finds a true result, it will short-circuit the loop and continue no more - giving us a performance boost. ‘Think of Array Some as: “I want to check if any value(s) in my array meets my condition - a yes/no answer” Here's the syntax for Array Some: const returnValue = array.some((value, index, array) {..}, thistre); Our returnValue will contain a Boolean value true or false. ‘As Someretums a Boolean, its result is commonly used in conditional statements. Array Some syntax deconstructed: + Some’s first argument is a callback function that exposes these parameters: ~ value (the current element) ~ index (the element’s index - sometimes used with Filter) ~ array (the array we are looping - rarely used) ~ Inside the body of the fimction we need to return an expression which will evaluate to a Boolean (true or false) Arty Some 21 + Some’s second argument thisArg allows the this context” to be changed See the ECMAScript Array Some specification”! In its simplest form, here is how Some behaves: 1 const greaterThanOne = [1, 2, 2] .come(x => x > 4 © console. log( greater ThanOne ); ‘As our array contains values greater than > 1, our expression evaluates to true, and Some returns true. Similarly, with an expression that checks if our values are greater than > 2, Some will return false 4 const greaterThanthree = sone(x => x > 9); © console. log(greaterThanthres); ‘As a performance benefit, Some will short-circuit and stop the loop on a true test result, otherwise it wil continuously loop if results are fale until the loop exits Let’s check some examples out Using Array Some Here's our data structure that we'll be using Array Some with (take note of the additional prono property): 1 const items = [ (id | mame: ‘Super Burger’, price promo: false }, es tia ; name: 'Jumbo Fries', price: 199, promo: false }, a Cid | mame: 'Big Slurp’, price: 209, promo: true} els Let’s use Some to check if any items are in the promo - we should expect to see our Big Slurp ' trigger Some to retum true: "Tetpe/taateconres col blog/walarsating the thie keyword- in javascript ated toe elecnatea oec-ezay POtype cme Arty Some 22 const isInPromo = itene cone(item => item.prono); console. log isInProno); Using a temary statement to calculate our total - if an item is in the promo we set the price to a flat 600 cents. Otherwise we'll use Array Reduce to sum the price properties: 1 const total = isInPromo 7 600 : items reduce((prev, next) => prev + next price, 0); Our example here is simple, but real enough. You can see how we've used the ieInProno resulting variable as part of a conditional statement - where it’s most commonly used! Notice how simple Some is, we're returning item promo (either true or falee) to get a final true result as one item matched our conditional test. You can retumm any type of expression inside Some’s callback fumction (such as using comparison logic item price > 99) Give the live Array Some demo” a try, you can toggle promo: true to prono: false and see the result change. Bonus: Some-ing without Some Let’s check out a for...in loop example that mimics the behaviour of Array Some: 1 let isInProno = false; S for (let i = 0; i < items. length; i+) { 4 const item = itenslil; if (item.promo) { 6 isInPromo = true; First we set isInPromo to false and it’s our job to detect when to set it to true. We'll loop the items and if one passes, we set isInPromo to trus. This is the same behaviour as Some, and if no items match then isInPromo will remain false. TT peraenecaalney Arty Some 23 Summary You've now leamed how to use Array Some to run a test on your array elements. If at least one clement in your array, when returned as part of an expression, evaluates to true then Some will exit the loop and return true Ino array elements pass the test Some will return false. No array items are retumed back to you, Some is exclusively for returning a Boolean result. If you do want items back, Array Map and Array Filter are better methods to use, If you are serious about your JavaScript skills, your next step is to take a look at my JavaScript courses", they will teach you the full language, the DOM, the advanced stuff and much more! Further tips and tricks: + Don’t forget to return inside your callback, or your values will be undefined and evaluate to fale - avoid undetected buge! + You can access the array you're looping in the third argument of the callback + You can change the this context via a second argument to .sone(callback, thisArg) so that any references to thie inside your callback point to your object + You can use arrow functions with Some but remember that this will be incorrect if you also supply a thisArg due to arrow functions not having a thie context + Using Some will skip empty array slots as if it were a falsy value + You shouldn’t need to in this day and age of evergreen browsers, but use a polyfill for older browsers if necessary Epitome Array Every the right way! Sey Learn JavaScript at hitpe:/altimstecourses.com What is Array Every? Array Every is a method that exists on the Array prototype that was introduced in ECMAScript 5 (ES5) and is supported in all modern browsers. Array Every tells you whether every element in your array passes your test. every clement passes, Every retums true. If just one element in the array fails, Every wil retum false ‘As soon as Every finds a false result, it wil short-circuit the loop and continueno more - giving us a performance boost. ‘Think of Array Every as: “Iwant to check if every value in my array meets my condition - a yes/no answer” Here's the syntax for Array Every: const returnValue = array.every((valus, index, array) = {...}, thisArg); Our returnValue will contain a Boolean value true or false. ‘As Every retums a Boolean, its result is commonly used in conditional statements. Array Every syntax deconstructed: «+ Every’s first argument is a callback function that exposes these parameters: — value (the current element) ~ index (the element’s index - not commonly used) ~ array (the array we are looping - rarely used) ~ Inside the body of the fimction we need to return an expression which will evaluate to a Boolean (true or falee), this will then tell Every what to return after completing the loop Amey Every 25 «+ Every’s second argument thisArg allows the this context” to be changed See the ECMAScript Array Every specification”! In its simplest form, here is how Every behaves: const isEveryValuefrus = [true, true, true] -every(Boolean); console. log(isEveryValueTrue); ‘As our array contains true values, our expression evaluates to true and Every returns true, Using JavaScript’s Bool ean object we coerce each result to a Boolean, essentially running an “all-true” check on the array. Boolean is actually a fimetion and typically called as Boolean([1, 2, 3]) to coerce any JavaScript value to a true or false value. Similarly, by induding a false value, Every will retum fale: const isEveryValuefrus = [false, true, true] every(Bcolean); console. log(isEveryValuefrue); ‘As our array contains a falee value, it will trigger Every to return false. As a performance benefit, Every will short-circuit and stop the loop on a falce test result Let’s check some examples out Using Array Every Here's our data structure that we'll be using Array Every with (take note of the additional stock property): "tet ateconres col blog walersnting the thie keyword- in javascript Mutpe//teo alecnatsaoec-azay rottype every Arrty Every 26 const items (id ane: 'Super Burger’, price: 399, stock: true }, (id ane: ‘Jumbo Fries', price: 199, stock: true }, {ia ane: 'Big Slurp’, price. stock: falee } Li Our Jumbo Fries, are out of stock based on the stock: falee property. If an item is out of stock, then we'll show a message in the console const isInSteck = items.every((item) => item stock); console. log(isInStock ); if (ListnStock) { console.log( “Sorry, ${itens. find(iten } item stock).name} is cut of Stock.~); Our example here is simple, but real enough. You can see how we've used the isInstock resulting variable as part of a conditional statement - where it’s most commonly used! Notice how simple Every is, we're returning item. stock (either true or falee) to get a final false result. You can return any type of expression inside Every’s callback fimetion (such as using comparison logic item price > 99) Give the live Array Every demo” a try, you can toggle etock: true to stock: falee and see the result change. Bonus: Every-ing without Every Let’s check out a for... in loop example that mimics the behaviour of Array Every: "ied etek come wrod Arrty Every 27 let ielnStock = true; for (let i = 0; i < items length; i++) { const item = items[i]: if (Jitem stock) { isInStock = false; break; } } First we set isInStock to true, and we need to disprove otherwise, We'll loop the items and if one fails, we set istnStock to falce. This is the same behaviour as Every, even though we're inverting the conditional statement. Summary You've now leamed how to use Array Every to rm a test on your array elements, If at least one clement in your array, when returned as part of an expression, evaluates to fale then Every will exit the loop and return fales. Fall array elements pass the test Every will return true. ‘No array items are retumed back to you, Every is exclusively for returning a Boolean result. If you do want items back, Array Map and Array Filter are better methods to use, If you are serious about your JavaScript skills, your next step is to take a look at my JavaScript courses”, they will teach you the full language, the DOM, the advanced stuff and much more! Further tips and tricks: + Don’t forget to return inside your callback, or your values will be undefined and evaluate to fale - avoid undetected buge! + You can access the array you're looping in the third argument of the callback + You can change the this context via a second argument to .every(cal lback, thisArg) so that any references to thie inside your callback point to your object + You can use arrow functions with Every but remember that thie will be incorrect if you also supply a thisArg due to arrow functions not having a thie context + Using Every will skip empty array slots as if it were a falsy value + You shouldn’t need to in this day and age of evergreen browsers, but use a polyfill for older browsers if necessary Paipeintnasecourerconloomed want Array Find the right way! Sed Learn JavaScript at hitpe:/ultimstecourses.com What i Array Find? Array Find is a method that exists on the Array prototype that was more recently introduced in ECMAScript 2015 (ES6) and is supported in all modern browsers. Array Find searches your array and retums you the first matching clement, or undefined. Find’s return value is dynamic and could be of any JavaScript type that exists in your array, a string, number, object etc. ‘Think of Array Find as: “Iwant to find a particular element in my array” In ways, Array Find is similar to Array Filter, however returns just the first result, whereas Filter ‘would return you as many results that satisfy the test! Here's the syntax for Array Find: const foo = array. find((value, index, array) => {...}, thisArg); ‘The value const foo will contain any element from your array, and therefore it could be of any value type. Array Find syntax deconstructed: + Find’ fist gzgument is callback fimction that exposes these parameters: ~ index (the element's index -not commonly used with Find) ~ array (the array we are looping - rarely used) ~ Inside the body of the fimction we need to return an cores w which will evaluate to a lean (¢rue or false), this will then tell E etprn leting the] = Find se Signs PE AAES Wows Me ine von oe A Sheahan geet MPLA the loop See the ECMAScript Array Find specification! "Rape taatecoues com log/walerending the thie keyword- in javascript atpe//toe elecmatea/oec-ezay prototype ind Arty Find 2» In its simplest form, here is how Find behaves: const found 'a!] find(x = x === '3"); console. log( found); Find will retum us a “shallow copy” of ‘a’ - which is always the case with any value in our array. We are always passed a copy rather than a direct reference - which helps us mitigate potential bugs. It will also return undefined if, for example with the value 'e', the result does not exist in the aray: const notFound = ['a', 'b!, ‘o!, ‘d!] find(x => x // undefined console. log(notF ound); ei ‘As Find retums any value type, it has very flexible use cases! You could return Booleans, Strings, Objects, Arrays to any degree - but a common use case could be finding an object inside an array by supplying an ID to lookup the object with. We could, for example, then use the return value to pethaps update that particular element or send it to a server. ‘As soon as Find successfully ‘finds’ a first clement match, it will retum it to you - s0 keep this in mind when dealing with duplicate array items, as you will only get one result back from Find. Find will also loop in ascending order, so there should be no surprises Using Array Find Here’s our data structure that we'll be using Array Find with: const items (id pane: ‘Super Burger’, price (id ane: ‘Jumbo Fries', price: {ia ane: 'Big Slurp’, price. Li We could find any item we like, via any of the properties available. Let’s use Find to find an item based on it’s id property: Arty Find 30 const found = items. find( (item) 1 (id: '@', rane: 'Junbo Fries’, console. log( found); ‘As found could also contain undefined, it’s best practice to safety check the variable in some way: const found = items. find( (item) => item.id if (found) { Jumbo Fries 1.99 console. log(“${found.nane} ${(found.price / 100).teFixed(2)}*); } Nicely done, Ifthe item is available, let’s do something with the data! Notice how simple Find is, we're simply returning item i once it matches. and we immediately get it back Give the live Array Find demo” a try. Bonus: Find-ing without Find Let’s check out a for...in loop example that mimics the behaviour of Array Find: // cundefined” by default let found; for (let i = 0; i < items length; i++) { const item = items[i]; if (itemid === '@') { found = item; break; } } First we declare let found and do not assign a value, Why? Because by default, it’s undefined - you can explicitly assign it if you like, though. Inside the loop, we then find the item and assign it to the found variable, and break the loop - giving us a nice imperative “find” solution, Tape ‘Arrey Find 31 Summary You've now leamed how to use Array Find to grab any particular element you want in your array, in any way you want to find it. Array Find is a nice and compact way that we can declaratively search through an array and get a copy of the first matched clement. Remember as well, Find is similar to Filter! Filter just gives you all results ifthey match, rather than the first result only. If you are serious about your JavaScript skills, your next step is to take a look at my JavaScript courses", they will teach you the full language, the DOM, the advanced stuff and much more! Further tips and tricks: + Don’t forget to return inside your callback, or your values will be undefined and evaluate to fale - avoid undetected buge! + You can access the array you're looping in the third argument of the callback + You can change the this context via a second argument to .find(callback, thistrg) so that any references to thie inside your callback point to your abject + You can use arrow functions with Find but remember that this will be incorrect if you also supply a thisArg due to arrow functions not having a thie context + Using Find will skip empty array slots as if it were a falsy value + You shouldn’t need to in this day and age of evergreen browsers, but use a polyfill for older browsers if necessary Tipe tamateconres comlconmealevaacap

You might also like