5 Useful Javascript Tricks

Some of these tricks may seem like standard operating fair but remember there was a time you were not aware of some of these javascript features. These are features that when discovered made our lives easier and our love of javascript grow fonder.

1 – Object Destructuring

Sometimes you get very large objects with lots of data thrown at you like event objects with onclick or onchange events or request objects when dealing with http requests.

Object destructuring gives us an easy way to parse properties out of a large object into its own stand alone variable. Here is a video on the subject.

2 – The Ternary Operator

While this is a feature of pretty much all programming languages, it’s great to reduce the bulk of if/else statements for simple processes. Mix this with object destructuring you have a way of switching the value being used by a process between similar objects with ease. Below is a video on the topic.

3 React: Passing components as props

There are many ways to pass down information between components whether it be context, prop drilling, props.children or passing a child component as its own prop (or if needed, you can bring out the big guns and setup redux). Passing down JSX/Components via props can be an awesome way to limit prop drilling in basic situations that don’t warrant context or redux.

Here is a video on the subject

4 Anonymous Functions

Whether it be lambdas in python or arrow functions in javascript, anonymous functions allow us to separate the functions processes from the variable that contains it. So we can create arrays of functions, objects filled with functions. Arrow functions make all of our days better:).

const helloWorld = () => console.log(‘hello world’);

5 filter array method

Sometimes you just need some of the items in an array but you still need the original array so popping, shifting and splicing your away may not be an option, enter the filter method. With filter, you can run a test on all items of an array and return a new array with those that pass the test.

//Find all even items in an array

const newArray = oldArray.filter(value => return value%2 == 0)

Leave a Reply

Your email address will not be published. Required fields are marked *