Ex12 function parameters


#1

I’m going through Ex12 and am wondering about function parameters.
This I get:

const yell_at_me = (what) => {
return what.toUpperCase();
}

You’re passing in what as the parameter and using that.

This I don’t quite get:

const print_lines = (err, data) => {
console.log(data.toString());
}

followed by:

fs.readFile(“poem.txt”, print_lines);

Is the print_lines function not expecting two parameters (err and data) when we call it? Are they optional? But if they are, the body of print_lines seems to be using the data parameter, how does it get that from our call?


#2

Nope, it takes two parameters, you just aren’t using the err parameter. Try doing console.log on that too in order to see what it is.


#3

Ok, thanks. Doing console.log I get err as being null.

I guess I was expecting the call to be:

fs.readFile(“poem.txt”, print_lines(err, data));

to match the definition. Is it a feature of callbacks, or JS that it isn’t so? I still don’t fully grok callbacks.


#4

Ahhhh yes, that’s a confusing thing about callbacks. So, you know how you can do this:

somefunc(1, 2)

And that passes 1 and 2 to somefunc. You can also do this:

let x = 1;
let y = 2;
somefunc(x, y);

That assigns 1 to x and 2 to y, then calls somefunc with x and y. But, that ends up being the same as somefunc(1,2).

Alright, do you see how you’re doing this:

const print_lines = (err, data) => {
console.log(data.toString());
}

Welllll, you’re making a variable named print_lines and assigning a function to it. It’s just like let x = 1, and there’s no reason to say that functions are now some kind of magic thing that can’t be like 1 or 2 or x or y. That means when you do this:

fs.readFile(“poem.txt”, print_lines);

You are passing the variable print_lines to the fs.readFile function. That. Is. All. Now, it just so happens that readFile expects this variable to be a function and not a number. When it gets a function it will call it for you.

When you write this:

fs.readFile(“poem.txt”, print_lines(err, data));

You are trying to call print_lines for the fs.readFile function, before you call readFile, but then also trying to use the err, and data variables that only fs.readFile knows about. You are basically trying to do fs.readFile’s job.

So, in callbacks treat functions like variables and let someone else call them. If you put () after your callback then you are telling javascript to call your callback right there, not later.


#5

Oh wow! I think because of your clear explanation I am finally starting to get callbacks. I had actually searched the web and youtube the first time I encountered callbacks and just got more confused. Thank-you so much for taking the time to go through it in easy to understand terms for us!