JavaScript recursion variable value undefined [duplicate] - javascript

This question already has answers here:
Recursive function does not return specified value
(2 answers)
Recursive function returns undefined
(3 answers)
Closed 3 years ago.
When I run the below JS, the console correctly logs a as string: "foo", but then the return value is undefined. typeof() also says it's a string. There is no change from line 5 to 6 (the console.log and the return), so how can this spontaneously become undefined?
let a = "foo";
let c = 0;
function test() {
if (c === 5) {
console.log(a);
return a;
} else {
c++;
test();
}
}

In your recursive call, use return test():
let a = "foo";
let c = 0;
function test() {
if (c === 5) {
console.log(a);
return a;
} else {
c++;
return test();
}
}
Explanation: Consider the first call of test() in your original code. If c is 5, it will return a value, but otherwise, it won't return anything. Sure it will execute a second call of test(), but it will not return the value of that call to your main program. This is why the return statement is needed. And the same logic applies to all calls of test() where c is not equal to 5.

Related

How to call a function that returns another function in JavaScript? [duplicate]

This question already has answers here:
Functions that return a function
(10 answers)
Closed 3 years ago.
I was taking a small test online and there was this code:
function getFunc() {
var a = 7;
return function(b) {
alert(a+b);
}
}
var f = getFunc();
f(5);
I would like to know why I can't call getFunct(5) directly for example.
I don't understand the last two lines.
Why do I need to assign the function to a variable. What happens when doing f(5)?
How does JS interpret that the 5 is a variable for the inner function and not the outer?
You could call the inner function immediately after calling the first one, because the first call returns a function and the second call gives the result.
function getFunc() {
var a = 7;
return function(b) {
console.log(a + b);
}
}
getFunc()(5);
By assigning getFunc() to the variable f you actually assigned the return value i.e. inner function to f since that's what getFunc is returning. The braces () make a difference here.
However had it been f = getFunc i.e. without the braces, that would imply f is an alias for getFunc and you'd have to do f()(5) in that case.

Method return undefined [duplicate]

This question already has answers here:
How does "this" keyword work within a function?
(7 answers)
Closed 5 years ago.
I have a problem receiving a value from a void method
For example:
test() {
var x = this.test2("hi there");
console.log(x);
}
test2(data){
return data;
}
I want to receive the data from test2 but it keep saying undefined what do I do wrong in here? And how can I make this work?
It is probably so basic but I just want to know why I receive the value undefined
Add function in front of definition.
function test() {
var x = this.test2("hi there");
console.log(x);
}
function test2(data) {
return data;
}
test();
Try like this :
test(): void {
var x = this.test2("hi there")
console.log(x);
}
test2(data): void {
return data
}

Scope chain example [duplicate]

This question already has answers here:
Surprised that global variable has undefined value in JavaScript
(6 answers)
Closed 5 years ago.
So,I am trying to grasp the concept of scope chain in javascript and therefore I created the following example to check if I got it right.
Note: I am familiar with the following concepts(Execution Contexts and Lexical Environments).
Example:
function test(){
function test2(){
//This prints 2 as expected
console.log(a);
}
//This should print 1 but instead it prints undefined
console.log(a);
var a = 2;
test2();
}
var a = 1;
test();
if for example I comment the following:
//var a = 2;
Then the output in both cases is 1.
You should take a look into Hoisting Concept in JavaScript.
the JS engine will move all declaration in the top of the block before going into the execution step.
About your exemple :
function test(){
function test2(){
//This prints 2 as expected
console.log(a);
}
//This should print 1 but instead it prints undefined
console.log(a);
var a = 2;
test2();
}
var a = 1;
test();
will be treated like this
var a; // initialized to undefined
function test(){
var a; // initialized to undefined [which is printed]
function test2(){
//This prints 2 as expected
console.log(a);
}
//This will print undefined which is the actual value of a
console.log(a);
a = 2;
test2();
}
a = 1;
test();
that's why it print undefined

What is the meaning of (0, someFunction)() in javascript [duplicate]

This question already has answers here:
(1, eval)('this') vs eval('this') in JavaScript?
(4 answers)
Closed 6 years ago.
The community reviewed whether to reopen this question 3 months ago and left it closed:
Original close reason(s) were not resolved
I found this code in someone's code, it sound like this:
(0, function (arg) { ... })(this)
After I try to play around like below,
(0, function (arg) { console.log(arg) })(2);
console.log((0, 1, 2, 3));
(0, function plus1 (arg) { console.log(arg + 1) }, function plus2 (arg) { console.log(arg + 2) })(5);
I found that it will always return last item in the bracket.
I wonder what is the name of this programming pattern and what is the use case?
In this particular case it seems superfluous, but sometimes this approach is useful.
For example, with eval:
(function() {
(0,eval)("var foo = 123"); // indirect call to eval, creates global variable
})();
console.log(foo); // 123
(function() {
eval("var bar = 123"); // direct call to eval, creates local variable
})();
console.log(bar); // ReferenceError
It's also useful when you want to call a method without passing the object as the this value:
var obj = {
method: function() { return this; }
};
console.log(obj.method() === obj); // true
console.log((0,obj.method)() === obj); // false
Also note that, depending on the context, it might be the arguments separator instead of a comma operator:
console.log(
function(a, b) {
return function() { return a; };
}
(0, function (arg) { /* ... */ })(this)
); // 0
In this scenario, (0, function (arg) { /* ... */ }) are the arguments (a=0, b=function (arg) { /* ... */ }) to the function
function(a, b) {
return function() { return a; };
}
rather than the comma operator. (Then, the (this) at the end is function call with argument this to the returned function function() { return a; }. But this part is not relevant to the comma operator/argument separator difference)
It is a comma operator wrapped with a self-executing anonymous function. However, I have no idea as to why the meaningless 0 was included except for obfuscation purposes.
typical example could be,
for(var i=0,j=10; i < j; i++){
// code ...
}
comma operator would evaluate expressions from left-to-right and return result of right most expression
// e.g.
var a = 1, b= 2, c = 3, d = function(){ console.log("a => " + a) }()

How to refer a undefined parameter in global scope

var a = 2;
function f(a) {return a;}
console.log(f(1));// return 1
console.log(f());// return undefined, but I want to make it return 2...
f() returns undefined, but I want to it refer the variable a in global scope. How could I achieve that?
var a = 2;
function f(b) {
return b || a;
}
You need to use a different name for the function argument, else it's going to shadow the outer a and won't give you any chance to return it. Then it's a simple matter of deciding which value to return. Here I'm using a simple falsey check, you may or may not want to use something more detailed like typeof b === 'undefined' or such.
Use arguments.length to test if a parameter was passed to the function:
var a = 2;
function f(b) {
if(arguments.length===1) return b;
return a;
}
console.log(f(3)); //3
console.log(f(undefined)); //undefined
console.log(f(0)); //0
console.log(f()); //2
you could do something like this, which checks if the variable has been defined or not.
var a = 2;
function f(x) {
return (typeof x==="undefined")? a : x;
}
console.log(f(1));// return 1
console.log(f());// return 2

Categories

Resources