assigning a function(with arguments) a variable name? [JavaScript] - javascript

I've decided to teach myself functional programming.
I've submitted all of my assignments whilst maintaining the rules of functional programming, and my instructor is totally fine with it. To grab inputs, I've been doing something like this:
var getWidth = function(){
return prompt("What is the width?");
};
This works fine but it could be something simpler, like:
var getWidth = prompt("What is the Width?");
The problem with this, is when I call the function getWidth(), it simply runs the function once and assigns it to the getWidth variable. But that's not what I want, I want it to run prompt("What is the Width?") every time getWidth() is called. I've tried to search for it, but I'm not really entirely sure how to phrase it. Google's useful, if you know how to use it.

Well you could use bind()
var hm = window.prompt.bind(window, "simpler?");
console.log(hm());

it could be something simpler, like:
You cannot "simplify" a function
var a = function onePlusTwo() {
return 1 + 2;
};
by writing
var a = 1 + 2;
The two do entirely different things.
The first defines a function (meaning, does not execute it), and assigns the function to the variable a. The function can then be called with a(), which will evaluate to 3, since that is the return value of the function:
alert(a() * 2) // 6
The second (var a = 1 + 2;) merely executes the code which you had in the body of the function. Executing it assigns the result of 1 + 2 to the variable a. This code is "re-usable" only by copying and pasting it elsewhere in your program.
So if you want to define functionality and re-use it, you have no choice but to define it as a function. That's what functions are for!
If you want to take a function and make another function you can use to call that function later, with or without some arguments, then as mentioned in another answer, you can use bind, as in var a = prompt.bind(window, "What is the width?");, and then call it with a(). But this is essentially the same as writing the function out in the way you did in the first example, and is a little bit less readable.
By the way, none of this is "functional programming". Functional programming does not mean just using functions; all programs do that. Functional programming refers to a style of programming involving manipulating, combining, dynamically creating, and passing around functions.

You cannot simplify your function this way. By the first method:
var getWidth = function(){
return prompt("What is the width?");
};
You are returning an executable function, and assigned the function reference to a variable getWidth. However in the second one:
var getWidth = prompt("What is the Width?");
You are returning the result of the function window.prompt.

What the OP might be looking for, is the lambda functional shorthand. It's a really simple bit of code, that let's you right functions much shorter. It's usually, used for anonymous functions, but it could easily be re-purposed here. For example:
function getWidth(){
return prompt("What is the width?");
}
Would be reduced to:
var getWidth() = () => prompt("What is the width?");
Note that the value of prompt is returned automatically, so you don't need to add return to your code.
Parameters could also be specified if desired, like this:
var getWidth = (x) => prompt(x);
And if you use arguments this way, then the () are optional. This would work too:
var getWidth() = x => prompt(x);

Related

declaring local variables inside document ready or inside function in different scope

I need to know which is the better way of declaring some local variables. Which is better in terms of practice, performance? Since, local variables declared inside the function gets removed as soon as the function is executed, does declaring as many local variables (eg: a,b in example below) inside various functions compared to declaring only once inside document.ready() makes any difference?
Method 1:
<script type="text/javascript">
$(function() {
getItem1();
getItem2();
}
function getItem1() {
var a = 100;
var b = 1000;
//do something with a,b
return item1;
}
function getItem2(){
var a = 100;
var b = 1000;
//do something with a,b
return item2;
}
</script>
Method 2:
<script>
$(function() {
var a = 100;
var b = 1000;
getItem1(a,b);
getItem2(a,b);
}
function getItem1(a,b) {
//do something with a,b
return item1;
}
function getItem2(a,b) {
//do something with a,b
return item2;
}
</script>
It's really an idea of why i am using these functions and what are my purposes because it may vary, in Method 1 you are declaring the variable inside a function which those variable will be saved in memory as soon as the function is being executed and they will be deleted when it finish , so if the function contain too many variables and too many lines of code it will not be a good idea if you r looking for performance so it is better using Method 2 ,but if your function is easy and having few lines of code with easy execution method 1 is better of course
It's all a matter of what you need, really.
Will you be reusing your functions on multiple instances? Will it be true that if a and b will be supplied on all possible scenarios, the code inside getItem will process the values correctly? If so, then passing the values will be a good choice since you have the free will to pass whatever you want to. If a and b are just constant and will never change at all, then having the values constant would be a great idea as well.
The second choice gives a lot of flexibility and you can change the values anytime you want, this makes the code more 'generic' and 'reusable' - provided you're going to use the same process.
Performance wise, they make a little difference. With the first option allocating a bit more memory since you have to instantiate a and b twice.

Motivation for mutiple layers of referencing? - Code Academy JavaScript

I am working through the JavaScript track on CodeAcademy and have encountered a question on Objects II -> Introduction to Objects II -> Private Methods (25/30). I'm not understanding the motivation behind things pointing to things, that point to other things. If we are trying to get to the value of a variable why not refer to it more directly? For example
var d refers to var c
and
var c refers to var b
and
var b refers to var a
Why do this rather than referring to var a initially? Why create variables b, c, and d at all? Anyway in Private Methods - 25/30 the heart of the matter is below. *Note - I put the exhaustive/exact code at the very bottom
**var bankBalance = 7500;** // Located within the Person class
**var returnBalance = function()** // Create returnBalance method which returns
**return bankBalance;** // the bankBalance above
t**his.askTeller = function() {** // Create the askTeller method which calls
**return returnBalance;** // returnBalance method above
**var myBalanceMethod = john.askTeller();** // create a variable named myBalanceMethod
// which equals the value for askTeller method above
**var myBalance = myBalanceMethod();** // create a variable named myBalance which
// equals the value for myBalanceMethod method above
**console.log(myBalance);** // logs to the console the value of myBalance
This all seems like a lot of trouble. What is the motivation to go through all this trouble instead of a more direct reference to bankBalance?
Below I have included my EXACT code (note - it works just fine I just don't understand to reasoning behind the multiple layers)
**function Person(first,last,age) {
this.firstname = first;
this.lastname = last;
this.age = age;
var bankBalance = 7500;
var returnBalance = function() {
return bankBalance;
};
// create the new function here
this.askTeller = function() {
return returnBalance;
};
}
var john = new Person('John','Smith',30);
console.log(john.returnBalance);
var myBalanceMethod = john.askTeller();
var myBalance = myBalanceMethod();
console.log(myBalance);**
Referencing something through another name isn't demonstrated properly in the example (which is why real-world examples are so necessary and so praised when used).
When we assign a variable to something we already have a reference for, such as:
var cc = Components.Classes;
we can do it for brevity, such as above. Writing cc as opposed to Components.classes can make the code a lot clearer and easier to read, as long as the context is clear. Once you start using APIs, the DOM or complex objects, the usefulness of this becomes quite clear. In this case, I can replace all my Components.Classes references, such as:
Components.classes["#mozilla.org/messenger;1"];
with
cc["#mozilla.org/messenger;1"];
Much better - especially when you have to chain these:
var os = Components.classes["#mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
becomes:
var os = Cc["#mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
Now it fits in a single line and is much easier to vgrep/tokenize-with-your-eyes.
Another advantage is assigning, for example, as single definition of a function to two or more objects:
function _start() { /* start monitoring */ }
function _stop() { /* stop monitoring */ }
/* ... code ... */
process_observer.start = _start;
process_observer.stop = _stop;
memory_monitor.start = _start;
memory_monitor.stop = _stop;
In this example, assuming we've written our _start and _stop functions to be agnostic of what our object monitors and can fit any monitoring object, we can write our function once and still assign it to each object separately so we can call process_observer.start() instead of start(process_observer) which would requite acting on the object rather than having the object act ( the former might involve exposing data and methods we would otherwise want to keep hidden, to prevent errors and promote clarity - it also might prevent us from using certain design patterns ). These are of course a matter of preference, design approaches and perspective, but never underestimate readability and clarity in code. Also, if we change _start or _stop is changes for all objects that use them, instead of requiring manual changes. A common usage case is having different implementations for different platforms or browsers and having the proper function assigned to all objects that use it, at initialization, where we detect what where running on.
Also, you might have noticed I didn't use parenthesis () when I assigned my functions to the object owned variables - when you do it like your example:
myBalance = myBalanceMethod();
you're not assigning myBalanceMethod to myBalance - you're calling myBalanceMethod (because of the ()) and assigning it's return value to myBalance - very big trap. People trip over this all the time when assigning click handlers in html elements.
To be honest, as I said in the beginning, the example is terrible - there is no reason write that code that way and, as you've already found out yourself, it makes it harder to understand rather than easier, which is the whole point of aliasing variables and functions and being able to assign them so freely.

Do javascript functions need to be declared in the reverse order?

Elaboration: If I would have, for example the following code:
//Javascript example
var alice = function() {
var value = bob() + 1;
console.log value
}
var bob = function() {
var value = 1;
return value;
}
//Running function A
alice()
Would I have to declare function B first, because I am calling it in function A without reaching function B yet.
No.
If you have a function declaration, then it will be hoisted and order doesn't matter (although putting functions in an order so that a function call doesn't appear before the function being called is good practice).
If you have function expressions (as you do in your example), then you need to have the functions created before they are called, noting that in this example none of them are called before the line alice() so only that line needs to be after the functions and the order of the functions themselves doesn't matter. (But the best practise principles described above hold).
No, because the Javascript interpreter will recognize the functions declared after and link them appropriately to the line in question.
The only limitation is the definition of every function before utilization

Execute private function inside the class by its name (string)

At the moment I have simple JavaScript class like this:
function MyClass() {
// ... some code ...
this.Create = function() {
funcName = 'myTestFunc()';
cTimer = setTimeout(funcName, 1000);
}
// ... more code ...
var myTestFunc = function() {
alert ('everything\'s OK!');
}
// ... more code ...
}
and to test it I'm using this code:
x = new MyClass();
x.Create();
I have some troubles to execute this function by it's name. If I put just eval(funcName); instead of setTimeout call it works fine but can't figure out why it doesn't work this way.
Course, this is part of more complex code but rest of code is irrelevant to this problem.
My question is obvious - How to execute function by its name set as setTimeout function's argument? Is it possible?
Note: Making this function public (this.myTestFunc = ...) isn't an option!
Update:
funcName = "myTestFunc()"; is just an example. In real code it looks like funcName = getRandomEffectFunctionName();! It's just a random value.
Referring to the update:
Instead of setting:
var funcName = "getRandomEffectFunctionNeme()";
Thus, setting a reference to the function's name you should do
var funcRef = getRandomEffectFunctionNeme;
And set a reference to the function itself . Not only this avoids the issues setTimeout with strings has*. It also solves your closure issue since your code is structured in such a way the timeout has access to the function itself.
In your case, let's assume you have some functions that are filters, for example lowPass highPass and blur. In that case, instead of choosing a function name we would be choosing a function.
First, we store these functions in an array:
var filters = [lowPass,highPass,blur];
In JavaScript, functions are first-class objects, you can pass them around just like other objects.
Next, we'll get a random number
var chosen = Math.floor(Math.random()*3);//get a random number between 0 and 2
Finally, we'll choose the filter and invoke it
var filter = filters[chosen];
setTimeout(filter,1000);
( * just try debugging it, it basically invokes the compiler whenever ran and is painfully slow)
You just pass a function to setTimeout as a parameter, rather then a string, setTimeout(myTestFunc,1000) .
When calling Create it would have access to it anyway because they are in the same closure.
NOTE: This solution is only applicable if you can not pass the function name as a function reference, for example if you're integrating with code that is outside your control. Generally, when possible, you should pass a function reference since in JavaScript, all functions are objects.
Assuming that the timeout and the function are in the same closure your code is pretty close. The problem is that your eval call executes in the global context because it is in a timer. This means they are no longer in the same lexical scope.
You can however, grab a reference to the function by clever use of eval which you can later call in the setTimeout invocation.
var F=eval(funcName);// gain a reference to the function given the function's name
cTimer = setTimeout(F, 1000);
If you're using AIR or don't trust the functionName string you can do the following:
function Test(){
var functionContainer={
t:function(){
console.log("it's t");
}
};
this.callT=function(functionName){
var F=functionContainer[functionName];
console.log("F is:",F);
setTimeout(F,500);
}
}
(new Test()).call("t");
This is preferable since you are invoking setTimeout with a function's name and not a string. In general, using setTimeout with a string can have issues, it's hard to debug or maintain.

Is my javascript coding style following best-practice?

What is the 'best practise' with regard to coding style.
Should I use _ for private members?
Should I use this._privateMember?
Please re-write my code in proper style if its wrong:
(function()){
var _blah = 1;
someFunction = function() {
alert(_blah);
};
someOtherFunction = function {
someFunction();
}
}();
I would read this and incorporate any part you agree with:
http://javascript.crockford.com/code.html
You do not have to agree with all of it
I don't think there is one. Use a prefix if you think it helps.
I use _ for private members because it distinguishes them which can be quite helpful in Javascript when you have variables coming from all over the place. But they do clutter the code a bit.
I don't use _ for variables that are declared using var. I do however, use _ to denote object members that shouldn't be access directly.
Some people (who are strange in my opinion :P), also prefix variables with a $ if it contains a jQuery object.
As long as you are consistent with what you do, there are no problems.
Aside from just the code you're showing now, you should use Capital Letters to distinguish constructor functions, and camelCase to name instances of objects.
function Foo (val) {
this.set(val);
};
Foo.prototype.get = function () {
return this._dontTouchMePlease;
};
Foo.prototype.set = function(val) {
this._dontTouchMePlease = parseInt(val, 10);
};
var aFoo = new Foo(6);
I think that its generally accepted that if a variable name starts with a _, you probably shouldn't touch it (accept in dire cirumcstances and even then, two keys and special codes should be provided).
If I'm remembering my Crockford correctly, you'll want to put var in front of the two inner functions, otherwise they will be implicit globals. If you want them to be globals, then that's moot. Either way, your second inner function declaration should probably end in a semicolon. This might be a misformating thing, but I think its generally accepted that the bodies of functions are indented one more level in. Also, I've never seen the (function()){/* stuff */}(); construction before, but that says pretty much nothing.
I'd write it these ways - one for if your just declaring a function and another for if your using an anonymous function and immediately applying it to get a result, because I don't which one you're trying to do (again, if you want the inner functions to be global, then this won't be what you intended):
//function declaration
var myFunction = function () {
var _blah = 1;
var someFunction () {
alert(_blah); //or console.log(_blah); for debugging purposes
};
var someOtherFunction () {
someFunction();
};
};
//using a one-of to assign a result
/* NOTE: if you are using this version, myResult will be undefined
(at least given the functions you provided), but like I said,
I don't recognize the construction you provided, and am therefore
assuming that you meant one of these two, which could be a perfectly
falacious assumption, and in that case, my apologies
*/
var myResult = function () {
var _blah = 1;
var someFunction () {
alert(_blah);
};
var someOtherFunction () {
someFunction();
};
}();
BTW, (and I don't want to overstep) Crockford's "JavaScript: The Good Parts" is a stellar reference for JavaScript syntax. He also has, on his website a JavaScript style guide of sorts (though I don't know how widely followed it is). Link is: http://javascript.crockford.com/code.html
I also use the "_" in c# for private/protected members. It is a fast way to see if the variable is a member-variable or not. And you can access it faster with code-completion because you don't get in mess with the public members (private: _blah , public property: Blah).
But are there any private members in javascript anyway? I think every variable defined as member is accessible from the outside.
So you don't have a public wrapper for the private member. And that means the "_" is a bit a overhead and the same can be achieved with "this.".
I prefer you to use the following stuffs which is preferably used around the world programmers.. see below
i = Int
f = Float
o = Object
r = Return
a = Array
e = Element
g = Global declaration
hook = a function which can be used for hooking with other functions
call = a function which can be used for making call from client to server system
sync = a function which can be used for SYNC
and so on.. you can prefix on your coding...

Categories

Resources