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";
};
peterh
  • 11,875
  • 18
  • 85
  • 108
Hussein
  • 42,480
  • 25
  • 113
  • 143

3 Answers3

35

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?

Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
34

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
}
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 1
    @Nick I like passing them around better than leaving them out in the open for others to modify. – Jacob Relkin Jan 05 '11 at 03:15
  • 1
    @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. – Nick Craver Jan 05 '11 at 03:16
  • 1
    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. – Phrogz Jan 05 '11 at 03:21
  • The module pattern allows you to do this while still keeping the 'str' variable protected from outside editing. Quick example of a shared var: http://jsfiddle.net/Ma8Hs/ – david Jan 05 '11 at 03:21
  • @david - true, but you'd have to proxy the functions outside, creating a closure so *they* can be accessed, complicated things a bit :) – Nick Craver Jan 05 '11 at 03:22
  • 1
    @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... – David Tang Jan 05 '11 at 03:24
  • @Nick, it's only complex if you say it out loud >.> – david Jan 05 '11 at 03:25
  • What happens if we are referencing $(this) in var str. Will that still work in function b and retain the value of this that was referenced in function a. – Hussein Jan 05 '11 at 03:27
  • @alex - it depends on where the functions are called from, `this` will refer to the current context, but what that is depends on how they're called – Nick Craver Jan 05 '11 at 03:28
2

i use..

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

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