Something Like that:
Immediately Invoked Function Expressions (IIFE)S
What is (IIFE)S?
Immediately Invoked Function Expressions
For that you need to create first html code.
HTML
<p id="demo1"></p>
After that add this JS code.
JS
var greeting = function(name){ return 'Hello ' + name; }('John'); document.getElementById("demo1").innerHTML = greeting;
[codepen_embed height=”265″ theme_id=”0″ slug_hash=”GvyyEd” default_tab=”result” user=”pradeepanvi”]See the Pen IIFE in javascript by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]
Now you can see
Hello John
Another Example
For that you need to create first html code.
HTML
<p id="demo1"></p>
After that add this JS code.
JS
var firstname = 'Johan'; (function(name){ var greeting = 'Inside IIFE: Hello'; document.getElementById("demo1").innerHTML = greeting + ' ' + name; }(firstname));
[codepen_embed height=”265″ theme_id=”0″ slug_hash=”Ljeeej” default_tab=”result” user=”pradeepanvi”]See the Pen IIFE in javascript 02 by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]
Now you can see
Inside IIFE: Hello Johan
IIFE and safe code
1. Doesn’t take global variable with global parameters.
2. replace global variable with IIFE.
For that you need to create first html code.
HTML
<p>Inside Function = <span id="demo1"></span></p> <p>Global = <span id="demo2"></span></p>
After that add this JS code.
JS
var greeting = 'Hola'; (function(global, name){ var greeting = 'Hello'; global.greeting = 'Hello'; document.getElementById("demo1").innerHTML = greeting + ' ' + name; }(window, 'John')); document.getElementById("demo2").innerHTML = greeting;
[codepen_embed height=”265″ theme_id=”0″ slug_hash=”GvyyGX” default_tab=”result” user=”pradeepanvi”]See the Pen IIFE in javascript 03 by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]
Now you can see
Inside Function = Hello John
Global = Hello