Home > Web Front-end > JS Tutorial > body text

Avoid using too many if statements in JS scripts. Here are 6 ways to replace if.

青灯夜游
Release: 2020-11-09 17:59:46
forward
3000 people have browsed it

Avoid using too many if statements in JS scripts. Here are 6 ways to replace if.

Recommended tutorial: "JavaScript Video Tutorial"

When I was refactoring the code recently, I found that the early code used too many if statements to a degree I have never seen before. That’s why I think it’s important to share these simple tips that can help us avoid using too many if statements.

Next we will introduce 6 ways to replace the use of if. This is not to be paranoid about not using if, but to change it. way to think about our coding ideas.

1. Ternary operator

Example 1

Code with IF:

function saveCustomer(customer) {
  if (isCustomerValid(customer)) {
    database.save(customer)
  } else {
    alert('customer is invalid')
  }
}
Copy after login

Refactored code:

function saveCustomer(customer) {
  return isCustomerValid(customer)
    ? database.save(customer)
    : alert('customer is invalid')
}
Copy after login

Using ES6

const saveCustomer = customer =>
   isCustomerValid(customer)?
     database.save(customer) : alert('customer is invalid')
Copy after login

Example 2

Code with IF:

function customerValidation(customer) {
  if (!customer.email) {
    return error('email is require')
  } else if (!customer.login) {
    return error('login is required')
  } else if (!customer.name) {
    return error('name is required')
  } else {
    return customer
  }
}
Copy after login

Refactored code:

const customerValidation = customer =>
  !customer.email   ? error('email is required')
  : !customer.login ? error('login is required')
  : !customer.name  ? error('name is required')
                    : customer
Copy after login

Example 3

Code with IF:

function getEventTarget(evt) {
    if (!evt) {
        evt = window.event;
    }
    if (!evt) {
        return;
    }
    const target;
    if (evt.target) {
        target = evt.target;
    } else {
        target = evt.srcElement;
    }
    return target;
}
Copy after login

Refactored code:

function getEventTarget(evt) {
  evt = evt || window.event;
  return evt && (evt.target || evt.srcElement);
}
Copy after login

2. Short-circuit operator

Example 1

Code with IF:

const isOnline = true;
const makeReservation= ()=>{};
const user = {
    name:'Damian',
    age:32,
    dni:33295000
};

if (isOnline){
    makeReservation(user);
}
Copy after login

Refactored code:

const isOnline = true;
const makeReservation= ()=>{};
const user = {
    name:'Damian',
    age:32,
    dni:33295000
};

isOnline&&makeReservation(user);
Copy after login

Example 2

Code with IF:

const active = true;
const loan = {
    uuid:123456,
    ammount:10,
    requestedBy:'rick'
};

const sendMoney = ()=>{};

if (active&&loan){
    sendMoney();
}
Copy after login

Refactored code:

const active = true;
const loan = {
    uuid:123456,
    ammount:10,
    requestedBy:'rick'
};

const sendMoney = ()=>{};

active && loan && sendMoney();
Copy after login

3. Function delegate:

Case 1

Code with IF:

function itemDropped(item, location) {
    if (!item) {
        return false;
    } else if (outOfBounds(location) {
        var error = outOfBounds;
        server.notify(item, error);
        items.resetAll();
        return false;
    } else {
        animateCanvas();
        server.notify(item, location);
        return true;
    }
}
Copy after login

Refactored code:

function itemDropped(item, location) {
    const dropOut = function() {
        server.notify(item, outOfBounds);
        items.resetAll();
        return false;
    }

    const dropIn = function() {
        server.notify(item, location);
        animateCanvas();
        return true;
    }

    return !!item && (outOfBounds(location) ? dropOut() : dropIn());
}
Copy after login

Everyone said that there is no project to write on the resume, so I found a project for everyone and also included a [Building Tutorial].

I cooperate with Alibaba Cloud on the server, and the discounted price is relatively cheap: 89/year, 223/3 years, which is cheaper than 9.9 per month for students. I bought it to build a project, and it is more comfortable to be familiar with the technology stack (for old users) Just buy it with a family account. I use my mother's recommendation to buy it for three years. You can check it out by clicking on this article.

4. Non-branching strategy

This technique tries to avoid using switch statements and instead create with key/value A map and uses a function to access the value of the key passed as an argument.

Example 1

Code with switch:

switch(breed){
    case 'border':
      return 'Border Collies are good boys and girls.';
      break;  
    case 'pitbull':
      return 'Pit Bulls are good boys and girls.';
      break;  
    case 'german':
      return 'German Shepherds are good boys and girls.';
      break;
    default:
      return 'Im default'
}
Copy after login

Refactored code:

const dogSwitch = (breed) =>({
  "border": "Border Collies are good boys and girls.",
  "pitbull": "Pit Bulls are good boys and girls.",
  "german": "German Shepherds are good boys and girls.",  
})[breed]||'Im the default';


dogSwitch("border xxx")
Copy after login

5. Function as data

We know that function is the first class in JS, so using it we can split the code into a function object.

Code with IF:

const calc = {
    run: function(op, n1, n2) {
        const result;
        if (op == "add") {
            result = n1 + n2;
        } else if (op == "sub" ) {
            result = n1 - n2;
        } else if (op == "mult" ) {
            result = n1 * n2;
        } else if (op == "p" ) {
            result = n1 / n2;
        }
        return result;
    }
}

calc.run("sub", 5, 3); //2
Copy after login

Refactored code:

const calc = {
    add : function(a,b) {
        return a + b;
    },
    sub : function(a,b) {
        return a - b;
    },
    mult : function(a,b) {
        return a * b;
    },
    p : function(a,b) {
        return a / b;
    },
    run: function(fn, a, b) {
        return fn && fn(a,b);
    }
}

calc.run(calc.mult, 7, 4); //28
Copy after login

6. Polymorphism

Polymorphism is the ability of an object to have multiple forms. The most common use of polymorphism in OOP is using a parent class reference to refer to a child class object.

Code with IF:

const bob = {
  name:'Bob',
  salary:1000,
  job_type:'DEVELOPER'
};

const mary = {
  name:'Mary',
  salary:1000,
  job_type:'QA'
};

const calc = (person) =>{

    if (people.job_type==='DEVELOPER')
        return person.salary+9000*0.10;

    if (people.job_type==='QA')
        return person.salary+1000*0.60;
}

console.log('Salary',calc(bob));
console.log('Salary',calc(mary));
Copy after login

Refactored code:

const qaSalary  = (base) => base+9000*0.10;
const devSalary = (base) => base+1000*0.60;

//Add function to the object.
const bob = {
  name:'Bob',
  salary:1000,
  job_type:'DEVELOPER',
  calc: devSalary
};

const mary = {
  name:'Mary',
  salary:1000,
  job_type:'QA',
  calc: qaSalary
};

console.log('Salary',bob.calc(bob.salary));
console.log('Salary',mary.calc(mary.salary));
Copy after login

Original text: https://dev.to/damxipo/avoid-use- if-on-our-js-scripts-1b95

Author: Damian Ciplat

For more programming-related knowledge, please visit: Programming Course ! !

The above is the detailed content of Avoid using too many if statements in JS scripts. Here are 6 ways to replace if.. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!