2️⃣

2.2 Callbacks

 

Callbacks

Using Callbacks is one way to implement asynchronous programming in Javascript. A callback is a function that is passed to another function and executes when some condition is met. As a simple example, say we want make a function that asks for the user's name and then greets the user:
function greeting(name) { alert('Hello ' + name); } function processUserInput(callback) { var name = prompt('Please enter your name.'); callback(name); } processUserInput(greeting);
Here, processUserInput() takes a function as its input. After asking the user for their name, the callback function is invoked and passed the user's name as input.
In this case, greeting() is passed to processUserInput(). Greeting() takes the user's name and displays it.

Previous Section

Next Section

 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.