JavaScript Set and Math.max for Code Efficiency

Small JavaScript language features that can save several lines of code. new Set() Set is a collection of unique values (it does not allow duplicates). const numbers = [1, 2, 2, 3, 4, 4] const unique = new Set(numbers) // [1, 2, 3, 4] Very useful for removing duplicate values from arrays in a quick and readable way. It also allows some operations such as: // Adds the value set.add(value) // Checks if the value exists set.has(value) // Deletes the value set.delete(value) --- Math.max() Used to find the largest number among the given values. Math.max(10, 5, 8) // 10 With an array and the spread operator: const numbers = [10, 5, 8] Math.max(...numbers) // 10 --- Putting both together. const numbers = [1, 5, 5, 3, 9, 1] // Removes duplicates and gets the largest value in a single line. const maior = Math.max(...new Set(numbers)) // 9 #JavaScript #TypeScript #WebDevelopment #FrontendDevelopment #ProgrammingTips #CleanCode #CodeQuality #SoftwareDevelopment #DevTips #LearnToCode #100DaysOfCode

  • No alternative text description for this image

Please update the image. You are spreading the Set into an array so “unique” becomes an array and you can’t use Set methods.

Like
Reply

To view or add a comment, sign in

Explore content categories