Callback function in java script

Example 1 : Simple Callback function

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JavaScript</title>
</head>
<body>
    <script>
        let x = function(){
            console.log('I am called from inside a function');
        }
        let y = function(callback){
            console.log('do something');
            callback();
        }
        y(x);
    </script>
</body>
</html>

Example 2 : Example of making functions abstract and calling it

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JavaScript</title>
</head>
<body>
    <script>
        let add = function(num1,num2){
            return num1+num2;
        }
        let multiply = function(num1,num2){
            return num1*num2;
        }
        let calc = function(num1, num2, callback){
            return callback(num1,num2);
        }
        console.log(calc(10,20,add));
    </script>
</body>
</html>

Example 3 : Example of passing anonymous function to a function

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JavaScript</title>
</head>
<body>
    <script>
        let calc = function(num1, num2, callback){
            return callback(num1,num2);
        }
        console.log(calc(10,20,function(x,y) { return x+y; } ));
    </script>
</body>
</html>

Example 4: Sorting of array

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JavaScript</title>
</head>
<body>
    <script>
        var myArr = [{
            num: 5,
            str: 'apple'
        }, {
            num: 7,
            str: 'cabbage'
        }, {
            num: 1,
            str: 'lol'
        }];
        myArr.sort(function(x,y){
            if(x.num > y.num){
                return 1;
            }else{
                return -1;
            }
        });
        console.log(myArr);
    </script>
</body>
</html>

Leave a Comment