assigning a function variable to another function - javascript

First up - n00b with Javascript here and I did try to search for something which represented similar concept as the one I have below but I couldn't find anything useful..sorry if my search skills are rather limited.
I'm going through the Eloquent Javascript and under the "Nested Scopes" section, there was some code showing how the scope of functions works; the following is the code (And a bit that I've added to experiment)
var landscape = function() {
var result = "";
var flat = function(size) {
for (var count = 0; count < size; count++)
result += "_";
};
var mountain = function(size) {
result += "/";
for (var count = 0; count < size; count++)
result += "'";
result += "\\";
};
// my nonsensical code -- begin
var myfunc = function(text) {
console.log("this is only a block of text -", text);
};
// my non sensical code -- end
flat(3);
mountain(4);
flat(6);
mountain(1);
flat(1);
// this is what I was trying to do and see what happens here..
mountain = myfunc("meh");
// end of my nonsense
return result;
};
console.log(landscape());
I understand that if within my function (myfunc) if I assign a value to result then when result is returned in the last line, it will get overwritten with whatever value is being assigned to it in myfunc
My question here I guess is what does it really mean to be able to assign one function variable to another (mountain = myfunc) and is there a real world usage to such a "feature"? If not, why does Javascript allow such an assignment?

This line:
mountain = myfunc("meh");
Assigns the return value of myfunc to mountain.
Since myfunc only logs something, it returns undefined (which is the default return value when no explicit return value is given).
Therefore, at the end of the example you've given mountain is undefined.
This is very useful, however, when you have functions that return other values. For example:
function add(a, b) {
return a + b;
}
function multiply(c, d) {
return c * d;
}
function divide(e, f) {
return e/f;
}
var multipliedThing = multiply(add(1,2), add(3,4));
var anotherMultipliedThing = multiply(add(5,6), add(7,8))
var result = divide(multiplied, anotherMultipliedThing);
// => 0.12727272727272726
The above is a bit contrived, but it shows a use case for assigning the return values of functions to variables.
The core concept of functions is general is to accept some value and return a value. With JavaScript (and many other languages) you get the "benefit" (I put that in quotes because it's debatable in some circumstances) of functions giving side effects (that is, mutating other values outside of the function). Therefore, if a function's purpose is for side effects, you might not need to return anything.
Look up "functional programming" if you're interested in a little bit of theory.

Here:
mountain = myfunc("meh");
you are calling myfunc with "meh" as parameter and assign its return value to mountain. The function logs a text and finishes. Since it does not have a return statement, it returns undefined and as a result, mountain will hold undefined at the end of the day. If, instead of that, you are doing this:
mountain = myfunc;
then the function named myfunc will be assigned to mountain, so, if you call mountain after this operation, it will execute myfunc.
My question here I guess is what does it really mean to be able to
assign one function variable to another (mountain = myfunc) and is
there a real world usage to such a "feature"? If not, why does
Javascript allow such an assignment?
The meaning of that is that you are able to store functions inside variables. It is a very useful feature, which you are using yourself when you define landscape, myfunc and mountain initially. Basically, a function can have properties, so there is literally an arsenal of possibilities you can do with a variable holding a function.

Related

Correct Syntax For Using The Returned Variable From A Function?

I have a function that returns a variable, I'd just like to know what's the correct syntax for doing something (such as doing math or writing a new variable using that returned variable.
Example Function:
function exampleFunction(number) {
var data_filter = number + number;
return data_filter;
}
The function returns data_filter, and I'd like to know what's the correct syntax for doing something with it, such as inputting it in another function.
What you have here is fine.
As one of the comment suggests typically you assign the result to a variable. Take a simple example here:
let myNumber = 10;
let myHalvedNumber = halveNumber(myNumber);
console.log(myNumber)
console.log(myHalvedNumber);
function halveNumber(numberToHalve){
return numberToHalve/2;
}
The best way to think about it in practice is to treat the function/input combination { f(x) } as a proxy for the result itself. This means that both of these examples are correct and how you choose to employ it is your own preference.
//These two approaches are identical and both valid:
//1) Assign to a variable for further use - typically better for variable re-use:
let myHalvedNumber = halveNumber(10);
aSecondFunction(myHalvedNumber);
//2) Use the result directly in a second call - typically shorter and arguably easier to maintain/read
aSecondFunction(halveNumber(10));
function halveNumber(myNumber){
return myNumber/2;
}
function aSecondFunction (myNumber){
console.log("the number is: " + myNumber)
}

Is it good practice to override function parameter value?

In JavaScript consider I am trying to append a new value and return it.
I have below example regarding overriding parameter value
The below function receives a string value as param and overriding the param with new value and returning it.
function test(value) {
value = value + "hi";
return value;
}
console.log(test("Hello"));
The below function receives a string value as param. I would like to append a new value and return it. So I assigned value to a local variable and then appended strong to a new variable and returning it.
function test(value) {
let temp = value;
temp = value + "hi";
return temp;
}
console.log(test("Hello"));
I am calling it and passing value
test(“Hello”);
Which one is recommended from above?
It's purely a matter of style. Some people think you should leave parameter values alone, others think it's fine to change them.¹
From a practical perspective, it doesn't cause any harm. That is, there is no hidden side-effect to doing so. In particular, since JavaScript is purely pass-by-value, reassigning the parameter can't have any effect on whatever argument was used to fill in that parameter:
function test(value) {
value = value + "hi";
return value;
}
let a = "let's say ";
let b = test(a);
console.log(b); // "let's say hi"
console.log(a === b); // false, `a` was not modified
Your version with temp can be simpler, though:
function test(value) {
let temp = value + "hi";
return temp;
}
(or even
function test(value) {
return value + "hi";
}
but I figure it's highly simplified for the question.)
¹ (I happen to be in the latter camp, but that's neither here nor there.)
Yes, this is not at all wrong and is often done by many programmers across many languages. It is a common practice.
You can use it in cases where you want to use the parameter value inside the function but after making certain modifications to it.
For example, I might want to add two numbers using a function add(a, b) where a and b can be strings or integers or floats.
But just to be sure about it, I can define the add function in the following way:
function add(a,b) {
a = parseFloat(a);
b = parseFloat(b);
return a + b;
}
and this is perfectly fine. This way I can be always sure that there will be no exceptions thrown or in case parameters were passed as strings, it doesn't returns 12 (if I said add(1,2)) when really it should have been 3.
By making parameter overriding a common practice and incorporating it into your coding style, you spare the browser from creating or defining new variables just to modify those variable values. This might not mean much in small applications, but in large scale heavy applications, it might make a noticeable difference especially on low end devices.
The short answer is: it's only a matter of style.
However, this isn't always right. When passing objects, they will be passed by reference, meaning that every change you'll make to the parameter will affect the original object:
const obj = {originalValue: true};
function modifyObject(input) {
input.originalValue = false; // The change happens here
return input; // So it will take place regardless of this line
}
console.log('before:', obj);
modifyObject(obj); // See? we don't even retrieve the return value
console.log('after:', obj);
If we were talking about Java, then creating a new variable would be good practice. As there is something called the Garbage Collector that collects unused variables, etc. and discards them. So keeping a link to the original variable wouldn't allow the collector to discard the variable. (I read this somewhere, but some people said to me it doesn't really work this way, so read more about this online if you want)
In JavaScript, however, it doesn't really matter. It depends on you. Your style. It also depends on the situation as it can be useful sometimes. But really it doesn't really matter. Do as you like.
If you want to simplify it you can do as #T.JCrowder said:
function test(value){
return value+ “hi”;
}
That's about it.
Using ES6 Template literals
function test(value){
return `${value} hi`;
}

Javascript, SOAP, Execute, Variable and function call

Is this
var result = XrmServiceToolkit.Soap.Execute(setStateRequest);
just storing the function into the variable,
executing and storing the return value into the variable,
or doing both?
Unfortunately I wasn't able to find something useful in the internet. Looking at http://xrmservicetoolkit.codeplex.com/wikipage?title=Soap%20Functions
it looks like the function is executed but i am not sure.
I also tested it with a normal Javascript inside the chrome browser and got this result:
> function test(a){
console.log(a);
};
undefined
Calling the function normal
> test("asd");
asd
With a variable declaration
> var x = test("asd");
asd
But it looks like the variable does not contain any information
> console.log(x);
undefined
> x
undefined
Now I am completely confused. Why is the function called as variable when it is never stored? I am new to Javascript and need to understand what this is exactly doing.
It is storing the return value of the function into a variable.
The reason your test function is not working is because you don't return a value in test.
function test(num) {
return num * 2;
}
var doubled = test(2);
// doubled now contains 4
var doubleVariable = test;
// doubleVariable is now the same as test
doubleVariable(2)
// returns 4
This article may clarify things a bit more

Trying to understand this function as value

I got this code from the Headfirst Javascript book. I changed the function names to be clearer. I'm trying to wrap my head around this.
I assigned add to the function outer with a number. That number remains for some reason - returns a reference to inner with n = num (which returns the added values?
Anytime I change outers n value, the inner will use that new value?
I believe I'm right on that. Is there anywhere I can read more about it? See better examples? Or can anyone explain this better?
function outer(n) {
var inner = function(x) { //or x = 0
return n + (x || 0); //added default 0 for testing to prevent NaN
}
return inner;
}
var num = 2;
var add = outer(num);
console.log(`Adding 2 to num(${num}): ${add(2)}`);
add = outer(5);
console.log(add());
console.log(add(2));
In JavaScript, functions can act as regular data. If you are OK with the idea of passing a number or string around, then passing a function around is no different. This allows you the ability to do some very cool and powerful things.
Here, instead of the add function simply giving you your numeric answer, it's giving you back a function with your number embedded into it. This means that add doesn't really add anything, add is a function for creating functions (similar to the idea of a "Factory" in class based programming).
Changing the names may make things easier:
function createAddFunction(numberThatWillBeHardWiredIntoReturnedFunction) {
var resultingFunction= function(x) { //or x = 0
return numberThatWillBeHardWiredIntoReturnedFunction + (x || 0);
}
return resultingFunction;
}
var num = 2;
// This will cause add to be a function that is hard-wired to add 2 to another number
var add = createAddFunction(num);
console.log(`Adding 2 to num(${num}): ${add(2)}`);
// This will cause add to be a function that is hard-wired to add 5 to another number
add = createAddFunction(5);
console.log(add());
console.log(add(2));
Let's rename the functions to make it even clearer. The outer function takes a parameter and uses it to create a new function. This new function is returned for future use.
function createFunctionThatAdds(n){
var adds_n = function(x) { return n + (x || 0); };
return adds_n;
}
var adds_2 = createFunctionThatAdds(2);
var adds_5 = createFunctionThatAdds(5);
console.log(adds_2(10));
console.log(adds_5(10));
The technique used is called currying. It's part of functional javascript.
You can read more about it here.
The idea behind it is that you can use a function to generate another function, which you can use further in your code.
Currying is made possible, because of a closure.
There are a lot of libraries that are built based on that principe, for example Ramda.

Give eval a value in JavaScript

very basic JavaScript programmer here!
I was busy on some code with variables that look like this:
blocktype1;
blocktype2;
blocktype3;
blocktype4;
... //everything between blocktype4 and blocktype70, the three dots are not actual code!
blocktype70;
Now I was using eval() in a function where a value was given to one of the blocktype variables. The blocktype depended on the variable "number".
This is what I had for that part:
eval("blocktype" + number) = 3
What I want is, say "number" is 27, then I want the variable blocktype27 to get a value of 3.
When I check the console it says:
ReferenceError: Invalid left-hand side in assignment
Could anyone possibly help me?
I would prefer just vanilla JavaScript and still the use of eval.
Thank you for your time!
The 'correct' solution would probably be to use an Array which is ideal for sequences and are accessible by index.
var number = 1;
var val = 3;
var blocktype = []; // so clean
blocktype[number] = val;
However, properties can be accessed as with the bracket notation as well. This assumes the variables are in global scope and are thus properties of the global (window) object.
var blocktype1; // .. etc
window["blocktype" + number] = val;
The problem with the eval is that is effectively the same as doing f() = 3 which does not make sense: only variables/properties can be assigned to1.
However eval is a built-in function and the results of a function cannot be assigned to, per the error message. It could be written as
var blocktype1; // .. etc (see dandavis' comment)
eval("blocktype" + number + " = " + val);
// What is actually eval'd is:
// eval("blocktype1 = 3")
which quickly exposes a flaw with eval. If val was the string "Hello world!" with would result in eval("blocktype1 = Hello world!") which is clearly invalid.
1 For the gritty: the left-hand side of an assignment has to be a Reference Specification Type, which is a more wordy way of describining the above behavior. (It is not possible for a JavaScript function to return a RST, although it could technically be done for vendor host objects.)
Feel free not to accept this, since it's specifically not using eval(), but:
You can allocate an array of size 71 like so:
var blocktype = new Array(71);
(your number values apparently start at 1, so we'll have to ignore the first element, blocktype[0], and leave room for blocktype[70], the 71st)
You can now assign elements like this:
blocktype[number] = 3;
and use them like so:
alert( blocktype[number] );

Categories