1

I'm currently doing an exercise in learnyounode and I can't quite figure out why this version of my code isn't executing correctly.

  1 'use strict';
  2 
  3 const fs = require('fs');
  4 
  5 
  6                                                                                     
  7 fs.readdir(process.argv[2], 'utf8', callback);
  8 
  9 var callback = function (err, files) {
 10     let ext = process.argv[3];
 11     files.forEach((val, idx) => {
 12         if (val.split('.')[1] == ext){
 13             console.log(val); 
 14         }
 15     });
 16 };

If I simply call fs.readdir(...) at the end, it executes so I know it must be an asynchronous / function closure sort of issue that I'm not understanding. Could someone explain why my code above throws an error saying (node:23729) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated. ?

Thanks!

1
  • You call the function before you assign the callback. Commented Nov 8, 2017 at 20:55

1 Answer 1

4

callback is undefined at the time of the call to fs.readdir(). Instantiating it above this call would work.

fs.readdir(process.argv[2], 'utf8', callback); // callback is undefined here
var callback = ...

This will work though:

var callback = ...
fs.readdir(process.argv[2], 'utf8', callback); // callback is now defined

Using Javascript hoisting this will also work:

fs.readdir(process.argv[2], 'utf8', callback);
function callback() {
  // do callback stuff
}

Why doesn't Javascript hoisting work with var?

It's important to point out that the hoisting will affect the variable declaration, but not its value's initialization. The value will be indeed assigned when the assignment statement is reached source

What does this mean?

It means when you hoist a var declaration, you are only "reserving" the variable in scope and not running any of the code to set its value. Since all uninstantiated variables in javascript default to an undefined value, this was the value of the callback variable.

Sign up to request clarification or add additional context in comments.

2 Comments

wow thanks! the explanation for JS hoisting working with var really helped clear my misunderstanding. So despite var being global, it is still declared folllowing the top to bottom logic, right?
var is not global per se, its scope is whatever context it was declared in. But yes, execution is still top to bottom, including variable instantiation and assignment which is why you were getting undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.