Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The programming logic

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.

like image 677
Angus Avatar asked Aug 08 '26 20:08

Angus


2 Answers

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);
}
like image 191
Guerric P Avatar answered Aug 11 '26 08:08

Guerric P


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.

like image 34
Nmeer Naji Avatar answered Aug 11 '26 10:08

Nmeer Naji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!