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
You are right!, there are no reason to do this 8n this example.
you can write it like this
but keep in mind that this technique is useful when working with cloned classes, objects.
Try like this:
_x = x => Math.floor(x);
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.
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.
Let’s do it step by step :
As the first line is useless, your code could be refactored to this:
And as you’re not doing anything with
_x
except returning it, then it can be refactored again to: