How to access a variable from another function?

Asked

Viewed 73 times

-1

Talk guys, found a difficulty, beginner in JS.

I have 2 functions:

function getHeight() {
var tdHeight = document.querySelector(".info-altura").textContent;
console.log(tdHeight);
}


function getWeight() {
var tdWeight = document.querySelector(".info-peso").textContent;
console.log(tdWeight);;
}

Now I created a q will take the result of the function getWeight and getHeight to make a calculation, but returns me Undefined.

function calcImc() {
var resultImc = tdWeight / (tdHeight * tdHeight);
console.log(resultImc);
}

2 answers

2

Hello ! In the above code, you make a console.log with the values you took. Try to re-turn the values instead of the console.log.

The variable created in the context of the function exists only in the context of the function. What you can do is replace 'console.log' with 'Return' and instead of calling the variables created in the functions, call the function itself, it will return the value.

  • 1

    Hi Giovane, all right? I tried to add a "Return tdHeight" and still can’t access

  • 1

    worked, thanks!

1


In javascript we have the scopes of variables, we should keep in mind that we should:

1) restrict to the maximum the use of that scope, but what that scope is?

The global scope is where you can have variables loose inside the file as for example:

let minhaVariavel = 'variavel global'

always remember to declare your variables with Let as this is the newest way the language has implemented for some troubleshooting improvements.

we also have the function scope, we have the variables within a function and the same will only be seen within it, this would be the most correct way to work but not the only, ex:

function minhaFuncao() { 
   let minhaVar = 'variável de função é local' 
   return minhaVar
}

to solve the problem that in reality is a solution we can return in each function the value and then add all.

const tdHeight = function() {
    return "alguma coisa"
}

const tdWeight = function() {
    return "mais outra coisa"
}
const result = function(){
    return tdHeight() + tdWeight()
}

console.log(result())

another output would be to assign global variables

let tdHeight
let tdWeight

function getHeight() {
	tdHeight = "alguma coisa"
}

function getDWeight() {
    tdWeight = "mais outra coisa"
}
const result = function(){
    return tdHeight + tdWeight
}
getHeight()
getDWeight()
console.log(result())

  • thanks for the detailed explanation!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.