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";
};
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";
};
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?
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
}
i use..
function a(){
let str = "first";
localStorage.setItem('value1', `${str}`);}
function b(){
let str = localStorage.getItem('value1');
let new = str + " second";}