Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I just started to learn javascript and programming overall. I found these examples and trying to figure out results of those two functions.
First:
(function(){
var x = y = 11;
})();
console.log("x = " + (typeof x !== 'undefined'));
console.log("y = " + (typeof y !== 'undefined'));
Results are true and false.
Is it because var x is declared with var keyword so it is local var and y is not?
and second example:
(function(){
console.log("a");
setTimeout(function(){console.log("x")}, 1000);
setTimeout(function(){console.log("y")}, 0);
console.log("b");
})();
Please explain me the second example?
If I got it right, setTimeout will wait for execution even if time is set to 0.
Thanks
First: Correct. If you'd remove the 'var' from the 'x'-declaration that variable would also be available outside the function scope.
Second: The javascript function 'setTimeout' starts an asynchronous operation. In other words, the passed function gets added at the end of the queue to be operated at a later time, even if the passed time is 0ms.
The 'console.log' functions run synchronously, so they always will be executed before the functions given with the 'setTimeout'-function.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
The community is reviewing whether to reopen this question as of 1 year ago.
Improve this question
This question is from an online quiz and I'm confused by it. I feel its the third one but I get undefined.
Which choice is an example of an arrow function, if c is defined in the outer scope.
a,b =>c;
{a,b} => c;
(a,b) =>c; //this one.
a,b => {return c;}
The question is primarily asking about syntax. The third option is indeed the correct choice, because the function parameters a and b must be enclosed in parenthesis ( and ).
You get undefined because c must first be defined.
var c = 'foo'; // define c in outer scope
var f = (a,b) => c; // define the arrow function
var result = f(1,2); // invoke the arrow function with some parameters
console.log(result); // examine the output is 'foo', the value of c
Only the second one has invalid syntax.
The first and last one are also valid, and employ the comma operator, with the arrow function being the right hand operand. You'll still get a run time error if a is not a defined variable, but once it is, it is valid:
let a; // define
a,b =>c; // valid
a,b => {return c;} // valid
console.log("ok");
The third one would be the evident choice; it is also the only valid arrow function that does not need a to be defined in the outer scope.
If you call these valid functions, then c needs to be defined, which seems to be guaranteed.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
It would be very helpful, if someone explains the working of a curry function. I have read many examples, but not able to grasp it properly. Is it anyhow related to closure.
Currying is just technique, that can make use of any language feature (e.g. closures) to achieve the desired result, but it is not defined what language feature has to be used. As of that currying does not require to make use of closures (but in most of the cases closures will be used)
Here a little example of the usage of currying, with and without the usage of closure.
With the use closure:
function addition(x,y) {
if (typeof y === "undefined" ) {
return function (y) {
return x + y;
}
}
return x + y;
}
var additionRemaining = addition(3); // Currying
additionRemaining(5);//add 5 to 3
With the use of new Function instead of closure (partial evaluation):
function addition(x,y) {
if (typeof y === "undefined" ) {
return new Function('y','return '+x+' + y;');
}
return x + y;
}
var additionRemaining = addition(3); // Currying
additionRemaining(5);//add 5 to 3
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
How Java script engine handles Callback and how does the engine know that it is a callback if we pass a function as a parameter to another function.
Oversimplifying, functions are something we can pass around, like anything else. We can pass parameters that are numbers, functions, strings, etc.
Take a look at this:
// We'll just call the function passed in our function
// This is essentially a callback that does no work before
// calling the callback.
function call_function(f) {
return f();
}
var func = function(s) {console.log('func was called');}
var notAFunc = 42;
call_function(func); // func was called
call_function(notAFunc); // TypeError: number is not a function
The TypeError is the same as trying to call 42 as a function (because that's all we're doing):
42() // TypeError: number is not a function
The basics are that JavaScript doesn't do anything extra special to know if a callback you're passing is a function or not. At some point it will try to call the function, which may or may not result in an error.
EDIT
Xufox noted in a comment that the type of the paramenter could be checked, something like this:
function call_function(f) {
if (typeof f === 'function') {
return f();
}
}
It's good to keep that in mind, but that has nothing to do with the engine, it's up to the programmer to do that kind of sanity checking.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I was reading Chapter 4: Functions() of the book Javascript Enlightenment by Cody Lindley.
http://jsfiddle.net/4a860dkg/
I was playing around with functions and wanted to know why in the fiddle addNumbersA returns anonymous(num1, num2, /**/) rather than returning a function()
Can anyone tell me why does this happen?
EDIT:
1. What I want to ask is that why doesn't logging addNumbersA return me a function() as it must do.
2. When I use typeof(addNumbersA), I get a function and not a function() - whereas addNumbersB returns function().
Apologies if i'm not clear enough.
The reason console.log(addNumbersA); returns:
function anonymous(num1,num2
/**/) {
return num1 + num2
}
Is because its a functional expression. The function keyword, when used as an expression, can create a function value. A function value can do all the things that other values can do—you can use it in arbitrary expressions, not just call it. It is possible to store a function value in a new place, pass it as an argument to a function, and so on.
Similarly, console.log(addNumbersB); returns:
function (num1, num2) {
return num1 + num2;
}
You can test this out in chrome dev tools, perhaps some inspectors/js repls have different notations of shortcutting, such that you may not get EXACT output (ie. just get 'function()' in Firebug).
Function is a constructor for function.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
When you define a function as an instance of Function constructor, it is not compiled but stored as a runtime string. That's why it shows up as a function definition and not as a function object.
They will function the same except because it is compiled at the time of execution, it only has the global closure and has no knowledge of the local closure except for its own local variables.
console.log(addNumbersB); // logs function() correct!
This will not run the function, which your are expecting.
This does:
console.log(addNumbersB(2,2)); // logs 4 correct!
The above returns 4 because we call the function and pass the two numbers which are then added by the function;
The first example you give is a method rarely used for normal day to day coding, it creates a function from a string that represents valid code.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I am using javascript eval(). For some reason, it is causing bugs, so I am replacing all eval. I have replaced this
var abc = "item." + str3 + ".power";
abc = eval(abc);
with
var abc = item[str3]["power"];
But I don't understand how do I replace these two statements?
1) setTimeout(eval(reloadfunction), 180000);
2) buttonrow = buttonrow + eval(button)(i, item);
reloadfunction is a variable which gets some string value which is a function name.
button is a variable which gets some string value and executes it as function and passes "i" and "item" which are other variables.
If the variables and functions you are dealing with are global (ie. defined in the global scope) then you can use window[reloadfunction] and window[button](i,item).
If they're locally scoped, however, you will have to completely restructure your code to have something like a map of functions:
var functions = {
func1: function() {doSomething();},
func2: function() {doSomethingElse();}
};
setTimeout(functions[reloadfunction],180000);
I would use this :
setTimeout( new Function(reloadfunction) , 180000);
since it runs in its own scope. ( not global , not current but its own)
p.s. you could set context also :
new Function(reloadfunction).apply(t,[]) //immediate execute
new Function(reloadfunction).bind(t,[]) //future execute (notice ie=>9)
as for comment : here is an example :