Using '(e)' in functions?

Well, yes, ish. It’s just a more general thing than that, it’s a very broad thing, it’s not specific.

So I’ll have a look at what you’re trying to do in a bit, but just in an attempt to clarify (sorry for long post again):

When you write code that is to be used by other developers (or you): a programming language, or a framework, or a library or even a single class or function. Or, say, a web interface, or the code for some hardware device. Just basically anything that needs to be used programmatically.
When that is done, you want to hide how it works. To use another analogy, a TV. The internal workings of it aren’t exposed, you don’t have to fiddle around with the circuits to just turn it on or off. You just press a button. Click on. Click off.

An API is just that – the programmatic controls that are exposed so you can do {the things} with whatever you’re using.

This is what I mean by it being much more general and non-specific than I think you understood it to be. It’s just the {things} made available by {thing} that you can use to interact programmatically with {thing}.


So in a web context, “API” is often used to refer specifically to the controls provided by some web service to let you, as a programmer, get access to some resources on that service’s system.

This is the same as I’ve described above. What I think obfuscates understanding is how it’s talked about – colloquially, you “access an API”, as if this is a special kind of system. But this is what I alluded to in a previous post: you use an API. That’s semantics, but I think it’s important. It’s not a mysterious thing.

An API can be defined in an almost infinite number of different ways. There are naturally common patterns, architectures, protocols etc. that developers use because if everyone just did their own thing, it would be almost impossible, as a developer, to get anything done.

So, example, anyway:

Say you have an application that has some stuff stored in a database, say types of domestic cat. You have some function that takes a string (a key), and when you run the function it looks up whatever is under that key in the database. And it returns that data as a string – under the hood, it tells the dB system to make a query, gets the result, converts it to JSON.

function getCatInfo (catType) {
  const dbResponse = myCatDatabase.query(catType);
  // Bleep bloop bloop, do some stuff
  return JSON.stringify(dbResponse);
}

And that’s ok, works on your computer. You’ve got the database and you’ve written the code and you can look up cats and stuff. You can just run the file with the function – something like node ./look-up-cats.js persian But you want to put this on the web and let everyone look up cats.

So you buy a domain name, cats.info, and you find somewhere to host an app. Then you look up how to make your cat app available on the web. And you figure out that, install Express or whatever in your app, and you start it up. And what you end up with is something that listens for HTTP requests and responds with something else. You type a URL into your browser (https://cats.info/persian), the URL points to the domain that your app is hosted on, your app is running and reads that request, it takes the incoming URL, splits the string, grabs the persian bit, gives it to your getCatInfo function and gets the result, sends that back as a text, says the type is JSON, you get that back in the browser.

So the API the functional bit of the app is a function called getCatInfo. The API for the made up database library I used in the function includes a function called query. The web framework has an API – if it’s Express, if you go to the Express docs, there’s instructions on the functions you use to work with Express. Node has an API, it has a standard library it ships with, loads of functions for doing various things. The browser that made the request has an API – maybe the request was made with JS, and used one of the API functions fetch. Maybe it wasn’t, maybe it just used an HTML form element, which has an API. And the API for the overall web service, that’s not functions, that’s basically just a list of URLs and what you get by typing in those URLs – https://cats.info/someCat will give you some data about someCat, that’s the API

1 Like

Ah I got it! Makes perfect sense. Thanks for taking the time to break that down to me. I can see how it can be a really general concept now.

It can be rather complex in its broad nature.

@miketandy @chimegreat4real2008 Just picked up the book! I can already tell how much its helping me understand things better! Thanks SOO much for your recommendations :pray: . ‘Head First Javascript’ helped me alot but this is the book that I should have really gotten from the start. Gotta love that straight forward format and presentation.

Thanks again for your help guys :+1:

Glad it’s helping, it’s a fun read and very practical, he’s got a php/mysql book coming out later this year… The long awaited sql

1 Like

Yeah ive seen some articles about that. Apparently he’s been dragging his feet on getting it done :joy: But if its as good as his previous two, I wouldn’t mind picking it up.

I can only imagine how much work goes into creating one of his books.

I’m taking at stab at answering your original question again.

There’s been lots of talk of APIs, short for Application Programming Interface, in the thread. Here’s a chunk from the definition of interface on Merriam-Webster:

the means by which interaction or communication is achieved

Think of this like a contract for how to use a certain system (be that a function, a class method, a REST API, whatever). It sounds like you’re okay with the idea that you can make a function add that returns the sum of two numbers. Maybe somewhere in your own code you defined it yourself like such:

function add(a, b) {
  return a + b;
}

Although this would be more explicit in some other programming languages, you’ve implicitly defined an interface for this function. In plain English, the interface would be something like “give me two numbers, and in return, I’ll give you their sum as a number”.

In other words, it would be nonsensical to use add in the following manner.

add(5);

You likely don’t even think to try something like this. It breaks the contract that you yourself defined.


On the other hand, we often find ourselves working with other people’s code. You’ve probably wrote more console.logs than you can remember. But how do you know that you can hand it strings and it’ll log them to your browser’s console for you? Because that’s its interface! You never wrote the code that does that. But you can look up its interface online on MDN so you know how to use it.

Likewise we can look up the particular documentation for events in React, and find out about their interface. Here’s the page: SyntheticEvent - React

Your event handlers will be passed instances of SyntheticEvent , a cross-browser wrapper around the browser’s native event. It has the same interface as the browser’s native event, including stopPropagation() and preventDefault() , except the events work identically across all browsers.

Okay, that’s a bit to unpack, but let’s try it.

Your event handlers

Your handler is a function, in this case it’s more specifically a callback function. You tell React, “hey, here’s the handler that I wrote, when you see this event, call it”.

<form onSubmit={submitTodoHandler}>

“hey, here’s the submitTodoHandler that I wrote, when you see a submit event on this form, call it”

Moving on, will be passed instances of SyntheticEvent

This here answers the question about why your handler has that e parameter. As we said above, you’re telling React to call your handler when the event happens, here the docs are saying “we will give your handler an event object as an argument”. Since you’re defining the handler, you also define the name of its parameters, so it doesn’t have to be e, it just is by convention.

const submitTodoHandler = (theEventObjectPassedToMeFromReact) => {
  theEventObjectPassedToMeFromReact.preventDefault();
  // ...
}

This would still be valid, just unwieldy.

Well, what’s an instance of SyntheticEvent? The docs go on to say “It has the same interface as the browser’s native event”, and then there’s a giant list of all of its properties and methods.

Every SyntheticEvent object has the following attributes:

boolean bubbles
boolean cancelable
DOMEventTarget currentTarget
boolean defaultPrevented
number eventPhase
boolean isTrusted
DOMEvent nativeEvent
void preventDefault()
boolean isDefaultPrevented()
void stopPropagation()
boolean isPropagationStopped()
void persist()
DOMEventTarget target
number timeStamp
string type

So we know that the object passed to our handler function will have all of these ways to interface, or interact, with it. In the case of naming it e, we could then call e.stopPropogation(), or e.preventDefault(), or log the time of the event with console.log(e.timeStamp), because the docs say that the object will have all those methods and properties. But we can’t write e.push("foo"), because according to the interface in the docs, the event object does not have a push method.

And if we’re unsure what those properties hold or what those methods do, then we can check the docs for the browser’s native event.


TLDR

Your add function’s interface, in plain English - “give me two numbers, and in return, I’ll give you their sum as a number”

React’s event handling interface, in plain English - “give me a callback function handler, when the event happens, I will call handler and give it an event object”

2 Likes

Ok I see that now. That makes perfect sense. Its still alot to wrap my head around but I believe that im starting to get it. It has to do with the programs behavior and documentation. How it handles data.

To maybe make it more clear, imagine in your own code you wrote this:

// 1. define an object with a timeStamp property
const event = {
  timeStamp: Date.now()
}

// 2. define a function that logs the timeStamp property of its argument
const handleEvent = (e) => {
  console.log(e.timeStamp);
}

// 3. call the function from step 2, passing the object from step 1
handleEvent(event);

In your own code, this is pretty clear what’s happening, I think.

However in the React ecosystem, you’re only handling step 2. Both steps 1 and 3 are done on the React side. Does that make sense?

1 Like

yeah that makes sense. So you’re basically creating an event object, and using a custom ‘event’ from step 1 as a method for that event object that you are later referencing in step 3 :face_with_monocle:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.