When called inside a function with parameters passed from parent, why is the setTimeout function logging undefined?

Viewed 40

I have been working with the asynchronous function setTimeout in javascript. The following code gives different results when the parameter is passed in one setTimeout function and not in another. Can someone explain this?

Code 1:

console.log("Before");
getUserId(2);
console.log("After");

function getUserId(id){
  setTimeout(() =>{
    console.log(id);
  }, 2000);
}

Output 1:

Before
After
2

and,

Code 2:

console.log("Before");
getUserId(2);
console.log("After");

function getUserId(id){
  setTimeout((id) =>{
    console.log(id);
  }, 2000);
}

Output 2:

Before
After
undefined
4 Answers

If you want to pass parameters to your callback you can put them after delay param. If you don't pass any parameters then your callback is called without any

setTimeout(function[, delay, param1, param2, ...]);

console.log("Before");
getUserId(2);
console.log("After");

function getUserId(id){
  setTimeout((id) =>{
    console.log(id);
  }, 100, id);
}

The parameter id inside the setTimeout callback will be undefined unless you assign a default value to it like the example

function parentMethod(parentId) {
  setTimeout((id = parentId) => {
    console.log(id);
  }, 2000);
}

Check this line setTimeout((id = parentId) => {

Here I am assigning a default value to it, so it will log whatever I assign to the parent method.

Because in sample 1 id is set in the scope of getUserId(id) In sample 2 the id is set again in that scope, but then a second narrower scoped id was created via your anonymous function. there is no need to pass setTimeout() the id parameter since it already exists in the getUserId scope

In the second example, you are redefining scope for the variable id in the callback passed to setTimeout(). In other words this is the same as:

function getUserId(id){
  setTimeout((some_other_id) => {
    console.log(some_other_id);
    // some_other_id is undefined
  }, 2000);
}

Understanding the scope of id will explain / fix your problem.

Related