Article

Anonymous Functions

https://cdn.jsdelivr.net/npm/[email protected]/dist/js.cookie.min.js
Copy to clipboard

An anonymous function is a function that has no name and is often used in between other lines of code.

For example you can assign anonymous function to a variable like so: https://raw.githubusercontent.com/finsweet/jqueryCourse/main/functions/ex3.js?actionable=false

In javascript anonymous functions are used by the developer to fill in some custom functionality inside another function that is accomplishing an overarching task. Example: https://raw.githubusercontent.com/finsweet/jqueryCourse/main/functions/ex4.js?actionable=false

In the above example the overarching task is to check if the document has been loaded and is ready to be manipulated by JavaScript.

This overarching function is : $(document).ready()

The anonymous function inside ready() so that we can tell the browser what to do once the page is ready.

The code below will make the browser show a pop up with “hello” once the page is loaded: https://raw.githubusercontent.com/finsweet/jqueryCourse/main/functions/ex5.js?actionable=true

In newer JavaScript versions, the syntax for writing functions has been further simplified. Instead of using: https://raw.githubusercontent.com/finsweet/jqueryCourse/main/functions/ex6.js?actionable=false

Developers can now drop the function name and use: https://raw.githubusercontent.com/finsweet/jqueryCourse/main/functions/ex7.js?actionable=false functions can also include a return statement.

This mean that when the function is called it will produce a value which can be stored in a variable.

The following example defines a function that adds two numbers represented by a and b, then returns the value of the addition: https://raw.githubusercontent.com/finsweet/jqueryCourse/main/functions/ex8.js?actionable=false In the above example a and b are the arguments of the function.

They are used to describe things that we will alter inside the function definition. These names are chosen by the developer and can be anything descriptive of what the function is trying to accomplish.

To use the of function add() We execute it and store the return value in another variable called c: https://raw.githubusercontent.com/finsweet/jqueryCourse/main/functions/ex9.js?actionable=true

<script>
$(document).ready(function(){
  XT1
});
</script>
Copy to clipboard
Send to Live Demo

Live demo

<script>    
$(document).ready(function() {
  XT1
});
</script>
<script>
  
</script>
Copy to clipboard
Press the Run Demo button to execute the scripts above.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Your browser is too small

Resize your browser to be at least 769px wide.