Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions stored in variables? Javascript

Tags:

javascript

Could somebody please explain what this notation is in javascript? What is function(d) doing? In this program it seemse that x is called by the following, but I have no idea what any of this means. Thanks in advance...

x = function(d) { return d.x * width / mx; };

// later....
 x({x: .9}); // call
like image 213
Apollo Avatar asked Feb 21 '23 00:02

Apollo


1 Answers

.9 is a value of the property x of the object(d) being passed into the function.

In the function, d = {x:9}(object) , now when you ask for d's property(x) Value (using DOT notation), it returns the value for the property x.

so d.x returns 0.9!

So you would ask me how did i pass the value of the property into the function-X in the first place, well thats what we did when we dis this -> x(objectBeingSent); where objectBeingSent is {x: .9}.

Anonymous functions are functions that are dynamically declared at runtime. They’re called anonymous functions because they aren’t given a name in the same way as normal functions.

Anonymous functions are declared using the function operator. You can use the function operator to create a new function wherever it’s valid to put an expression. For example you could declare a new function as a parameter to a function call or to assign a property of another object.

The function operator returns a reference to the function that was just created. The function can then be assigned to a variable, passed as a parameter or returned from another function. This is possible because functions are first class objects in javascript.

Here’s an example where a function is declared in the regular way using the function statement:

 function eatCake(){
     alert("So delicious and moist");
 }
 eatCake();

Here’s an example where the same function is declared dynamically using the function operator:

 var eatCakeAnon = function(){
     alert("So delicious and moist");
 };
 eatCakeAnon();

See the semicolon after the second function's closing bracket? }; You use a semi-colon after a statement. This is a statement:

var eatCakeAnon = function(){
         alert("So delicious and moist");
     };

Source

P.S. Best explanantion that i could find!

like image 128
Eswar Rajesh Pinapala Avatar answered Feb 28 '23 01:02

Eswar Rajesh Pinapala