-1

When I pass a string to a function as a parameter, it returns undefined. Why is that?

let a = 'b';

let test = (a) => console.log(a);

test(); // undefined
Runtime Terror
  • 6,242
  • 11
  • 50
  • 90
  • The `a` from the parameter list shadows the higher scoped `let a = 'b'`. Read how scoping works in JavaScript in the linked duplicate. – Madara's Ghost Jan 07 '17 at 21:27

2 Answers2

2

Why is that?

Because you don't pass any argument. Try the following:

test(a);

The following definition:

let test = (a) => console.log(a);

is like the following:

function test(a){
    console.log(a);
}

So when you call test, without passing any argument the value of a would be undefined.

Christos
  • 53,228
  • 8
  • 76
  • 108
2

When you call test(); you aren't putting anything between ( and ), so you aren't passing any parameters.

When you defined test (with (a) =>) you created a local variable a that masks the global variable with the same name.

To pass a you have to actually pass it: test(a).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335