Where I write code.

Thursday, 10 January 2019

Mastering in Javascript | Conditionals

Mastering in Javascript:

As a JavaScript developer, we have to handle multiple conditions to match our requirements.
So here are some better ways to handle conditionals.

Using Array.every for conditioning object array elements:

This will is a common condition to check the object array contains the same value for value or not for a key, so lets take an example as follows:

const jar = [
    { name: 'orange', color: 'orange' },
    { name: 'apple', color: 'red' },
    { name: 'guava', color: 'green' }

function check() {
  let isAllRed = true;

  // condition: all fruits must be red
  for (let f of jar) {
    if (!isAllRed) break;
    isAllRed = (f.color == 'red');

  console.log(isAllRed); // false

mastering in javascript

If you see the code we have to check whether each array element color is red or not.
So we did the loop on each element and added the flag to check whether its true or not, but the code is so long, we can reduce it using Array.every() function.

function check() { const isAllRed = jar.every(fruit => fruit.color == 'red'); console.log(isAllRed); // false } check();

Much easier and cleaner right? 

Using Array.some for conditioning object array elements:

Now, let's take above example, you have to check whether jar contains red color or not so you can easily write that condition with the following code.
function check() {

  const isAllRed = jar.some(fruit => fruit.color == 'red');

  console.log(isAllRed); // true

Much easy right?

Using Array.includes for Multiple Criteria

if you want to check multiple conditions like if the fruit is apple or banana etc then we use the following statements to check.

function test(fruit) { if (fruit == 'apple' || fruit == 'strawberry') { console.log('red'); } }

if you see the code you are checking with apple and banana only what if you have to add more fruits to check then again you have to add more || operator right?

So let's use Array.includes to handle this condition.

function test(fruit) {
  // extract conditions to array
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];

  if (redFruits.includes(fruit)) {
isn't it easy and maintainable? We can extract the element from an array.

That's it for this post.

let's master in javascript by reading more contents if you want to master in javascript then click here to read my all posts.

Thanks and comment if you want to some clarifications. 

Link for more info for this topic: click here

No comments:

Post a comment