Javascript - Refactoring if..else statements (ES6)

javascript if statement multiple conditions
refactoring if statements
alternative to if statement javascript
multiple if statements javascript
if statement with array javascript
python refactor if else
es6 if statement
javascript if else

I am trying to refactor if..else statements.

My code:

let condition = 'hi';

if(condition === 'hi'){
  commonFunction('hi');
  console.log('hi is called');

}else if(condition === 'bye'){
  commonFunction('bye');
  console.log('bye is called');

}else if(condition.includes('happy')){
  commonFunction('happy');
  console.log('happy is called');

}else if(condition === 'greeting'){
  commonFunction('greeting');
  console.log('greeting is called');

}

Refactored Code:

if(condition === 'hi'){
  hi();
}else if(condition === 'bye'){
  bye();
}else if(condition.includes('happy')){
  happy();
}else if(condition === 'greeting'){
  greeting();
}

function hi(){
  commonFunction('hi');
  console.log('hi is called');
}

function bye(){
  commonFunction('bye');
  console.log('bye is called');
}

function happy(){
  commonFunction('happy');
  console.log('happy is called');
}

function greeting(){
  commonFunction('greeting');
  console.log('greeting is called');
}

Is it better to declare each functions by condition like my refactored code???

Or, How about make class and call commonFunction by constructor? (I think switch..case is not useful becasue I have a condition that has includes() )


One thing can do about that is declare the function in an object using the condition as keys.

let objFunc = {
    'hi': function() {
       commonFunction('hi');
       console.log('hi is called');
    },
    'happy': function() {
       commonFunction('happy');
       console.log('happy is called');
    },
    'bye': function() {
       commonFunction('bye');
       console.log('bye is called');
    },
    'greeting': function() {
       commonFunction('greeting');
       console.log('greeting is called');
    },
};


objFunc[condition]();

5 Tips to Write Better Conditionals in JavaScript ― Scotch.io, When working with JavaScript, we deal a lot with conditionals, here are the 5 1 if/else statement that filter out invalid condition; 3 levels of nested if For the example above, we can actually refactor our code to achieve the  To execute no statements, use an empty statement. statement2 Statement that is executed if condition is falsy and the else clause exists. Can be any statement, including block statements and further nested if statements. Description. Multiple ifelse statements can be nested to create an else if clause.


One option would be to use an object containing functions, rather than having multiple standalone functions. Then, just use property lookup.

For this exact code, though, you could make it even DRY-er by using a Proxy to check which property was accessed, rather than having multiple properties (because all of your properties/functions have common functionality):

const condition = 'hi';

const fns = new Proxy({}, { get: (_, prop) => {
  console.log(prop + ' is called');
}});

const props = ['hi', 'bye', 'greeting'];
if (condition.includes('happy')) {
  fns.happy();
} else if (fns[condition]) {
  fns[condition]();
}

Refactoring the if Condition, Since values in JS evaluate to true or false. You can shorten your condition in the `if` statement. Remember my Falsy Values post last week. This is where it  In JavaScript we have the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true Use else to specify a block of code to be executed, if the same condition is false


In your original code you have written multiple if else statement just to call same function with different pre-defined argument, so instead of refactoring by your way, i think this is much easier and small code.

let predefinedArgs = {
    hi: 'hi',
    bye: 'bye'
    ...
}

let condition = 'hi'
commonFunction(predefinedArgs[`condition`]);

Tips to write better Conditionals in JavaScript, We normally use switch statements to avoid large if else if statements. However view raw switch-statement.js hosted with ❤ by GitHub With the introduction of ES6 Array functions, we can avoid using them 95% of the time. The statements if and else in javascript means exactly what they sound like, if something is true do this, or else do something else. Both these statements are used very often in the language in order to control programs data flow.


You have a set of conditions for which you want to call a common function. The best way to do this is simply test whether you can handle the condition (that's where you can use includes). Then call that function.

const allowed = ['hi', 'bye', 'happy', 'greeting']

let condition = 'happy'

if (allowed.includes(condition)) {           // do you know how to deal with condition? 
  commonFunction(condition)                 // if so call the function
} else {
  console.log(`unknown condition ${condition}`) // otherwise log an error
}

// not sure what commonFunction does, so this is just for the example
function commonFunction(condition) {
  console.log(`${condition} is called`);
}

The Art of Refactoring: 5 tips to Write Better Code, This operator is frequently used as a shortcut for the if statement. Syntax: condition ? exprIfTrue : exprIfFalse. Example: Show a message to  The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions.


I'd suggest to move all these if-elses into commonFunction itself (if it does not contain the same if-elses again, if it does you need more complex refactoring):

const commonFunction = (condition) => {
  let f = ['hi', 'bye', 'happy', 'greeting'].find(e => condition.includes(e))
  console.log(f + ' is called');
  if (!f) return;
  // do something
  // return the result if needed
}

commonFunction('greeting')
commonFunction('die')

Refactor Code By Using the Ternary Operator in JavaScript, First, meet the if statement replacement, the ternary operator: condition else { return customer } }. // ES6 style custom formatted ternary magic If you chain many if else statements, the code will become hard to read and difficult to maintain. In such situations, you should use the switch statement. JavaScript if else shortcut: conditional operator. JavaScript provides a conditional operator or ternary operator that can be used as a shorthand of the if else statement.


Rethinking JavaScript: The if statement, When you need to set a condition for a value or a function in JavaScript, the first things you try are if/else and switch. It looks like that: let foo = ''  To do so, we are using the conditional statements inside the render block in react application. This tutorial explains how to perform conditional rendering in react & react native application using simple if and else statement and ternary expression. As you already know, the React Native uses JSX which is a syntax extension to JavaScript.


An alternative to if/else and switch in JavaScript, I've had this personal mantra saying “Avoid if..else..else if statements and Haskell has pattern matching, we don't have that in Javascript. I think I can still refactor my boolean evaluation. ES6 Cool stuffs — A big fat Arrow. Python Tutorial for Beginners [Full Course] Learn Python for Web Development - Duration: 6:14:07. Programming with Mosh Recommended for you


Javascript: Path to eliminating If/else - Frontend Weekly, Statement that is executed if condition is falsy and the else clause exists. Can be any statement, including block statements and further nested if  Refactoring If-Else and Switch Statements The notion of code smells is often brought up when talking about refactoring. Code smells are somewhat of a gut-check for your code; if you have a “smelly” block of code, it probably needs some refactoring.