CodeGuy
CodeGuy

Reputation: 5

How can I use variables from another function in javascript

I cant have access to my variables from my function UserInfo all my variables are undefined. How can I have access to my variable and display them in my function seeInfoUser

let UserName;
let UserAge;
let UserBirthPlace;
let UserDream;  

let UserInfo = function(){
  let UserName = prompt("What is your name:");
  let UserAge = prompt("How old are you: ");
  let UserBirthPlace = prompt("Where were you born: ")
  let UserDream = prompt("What is your Greatest Dream: ");
}

let seeInfoUser = function (){              
  let UserInformation = ` ${UserName} is  ${UserAge} and he was born in ${UserBirthPlace} and his greatest dream is ${UserDream}`
  return UserInformation
}

let result = seeInfoUser(UserInfo());
console.log(result)

Upvotes: 0

Views: 47

Answers (2)

Scott Marcus
Scott Marcus

Reputation: 65808

You are re-declaring your variables in UserInfo which causes them to hide the ones already declared in a higher scope. Just remove the let keyword on the variable assignments inside the function so that, instead of re-declaring smaller scoped variables, you use the already declared ones.

// These variables will be available in the current scope and descendent scopes
let UserName;
let UserAge;
let UserBirthPlace;
let UserDream;  
    
let UserInfo = function(){
  // ...So, don't re-declare the variables - just use them!
  UserName = prompt("What is your name:");
  UserAge = prompt("How old are you: ");
  UserBirthPlace = prompt("Where were you born: ")
  UserDream = prompt("What is your Greatest Dream: ");
}
    
let seeInfoUser = function (){
  // You really don't need to declare a variable if all you are going to do is return its value
  return ` ${UserName} is  ${UserAge} and he was born in ${UserBirthPlace} and his greatest dream is ${UserDream}`;
}
    
let result = seeInfoUser(UserInfo());
console.log(result)

Upvotes: 3

J. Pichardo
J. Pichardo

Reputation: 3115

The issue with your code is the scope of the variables. In javascript, all variables declared with let have block scope. And you are redeclaring them inside your UserInfo function, so you should just use the variables you had already declared.

let UserName;
let UserAge;
let UserBirthPlace;
let UserDream;


let UserInfo = function() {
  UserName = prompt("What is your name:");
  UserAge = prompt("How old are you: ");
  UserBirthPlace = prompt("Where were you born: ")
  UserDream = prompt("What is your Greatest Dream: ");
}

let seeInfoUser = function() {

  let UserInformation = ` ${UserName} is  ${UserAge} and he was born in ${UserBirthPlace} and his greatest dream is ${UserDream}`

  return UserInformation
}



let result = seeInfoUser(UserInfo());
console.log(result)

Upvotes: 1

Related Questions