6 JavaScript Tips and Tricks
Below are just a few quick tips and tricks to have handy when working with JavaScript and I hope they prove helpful in a project or a future lab for upcoming Flatiron students!
- Using Array.from() to create strings or create unique arrays!
This neat little method has a few useful uses to create new arrays but in so many different ways! Below are just two of the several ways you can utilize it. The rest can be found on: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from
-Create an array with a string:
-Create a Unique Array when there’s repeated values in the original array using ‘new Set’:
2. Using the Ternary Operator in place of ‘if/else’ statements:
To simply your code when writing if/else statements and have it looking cleaner with a shortcut, the Conditional Ternary Operator is your solution! The operator takes three operands(objects or inputs), evaluates a condition, and executes a block of code based on that condition.
3. Dynamic Objects:
Square brackets are used to create dynamic values in objects.
4. Slicing arrays from the beginning or from the end:
You can easily slice an array by assigning a new numerical value for its length, and then return the altered array, but keep in mind that this method is destructive UNLESS you assign it to a new variable name first as seen in the array end splice example.
To slice the array from the end, use the .slice method and include a negative number in parenthesis to return the values starting from the end.
5. Converting an array into an object:
Using the spread operator in curly brackets {…} with the array to convert will return that array as an object. (Make sure to to set everything to a new variable.)
6. Converting an object into an array:
Using the capitalized Object along with calling dot notation on either the ‘keys’ or ‘values’ followed by the array name as an argument will return the object values in an array.
Googling tips and finding out all the useful ways to get around JavaScript can be an exciting journey because it’s like finding little treasures to utilize in your code. You’ll never know when you’ll need these!