R.App
R.App

Reputation: 69

Passing value from inside of function to a parameter in JavaScript

I have a function that replaces characters from a string

function ratko(a) {
    var k = a.toString();
    var z = k.replace(/\,/g, '], [');
    var s = z.replace(/\./g, ', ');
    var final = "[[" + s + "]]";
    alert(final);
}

What I need is to get the value of final outside the function like this:

var outsideValue = final;

EDIT!!! --

function ratko() gets it's value from ajax

success: function (data) {
if (data.success) {
alert("Note: This month has " + data.holidays.length + " holidays.");
praznici = data.holidays;
ratko(praznici);
}
else {
alert(data.ErrorMessage);
}

Upvotes: 1

Views: 83

Answers (4)

alessio271288
alessio271288

Reputation: 358

you must be modify your function code like this

function ratko(a) {
  var k = a.toString();
  var z = k.replace(/\,/g, '], [');
  var s = z.replace(/./g, ', ');
  var final = "[[" + s + "]]";
  //alert(final); comment this code line and replace this with the code above
  return final;
}

after you can call your function ratko with this simple code

var inputValue = 'simple message';
var parsedValue = ratko(inputValue);

you find the final value into a new variable parsedValue

Upvotes: 0

Samson
Samson

Reputation: 2821

You declare it outside the function scope:

  var finalVar;

function ratko(a) {
var k = a.toString();
var z = k.replace(/\,/g, '], [');
var s = z.replace(/./g, ', ');
 finalVar= "[[" + s + "]]";
alert(finalVar);
}

var outsideValue = finalVar;

Beware final is a reserved keyword in Javascript. I changed its name. Besides that, keep in mind that Javascript is always parsed from top to bottom. So using a variable before declaring it will definitely give you an undefined.

Upvotes: 0

cih
cih

Reputation: 1980

One option would be to use a global variable, just declare it outside of the function.

var myvar = 1;
function myFunction()
   alert(myvar); // 1
}

You can read more on javascript variables here.

Upvotes: 0

JohnB
JohnB

Reputation: 13713

Possibility 1:

function ratko (a) {
   ...
   return final;
}

var outsideValue = ratko (...);

Possibility 2:

var final;
function ratko (a) {
   // no var final declaration here
   ...
}
...
ratko (...);
// now final has the value assigned to it in the function

You can access variables declared in an outer scope in an inner scope, which is what you do in Possibility 2.

Upvotes: 1

Related Questions