Javascript callback functions

Created By: chatGPT

Callback functions in JavaScript are functions that are passed as arguments to other functions. They allow you to execute code after a specific task has been completed. This is particularly useful for asynchronous operations such as data fetching, where you want to wait for a response before proceeding with further actions.
function fetchData(callback) {
    setTimeout(() => {
        const data = { name: 'John', age: 30 };
        callback(data);
    }, 1000);
}

fetchData((data) => {
    console.log('Data received:', data);
});
When using callback functions, the code execution can be controlled to ensure that tasks are performed in the correct order. An example is shown below, where the calculateSum function runs once the data is fetched.
function calculateSum(x, y) {
    return x + y;
}

function getDataAndCalculate(callback) {
    fetchData((data) => {
        const sum = callback(data.age, 10);
        console.log('Sum:', sum);
    });
}

getDataAndCalculate(calculateSum);
It's important to handle errors when using callbacks, especially in asynchronous scenarios. You can achieve this by passing an error as the first argument to the callback function.
function fetchDataWithError(callback) {
    setTimeout(() => {
        const error = null;
        const data = { name: 'Jane', age: 25 };
        callback(error, data);
    }, 1000);
}

fetchDataWithError((error, data) => {
    if (error) {
        console.error('Error fetching data:', error);
        return;
    }
    console.log('Data received:', data);
});
For scenarios requiring multiple asynchronous operations, you can use nested callbacks. However, this can lead to 'callback hell'. To avoid this, consider using Promises or async/await for better readability.
function fetchDataOne(callback) {
    setTimeout(() => {
        callback('Data from first API');
    }, 1000);
}

function fetchDataTwo(callback) {
    setTimeout(() => {
        callback('Data from second API');
    }, 1000);
}

fetchDataOne((data1) => {
    console.log(data1);
    fetchDataTwo((data2) => {
        console.log(data2);
    });
});
Introduction And SetupVariablesData TypesMethodsControl FlowFunctionsOperatorsData StructuresCommentsSyntaxEvent HandlingError HandlingPrimitive Data TypesReference Data TypesConstLetVarStringNumberBooleanNullUndefinedSymbolObjectArrayTemplate LiteralsArrow FunctionsRegular FunctionsCallApplyBindAsync FunctionsPromisesCallback FunctionsIf StatementElse StatementSwitch StatementFor LoopWhile LoopDo While LoopFor EachBreak StatementContinue StatementTry CatchThrowFinallyScopeClosureThis KeywordPrototypesInheritanceConstructor FunctionsClass SyntaxStatic MethodsGettersSettersSpread OperatorRest OperatorDestructuring AssignmentMap MethodFilter MethodReduce MethodEvent ListenersDom ManipulationInnerHTMLQuerySelectorAddEventListenerPreventDefaultStopPropagationTimeoutsIntervalsJsonLocal StorageSession StorageRegexMath ObjectDate ObjectString MethodsArray MethodsObject MethodsDeep CloningShallow CloningCallback HellPromise ChainingAsync AwaitMap Vs ForEachFilter Vs ReduceNullish Coalescing OperatorOptional ChainingTypeof OperatorInstanceof OperatorStrict EqualityLoose Equality