Understanding the return statement. - javascript

I have looked at many examples but still cant figure how the return statement works.
function One() {
var newVal = 0;
Too();
console.log(newVal);
}
function Too(newVal) {
++newVal;
return(newVal);
}
Shouldn't this print 1 to the console? What I'm really trying to do is to have function Too increase newVal by 1 every time it's called. But I cant even figure out how to get the return statement to work. I should mention I don't want to use global variables. Thanks for any help.

Shouldn't this print 1 to the console?
No. The newVal inside Too is not the newVal inside One. They're completely separate.
What I'm really trying to do is to have function Too increase newVal by 1 every time it's called.
It can't, JavaScript doesn't have any mechanism for passing variables by reference like some other languages do (C#'s ref and out arguments, for instance). The closest you can come is to pass in a reference to an object and modify the object's state (which is really quite different and I won't go into it here as it would confuse things :-) ).
None of which has anything to do with the return statement.
The simplest way to do what you were describing is this:
function One() {
var newVal = 0;
newVal = Too(newVal);
console.log(newVal);
}
function Too(arg) {
++arg;
return arg;
}
Here's what happens when we call One:
A local variable called newVal is created.
Its value is set to 0.
A copy of its value is passed into the function Too as an argument. This has no link back to the newVal variable.
Too is called, accepting that value in its arg argument (arguments in JavaScript are effectively local variables).
Too increments the value in arg.
Too returns a copy of the value held by arg as its return value.
The return value of Too is assigned to the variable newVal.
We output that value (by passing it into console.log).

No, it shouldn't. The return statement establishes what the value of the function invocation will be in the calling environment when control returns there. Since your calling environment doesn't use the return value, there's no net effect.
Here's how you'd get the value back:
newVal = Too(newVal);
If you want to make a function that acts as a counter, such that each time you call it you get a new number back, you can do something like this:
var counter = function(initial) {
var c = initial || 0;
return function() {
return c++;
};
}(0);
What that does is use an anonymous function to set up a persistent environment for another function, which is returned from the outer one when it's (immediately) invoked. The returned function can then be called to return a new value from its private counter (the variable "c"):
var currentCount = counter();
alert(currentCount); // 0, the first time
currentCount = counter();
alert(currentCount); // 1, and so on

If a function return a value you need to call that function in your console.log or capture the returned value.
function One() {
var newVal = 0;
console.log(Too(newVal));
}
function Too(newVal) {
++newVal;
return(newVal);
}

Related

Currying in javascript multiple calls

I'm quite clear with the concept of closure in JavaScript but at some point i got confused when i need to solve the questions.
clos() => print("AB")
clos()() => print("ABC")
clos()()() => print("ABCC")
clos()()()() => print("ABCCC")
clos()()()()('xyz') => print("ABCCCxyz")
I have to implement above method in javascript
Can someone help me in implementing the above use case.
Solution Tried
function clos(...n){
let counter = 0;
const initial = "AB"
return function(param) {
counter = counter + 1;
return initial + "C".repeat(counter)
};
}
What you are trying to implement is not possible. However, there's one alternative that you can try, which will work.
Here's the code:
function c() {
this.counter = 0;
const initial = 'AB';
this.recursive = function(param) {
this.counter += 1;
return typeof param === 'undefined' ? initial + 'C'.repeat(counter - 1) + param : this.recursive;
}
return this.recursive
}
As you can see, instead of declaring a temporary variable, we are binding to the function via the this keyword the counter variable.
The question would be, how can the this keyword be used inside the recursive function, since it is not defined anywhere? Well, the reason is because the recursive function it is an anonymous function. From the mdn docs, regarding the name of a function:
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
Anonymous functions do not have a "self", therefore the this keyword does not work in them, it is not defined. What they use instead, it is they closure's self, in this case the c function, which does have a self as it is not an anonymous function, and it has the counter prop defined.
Finally, explaining the code a bit, JS must return a value. In this case, you want to keep returning functions and in the last call return a string. It is not possible to know if which is the last call of the returning function. What we do instead is to pass an argument to the last call, which is what is checked in the ternary operator:
If param is not undefined, meaning that a string has been passed, we will keep returning a function.
Otherwise, we return the resulting value.
See that we increment the counter value on every call.

JavaScript setting value to variable properties on a function call

I found that there are these two ways that a variable property value can be updated on a function call
Example 1:
function bar( arg ) {
return arg + 1;
}
var foo = {
num: 1
};
foo.num = bar( foo.num );
console.log( foo.num );
Example 2:
function bar( arg ) {
arg.num = arg.num + 1;
}
var foo = {
num: 1
};
bar( foo );
console.log( foo.num );
I want to know what are the proper naming convention for each of the method calls.
Also can anyone explain, how it is possible to update the original variable value inside a closed function operation as shown in example 2?
Primitive parameters (such as a number) are passed to functions by
value; the value is passed to the function, but if the function
changes the value of the parameter, this change is not reflected
globally or in the calling function.
If you pass an object (i.e. a non-primitive value, such as Array or a
user-defined object) as a parameter and the function changes the
object's properties, that change is visible outside the function.
Source : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
Well in javascript objects are passed by reference so when you pass a object to a function you're passing it's memory reference not a copy.
So when you update value in the function it updates the value at reference.
function bar(arg) {
arg.num = arg.num + 1;
}
var foo = {
num: 1
};
bar(foo);
console.log(foo.num);
When you pass a primitive value it is passed by value. It passes a copy of value so whatever changes you do in close function will not affect the original value.
function bar(arg) {
arg = arg + 1;
}
var foo = 1
bar(foo);
console.log(foo);
I want to know what are the proper naming convention for each of the methods.
There are no naming conventions for functions (I would only call them methods if they are directly associated to an object), except thar the name is camelCase. However there is a convention in functional programming that functions that return something are pure (they do not change anything, but just return something new, like your first function), and functions that return nothing are impure, they change something. Wether you strictly follow that pattern depends on your codingstyle, I follow that often but not always. It is also a bit harder in JS as JS is not typed.
also can anyone explain, how it is possible to update the original variable value inside a closed function operation as shown in example 2?
It is impossible. If you pass a number, it is passed as a value, you have no way to find out where that number belongs to. Thats a good thing as you can always keep track which function is able to mutate an object. bar(foo) is, bar(foo.num) is not.

How do I create a function that increments the value of a global value?

I am currently trying to perform some simple actions on a variable that I've given the value of zero. First of all, I am declaring a variable and giving it a value (0). Secondly, I am creating a function which is supposed to increment the value of my variable when the function is invoked. This is my code:
var orderCount = 0;
function takeOrder(orderCount) {
return orderCount++;
}
takeOrder(orderCount);
takeOrder(orderCount);
alert(orderCount);
The exptected result of the code snippet above would be "2", since the function is invoked twice and the number 0 therefore should be incremented twice.
I have also tried incrementing the variable "orderCount" with the following code instead of the one posted above:
function takeOrder(orderCount) {
return orderCount + 1;
}
Neither works. What am I doing wrong?
Remove orderCount from your parameter list, and don't include it as an argument when calling the function. By specifying it as a parameter, you're shadowing (hiding) the global variable that takeOrder closes over.
var orderCount = 0;
function takeOrder() {
// ^----- don't include `orderCount` as a parameter
return orderCount++;
}
takeOrder(); // <== don't specify it when calling the
takeOrder(); // <== function (though it would just be ignored)
alert(orderCount);
Couple of facts:
Parameter of the function acts like a function-scoped variable. You
can re-assign it, increment it etc. All these changes are gone once function finishes its execution.
Local variables named the same as "global" ones hide the latter
inside function body and therefore make all in-function changes isolated from the outside world.
Changing the parameter name will not help either, because the value of the global variable will be placed on the function call stack. In fact, passing any variable is not helpful at all.
Typical solution is to not use parameters at all and make your function change variable in the outside scope directly.
It is, however, possible to emulate passing a "reference" to a variable. If you really want your function to not know the global variable name:
var order = { count: 0 };
var anotherOrder = { count: 0 };
function takeOrder(order) {
order.count++;
}
takeOrder(order);
takeOrder(order);
takeOrder(anotherOrder);
console.log("Order:"+order.count);
console.log("Another order:"+anotherOrder.count);
Simply call the function without passing the parameter
var orderCount = 0;
function takeOrder() {
return orderCount++;
}
takeOrder();
takeOrder();
alert(orderCount);

How does Javascript's Scope work, getting unexpected behavior?

Heres a sample bit of code, similar to that that gave me grief:
for(var i=0;i<3;i++){
var Proof = true
if (i == 0){
Proof = false
//var CallBack = function(){alert(Proof);}; // true????
var CallBack = function(){alert(i);};
}
}
// Whatever happened to local scope? shouldn't CallBack be undefined now?
CallBack()// alert(3), should be 0?
CallBack isn't undefined, it alerts true or 3, could someone please explain to me what is going on that is making it act like this? is there some local keyword I am missing, or does JS not have scope? I am using no framework, and would appreciate some help on how to sort this out, and do this kind of thing properly...
JavaScript doesn't have block scope at all (yet, see below). All variables are declared throughout the function in which they appear (or throughout the global scope, if they're at global scope).
Assuming the code you've quoted is the only code in its scope, it's exactly the same as this:
var i;
var Proof;
var Callback;
for(i=0;i<3;i++){
Proof = true
if (i == 0){
Proof = false
//CallBack = function(){alert(Proof);}; // true????
CallBack = function(){alert(i);};
}
}
// Whatever happened to local scope? shouldn't CallBack be undefined now?
CallBack()// alert(3), should be 0?
More (on my blog): Poor, misunderstood var
CallBack()// alert(3), should be 0?
No, 3 is correct, because that's the value of i as of when CallBack is called. CallBack is a closure over the context in which it was created. It has an enduring reference to the context (including the i variable), not a copy of what existed when it was created.
If you wanted to get 0 instead, you'd have to have CallBack close over something other than i, something that won't change. The typical way to do that is to use a builder function you pass a value into:
function buildCallBack(index) {
return function() { alert(index); };
}
Then:
CallBack = buildCallBack(i);
The value of i is passed into buildCallBack as the argument index. buildCallBack creates a function closing over the context of that call to buildCallBack and using that index argument. Since that argument's value is never changed, the callback alerts 0 (in this case) rather than 3.
More (on my blog): Closures are not complicated
The reason I said "yet" above is that the next version of the spec (ES6) will introduce new block-scope semantics for the new let and const keywords and block function declarations. var will be unchanged, but if you use let to declare a variable instead, it has block scope rather than function/global scope.
When CallBack is being called, for loop is finished already. So i equals 3.
If you want i to be local, you should write like this:
var CallBack;
for(var i=0;i<3;i++){
(function(index) {
var Proof = true
if (index == 0){
Proof = false
//var CallBack = function(){alert(Proof);}; // true????
CallBack = function(){alert(index);};
}
})(i);
}
CallBack()
Here is a demo
UPDATE
Here is an alternative:
var CallBack;
for(var i=0;i<3;i++){
var Proof = true
if (i == 0){
Proof = false
CallBack = (function(index) {
return function(){alert(index);};
})(i);
}
}
CallBack()
demo
UPDATE 2
EXPLAINATION:
By writing (function(index) {...})(i) we declare an anonymous function and call it immediately (we could also write function(index) {...}(i) but I think the first case is clearer). In javascript, function is also a way to set another scope of variables, so in our case we "remember" the current state of i variable in index variable that is visible only within our anonymous function.
And when the 'CallBack' is called, alert shows 0 because i was equal 0 when that function was called.

What is the relationship between a function and a value?

What is the relationship between a function and a value? I thought that a function was a type of value; however, functions both contain values (arguments) and return values too.
I'm (obviously) new to programming, and want to ensure that I have a solid conceptual foundation as I move my way through JavaScript.
Functions do things. Variables hold values (data).
A function can accept data as arguments. A function can also return data, but does not have to. Consider this function which just adds two numbers together:
function addNumbers(numberA, numberB) {
var total = numberA + numberB;
console.log(total);
}
This is a function which accepts two arguments. Within the function's code block, those arguments' values are assigned to the variables numberA and numberB. The function's code creates another variable, total, and assigns the value of numberA added to the value of numberB. The function then calls another function, console.log, with the value of total passed in as an argument.
Now, the function can also return values. Let's modify this function a bit:
function addNumbers(numberA, numberB) {
var total = numberA + numberB;
return total;
}
If you were to call this function now, you get back the value of total. If I were to run this:
console.log(addNumbers(5, 5));
You would see 10 in the console. My number literal values were passed as arguments to addNumbers. The function did its work and returned to me the value of its total variable. This value is now passed in as an argument to console.log.
If that isn't crystal clear yet, then please read other tutorials online before continuing.
Now, in JavaScript functions are just like anything else. You can assign them to variables as well!
var newAddNumbers = addNumbers;
console.log(newAddNumbers(5, 5)); // Also returns 10 in the console
When you type:
function someFunction () {
This is no different than:
var someFunction = function () {
The function itself is assigned to the variable someFunction. In our original example, the function itself was assigned to addNumbers. So yes, function is a type just like number, object, boolean, etc.
If I have a function:
function add(a, b) {
return a + b;
}
add is a function. All functions are values; I can place them in a variable or pass them as an argument, for example.
a and b are arguments of add, but the function has not been called, so they do not have values. Similarly, the function has been called, so it has no return value.
When I call the function:
add(1, 2);
The function executes with a and b initially set to 1 and 2 respectively for that invocation.
If I call it again with different arguments:
add(3, 4);
Then this time a and b are initially set to 3 and 4; however, these a and b not only have different values than the last time; they really are different variables. Every time you call a function, the arguments are essentially variables, which are local not only to that function but to that invocation of that function.

Categories