Functions in JavaScript sharing information? [duplicate]

0

I would like to know if it is possible for two functions in Javascript to share information that is in one of them.

Example:

function a(){
    var nome = prompt("digite seu nome")
}

function b(){
    alert(nome)
}
    
asked by anonymous 27.11.2018 / 06:35

3 answers

3

Responding to the letter to what you said:

  

I would like to know if it is possible for two functions in Javascript to share information that is in one of them.

Yes, it is possible. There are basically two mechanisms for this: scope and return / return values.

Scope Sharing

Each function creates a new scope, and everything that is declared (with var , let , const ) in a scope is not visible outside it:

// aqui é o escopo global
var a = 'escopo global';

function f() {
    // f enxerga o escopo global
    console.log('f enxerga ' + a);

    // f também tem seu próprio escopo
    var b = 'escopo local de f';
    console.log('f enxerga ' + b);
}

// O escopo global não enxerga o escopo local de f
console.log(b); // ReferenceError

Since one function can be declared inside another, this allows you to create a chain of nested scopes . You can explore this mechanism and build your code so you have access where you need it.

Passing and returning values

A function, by definition, is something that gets one value and returns another - although in JS functions can also function as subroutines, not needing to receive or return anything.

When a function will work over a certain value, this value can be passed to it at the time of the call. For example:

function ola(nome) {
    console.log('Olá, ' + nome + '!');
}
ola('Douglas');

It can also return a value:

function ola(nome) {
    return 'Olá, ' + nome + '!';
}

console.log(ola('Douglas'));

Conclusion

Regarding the question code, you can not say anything because it does not show your real intention. The examples here serve as a guide to how things work, and it's up to you to decide which approach to use in each case.

Both solutions seem simple, and actually simple. The hard part is learning how to handle these basic features to make sure the code is clear, readable and modular. This you only learn in practice, and lots of practice.

    
27.11.2018 / 18:44
3

Declare your variable outside the function, making it a global variable that can be accessed and modified from anywhere in the code.

    var nome = "";

    function a(){
        nome = prompt("digite seu nome") }

    function b(){
        alert(nome) 
    }
    
27.11.2018 / 09:46
1

You can call the b function that will return what you typed at the a prompt. This return will be the value of the variable nome in the scope of the a function:

function a(){
   var nome = b(prompt("digite seu nome"));
   console.log(nome);
}

function b(nome){
   alert(nome);
   return nome;
}

a();
    
27.11.2018 / 06:49