6.1 Different ways of declaring functions

Some more useful information about functions in JavaScript. Functions can be declared in several ways, each of which has its own nuances.

The most standard way is this: keyword functionand Name.

   function print(data)
   {
     console.log(data);
   }

The second way is to first declare a variable and then assign an anonymous function to it.

window.print = function(data)
 {
     console.log(data);
 }

These two methods give absolutely equivalent results . When you declare an ordinary function in the first way, a new field is created on the window object with the name of your function and a reference to it is assigned to it.

6.2 Anonymous functions

It is also possible to create an anonymous function and not assign its value to anything. Why is such a function needed? How to call her?

And the thing is that you can call it immediately. Let's say we declared a function tempand immediately called it:


var temp = function(data)
    {
        console.log(data);
    }
 
temp("some info");

You can also declare it and immediately call it:


   (function(data)
    {
        console.log(data);
    })("some info");

Kind of like anonymous inner classes in Java...

6.3 eval() method

And another interesting way to execute code in JavaScript is to not create functions at all. In JavaScript, you can simply execute code given as a string. There is a special function for this eval()(from evaluation). The general call format looks like this:

var result = eval("code or expression");

Examples:


var x = eval("1/2");
eval("alert('Hi!')");