skip to Main Content

I’m following an online Javascript course for beginners. One exercise is about Math.floor(), and the example given is:

get floorNum(x){
    let _x = x;
    _x = Math.floor(x);
    return _x;
}

My question is: why not just put "return Math.floor(x)" in the function body? Why let _x = x, and then return _x? Why not just return x directly? What’s the underlying logic?
I want to learn some basic programming logic.

I tried google, but didn’t find what I want. I’m an absolute beginner.

5

Answers


  1. You are right!, there are no reason to do this 8n this example.

    you can write it like this

    function floor(x) {
    return Math.floor(x)
    }
    

    but keep in mind that this technique is useful when working with cloned classes, objects.

    Login or Signup to reply.
  2. Try like this:

    _x = x => Math.floor(x);

    Login or Signup to reply.
  3. Actually in js we can declare a variable starting with _.
    According to my intuition they might have used _ for just to represent the word floor.
    There’s no any restriction to write or declare variables in such a way.

    Login or Signup to reply.
  4. This also works fine.

    get floorNum(x){return Math.floor(x);}

    I think they coded that way, to understand easily.
    And they used the underscore ( _ ) to indicate that a variable name can start with ( _ ) sign too.

    Login or Signup to reply.
  5. Let’s do it step by step :

    get floorNum(x){
        // Here you are duplicating the argument (supposing it's a number)
        let _x = x;
        // Here you are reassigning the previous variable, making the first line useless
        _x = Math.floor(x); 
        return _x;
    }
    

    As the first line is useless, your code could be refactored to this:

    get floorNum(x){
        const _x = Math.floor(x); 
        return _x;
    }
    

    And as you’re not doing anything with _x except returning it, then it can be refactored again to:

    get floorNum(x){
        return Math.floor(x);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search