Skip to content

JavaScript inline function | Basic code

  • by

A JavaScript inline function is a function assigned to a variable that is created at runtime instead of at parse time. Consider an inline function to be a special case of a JavaScript function.

var func = function() { 
    //Code
};

Inline functions could also be declared with the more compact, arrow function syntax.

In this example, the function is defined inside a set of parentheses, followed by another set of parentheses that immediately invoke the function. Any code that needs to be executed within the function is placed inside the curly braces.

JavaScript inline function

Simple example code.

<!DOCTYPE html>
<html>
<body>

 <script>

  var foo = function (){ 
   alert('Inline function') 
 }
 setTimeout(foo, 100);

</script>

</body>
</html> 

Output:

JavaScript inline function

More Example

<script>
  
    var func = function() { 
      alert ('inline') 
    };
    $('a').click(func);

    // Alternative es6+ inline arrow function.
    let func2 = () => alert('inline');
    $('a').click(func2);

</script>

Inline JavaScript onclick function

You can use Self-Executing Anonymous Functions. this code will work:

<a href="#" onClick="(function(){
    alert('Hey i am calling');
    return false;
})();return false;">click here</a>

Or

You may inline any javascript inside the onclick as if you were assigning the method through javascript. Make code cleaner keeping your js inside a script block.

<a href="#" onclick="function hi(){alert('Hi!')};hi()">click</a>

An inline function is often used to encapsulate code and create a private scope for variables, preventing them from polluting the global namespace. For example, the following code defines an inline function that increments a counter each time it is called:

var counter = (function() {
  var count = 0;
  return function() {
    return ++count;
  }
})();

console.log(counter()); // Output: 1
console.log(counter()); // Output: 2
console.log(counter()); // Output: 3

Comment if you have any doubts or suggestions on this JS function topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *