24

Here are 2 functions in the simplest form. I'm working with jquery.

What is the best way to pass var str from the first function to the second one?

function a() {
    var str = "first";
};

function b() {
    var new = str + " second";
};
0

3 Answers 3

35

You need to either pass it between them, or it seems from your example, just declare it in a higher scope:

var str;
function a(){
  str="first";
}
function b(){
  var something = str +" second"; //new is reserved, use another variable name
}
Sign up to request clarification or add additional context in comments.

9 Comments

@Nick I like passing them around better than leaving them out in the open for others to modify.
@Jacob - You're assuming a has anything to do with b though, it could just be a() in one place, possibly never even called, then b() in another.
Man, it's really hard to decide which one of these answers to go with. Both are very, very valid given various uses, and there's no way to tell given the sparse details from the OP.
The module pattern allows you to do this while still keeping the 'str' variable protected from outside editing. Quick example of a shared var: jsfiddle.net/Ma8Hs
@Jacob, from this very limited example it's hard to see the OP's intended use of the variable. Choosing whether to pass as an argument, or declaring at a high scope, or even b.call(new String(str)) for arguments sake, really depends on the situation...
|
34

Use function parameters, like this:

function a() {
   var str = "first";
   b(str);
}

function b(s) {
   var concat = s + " second";
   //do something with concat here...
}

You could just declare a variable higher up in the scope chain, but I opt to use arguments to restrict variable access to only the contexts that absolutely need it.

Oh yeah, isn't that called the principle of least privilege?

Comments

2

i use..

 function a(){
 let str = "first";
 localStorage.setItem('value1', `${str}`);}

 function b(){
 let str = localStorage.getItem('value1');
 let new = str + " second";}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.