Home > Software engineering >  how can i make every if is running out separately
how can i make every if is running out separately

Time:03-28

function age(firstnum) {
    if (typeof firstnum === "number") {
        return firstnum = firstnum * 12;

    }
    if (typeof firstnum === "number") {
        return firstnum = firstnum * 30;

    }
}
console.log(age(15));
console.log(age(15))

**I want to make the code work in a separate way and also in the same function**

CodePudding user response:

You can use a constructor function and inside of it you can create other functions to do the job


function getAge(){
    
    this.ageOne = function(age){
        return age * 12;
    }
    
    this.ageTwo = function(age){
        return age * 30
    }
    
}

const myAge = new getAge();

console.log(myAge.ageOne(15))
console.log(myAge.ageTwo(15))

CodePudding user response:

Your function returns the value if the first condition is met.

You would use an early return if you want to check for a number or return something else if it is not a number, for example:

function age(firstnumber) {
    if (typeof firstnumber=== "number") {
        return firstnumber* 12 * 30; 
    } else {
        return "not a number"
    }
}
console.log(age(15));
console.log(age("abc"));

Result:

5400
"not a number"

I suggest using better variable names. The function age does not tell us what the function is doing. The variable name firstnumber is not telling us what the number is all about.

An alternative could be to use two functions (as indicated by @webCatDev in their getAge function) - simpler code below:

function age1(firstnum) {
    if (typeof firstnum === "number") {
        firstnum = firstnum * 12;

    }
    return firstnum
}

function age2(firstnum) {
    if (typeof firstnum === "number") {
        firstnum = firstnum * 30;
    }
    return firstnum
}
console.log(age1(15));
console.log(age2(15));

Again, tell us what the goal is.

CodePudding user response:

This can achieve this behavior with a closure for a static counter:

const age = (() => {
    let counter = 1;
    return function (firstnum) {
          counter;
        if (counter % 2 === 0 && typeof firstnum === "number") {
            return firstnum = firstnum * 12;
        }
        if (counter % 2 === 1 && typeof firstnum === "number") {
            return firstnum = firstnum * 30;
        }
    }
})();
console.log(age(15));
console.log(age(15));

You can also add the temporary result to the closure:

const age = (() => {
    let counter = 1;
    let temp = null;
    return function (firstnum) {
        if (temp === null) temp = firstnum;
          counter;
        if (counter % 2 === 0 && typeof firstnum === "number") {
            return temp = temp * 12;
        }
        if (counter % 2 === 1 && typeof firstnum === "number") {
            return temp = temp * 30;
        }
    }
})();
console.log(age(15));
console.log(age(15));

  • Related