@@ -77,4 +77,50 @@ const arrowFunctionExample = () => {
7777 console . log ( "This is an arrow function." ) ;
7878} ;
7979
80- arrowFunctionExample ( ) ; // Calling the arrow function
80+ arrowFunctionExample ( ) ; // Calling the arrow function
81+
82+ //callback functions
83+ // Callback functions are functions that are passed as arguments to other functions and are executed after a certain event or condition is met.
84+ // They are commonly used in asynchronous programming, event handling, and functional programming patterns.
85+ // Example of a callback function
86+ function callbackExample ( callback ) {
87+ console . log ( "Executing callback function..." ) ;
88+ callback ( ) ; // Calling the passed callback function
89+ }
90+ callbackExample ( ( ) => {
91+ console . log ( "This is the callback function being executed." ) ;
92+ } ) ;
93+
94+ function xx ( yy ) {
95+ console . log ( "This is a function that accepts a callback yy and called in xx." ) ;
96+ yy ( ) ; // Calling the callback function passed to xx
97+ }
98+
99+ xx ( function yy ( ) {
100+ console . log ( "This is a callback function yy passed to xx." ) ;
101+ } ) ;
102+
103+ let counter = 0 ;
104+
105+ // using a global variable to keep track of clicks but not recommended in production code
106+ // Using a global variable to keep track of clicks is not recommended in production code,
107+ // as it can lead to unexpected behavior and make the code harder to maintain.
108+ // Instead, consider using closures or state management libraries for better control over state.
109+ document . getElementById ( "clickMe" )
110+ . addEventListener ( "click" , function xyz ( ) {
111+ console . log ( "Button clicked! " , ++ counter ) ; // This is a callback function executed on button click.
112+ } ) ;
113+
114+ function attachEventListener ( ) {
115+ let localCounter = 0 ; // Using a local variable to keep track of clicks
116+ document . getElementById ( "clickMe2" )
117+ . addEventListener ( "click" , function closureExample ( ) {
118+ console . log ( "Button clicked! " , ++ localCounter ) ; // This is a closure that captures the local variable.
119+ } ) ;
120+ }
121+ attachEventListener ( ) ;
122+
123+
124+
125+
126+
0 commit comments