DEV Community

Abhinav Vp
Abhinav Vp

Posted on • Updated on • Originally published at abhinavvp.com

Another 4 JavaScript tips for shorter code

This is a continuation to my earlier article : 4 JavaScript tips for shorter code


1. Replace Switch or If-Else with key value pairs

The switch statement and if-else statement evaluates an expression and executes statements associated with that case. But as the number of cases increases the code grows as well.

function returnDaySwitch(val) {
      switch (val) {
         case 1:
            return "It's monday";
         case 2:
            return "It's tuesday";
         case 3:
            return "It's wednesday";
         case 4:
            return "It's thursday";
         case 5:
            return "It's friday";
         case 6:
            return "It's saturday";
         case 7:
            return "It's sunday";
         default:
            return "Enter a value between 1 - 7";
      }
   }
function returnDayIfElse(val) {
    if(val==1){
        return "It's monday";
    }else if(val==2){
        return "It's tuesday";
    }else if(val==3){
        return "It's wednesday";
    }else if(val==4){
        return "It's thursday";
    }else if(val==5){
        return "It's friday";
    }else if(val==6){
        return "It's saturday";
    }else if(val==7){
        return "It's sunday";
    }else{
        return "Enter a value between 1 - 7";
    }
}
const day = 3;
console.log(returnDaySwitch(day)); //It's wednesday
console.log(returnDayIfElse(day)); //It's wednesday
Enter fullscreen mode Exit fullscreen mode

This can be made simpler by using key-value pairs of an object.

 

function returnDayKeyValue(val) {
    const returnDayObject = {
        1: "It's monday",
        2: "It's tuesday",
        3: "It's wednesday",
        4: "It's thursday",
        5: "It's friday",
        6: "It's saturday",
        7: "It's sunday",
    }
    if(!returnDayObject[val]){
     return "Enter a value between 1 - 7";
    }
    return returnDayObject[val]
}
cosnt day = 3;
console.log(returnDayKeyValue(day)); //It's wednesday
Enter fullscreen mode Exit fullscreen mode

@lukeshiru gave some tips on how to make it more shorter

const dayToString = day =>
    ({
        1: "It's Monday",
        2: "It's Tuesday",
        3: "It's Wednesday",
        4: "It's Thursday",
        5: "It's Friday",
        6: "It's Saturday",
        7: "It's Sunday",
    }[day] ?? "Enter a value between 1 - 7");
Enter fullscreen mode Exit fullscreen mode

Or

const dayToString = day =>
    [
        undefined,
        "It's Monday",
        "It's Tuesday",
        "It's Wednesday",
        "It's Thursday",
        "It's Friday",
        "It's Satuday",
        "It's Sumday",
    ][day] ?? "Enter a value between 1 - 7";
Enter fullscreen mode Exit fullscreen mode

2. Remove duplicate elements in an array

Duplicate elements in an array can be removed by Set constructor and spread syntax. Set constructor converts an array into a set which cannot have duplicate elements. Spread syntax can be used to convert the set object back to an array.

const array = [1,2,2,3,4,5]
const uniq = [...new Set(array)];
console.log(uniq) // [1,2,3,4,5]
Enter fullscreen mode Exit fullscreen mode

3. Computed property names

You cannot set object keys as variables directly. It will read the variable names as key names

const key1 = "name";
const key2 = "age";
const student = {
    key1:"john Doe",
    key2:26
}
console.log(student)
//{ key1:"john Doe", key2:26 }
Enter fullscreen mode Exit fullscreen mode

Starting with ECMAScript 2015, you can put an expression in brackets [], that will be computed and used as the property name.

 

const key1 = "name";
const key2 = "age";
const student = {
    [key1]:"john Doe",
    [key2]:26
}
console.log(student)
//{ name:"john Doe", age:26 }
Enter fullscreen mode Exit fullscreen mode

4. Prevent falsey value from evaluating to false

There are six falsey values in JavaScript: undefined, null, NaN, 0, "" (empty string), and false. A falsy value is something which evaluates to FALSE, for instance when checking a variable. There could be scenarios where you wont want any falsy value to evaluate to false.

const number = 5;
if(number){
    console.log('The number exists')
}else{
    console.log('The number do not exist')
}
Enter fullscreen mode Exit fullscreen mode

Will print The number exists. But

const number = 0;
if(number){
    console.log('The number exists')
}else{
    console.log('The number do not exist')
}
Enter fullscreen mode Exit fullscreen mode

Will print The number do not exists. This can be handled by giving an exception at the evaluation

const number = 0;
if(number===0?true:number){
    console.log('The number exists')
}else{
    console.log('The number do not exist')
}
Enter fullscreen mode Exit fullscreen mode

@lukeshiru came to the rescue again simplifying it further in case if you are checking a number

const number = 0;

console.log(
    typeof number === "number"
        ? "The number exists"
        : "The number do not exist",
);
Enter fullscreen mode Exit fullscreen mode

Will print The number exists. 0 at the expression can be changed with any of the falsy values.

Top comments (1)

Collapse
 
abhi_vp_ profile image
Abhinav Vp

Whoa these are so good. Appreciate a lot for taking the time and effort for this. I'll add this to the post.