Search code examples
javascriptfunctionreturn

Basic issue when attempting to return the input variable value back to its initial global variable


I have the following problem which consists of failure in returning the variable values that are being used as an input parameter in a function.

The function, by itself, works perfectly fine.

But it fails to deliver the modified values back to its global variables for further use after being calculated within the function... and I cannot figure out a dynamic way to make this work.

This is the code I am using right now:

var $value_1 = "100.000"; // Initial Value
var $value_2 = "200.000"; // Initial Value
var $value_3 = "300.000"; // Initial Value

function_1($value_1); // Expected: "100.00"
function_1($value_2); // Expected: "200.00"
function_1($value_3); // Expected: "300.00"

// Failure in returning any values back to its variable despite being calculated in the function
alert($value_1); // Actual: "100.000"
alert($value_2); // Actual: "200.000"
alert($value_3); // Actual: "300.000"

function function_1($recieved_raw_value) // Example: "500.000" becomes "500.00"
        {
            var $parts = $recieved_raw_value.split('.');
            var $loc = $parts.pop();
            var $before_text = $parts.join('.');

            var $after_text = $recieved_raw_value.split('.').pop();

            if($after_text.length > 2) {
                $after_text = $after_text.slice(1,3);

                $recieved_raw_value = $before_text + "." + $after_text;
            } else {
                $recieved_raw_value = $before_text + "." + $after_text;
            }
            return $recieved_raw_value; // Not working to any of the 3 variables...
        }

Solution

  • Try $value_1 = function_1($value_1);

    Returning data doesn't alter the input variable you have to assign it.

    Or if you really want to edit the global (I would advise against it since it's generally bad practice) in the function instead of returning anything just do...

    $value_1 = $recieved_raw_value