0

Beginner here. Why userName is undefined in the function and how to make the function to have it as John Doe and not undefined?

const userName = 'John Doe';
console.log(userName);
const loggedInUser = (userName) => console.log('Logged in user is: ' + userName);
loggedInUser();

Console output:

index.js:22 John Doe
index.js:23 Logged in user is: undefined
Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
Steve Waters
  • 2,977
  • 8
  • 43
  • 86
  • 1
    You're hiding the "outer" `userName` with the `userName` parameter of the function. – Andreas Feb 04 '18 at 09:19
  • 2
    [An example of variable shadowing in javascript](https://stackoverflow.com/questions/11901427/an-example-of-variable-shadowing-in-javascript) – Andreas Feb 04 '18 at 09:26
  • FWIW, this is not a property, it's a "variable" though it would be more correct to say that it is a constant (since its value cannot change). – Felix Kling Feb 05 '18 at 03:33

1 Answers1

1
const loggedInUser = (userName) => console.log('Logged in user is: ' + userName);

defines a function named loggedInUser that takes a single argument.

After defining this function you call it on the next line loggedInUser();, but you don't provide the argument.

Try loggedInUser(userName);

Daniel
  • 9,741
  • 12
  • 40
  • 75