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.
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With