How this works? I can't understand this snippet [closed] - javascript

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 3 years ago.
Improve this question
let unrealFunctionToUnderstand = () => {
let tryToUnderstandThis = () => 666;
console.log('I\'m calling once time! :D');
return tryToUnderstandThis;
}
let hardcoreLesson = unrealFunctionToUnderstand();
console.log(hardcoreLesson());
console.log(hardcoreLesson());
I cant understand this code, my friend send me this...

unrealFunctionToUnderstand is a function. When called it logs "I'm calling once time! :D".
It also returns another function (tryToUnderstandThis) when called.
After defining this function you are (1) calling it unrealFunctionToUnderstand(), then (2) assigning it's returned value (tryToUnderstandThis) to hardcoreLesson. Then you are calling hardcoreLesson (reference to tryToUnderstandThis) twice and logging the result.
So you are calling unrealFunctionToUnderstand once, and it logs "I'm calling once time! :D", then calling tryToUnderstandThis twice, and it logs "666" twice.
Can you notice how I "ran" this code on paper? This is how you answer questions like this yourself. You interpret the code the same way the browser would, on paper. It becomes easier to pinpoint language constructs you don't understand or know yet, so you can first learn / ask about those. Then, if you understand each part, it becomes clear what is executed and why.

everything in javascript is an object, including functions. Which means you can return a function from a function.
That is exactly what unrealFunctionToUnderstand() is - it is a function which returns a function.
So, you call it once:
let hardcoreLesson = unrealFunctionToUnderstand();
Hence the console output only displays once. And you now have a reference to a function which simply returns the value 666.
let tryToUnderstandThis = () => 666;
....
return tryToUnderstandThis;
When you execute that, you get back the response.

hardcoreLesson store the value return by this function unrealFunctionToUnderstand.
So unrealFunctionToUnderstand calling only one time.
as hardcoreLesson store the value it's shows 2 times as it's called two time.

If you are familiar with any other programming language like C or Java, then you will be familiar with the following syntax.
function functionName(argument1, argument2, ...) {
// function body
// return statement
}
The new version of javascript introduces the arrow operator => to reduce your effort of writing single line functions. This is similar to lamda/inline function used mostly for single line functions.
So if you have a following function
function increment (value) {
return value + 1;
}
you can replace it with
increment(value) => value + 1
The other answers should help you understand how the function are also objects and how it can be called in different ways.
Some helpful links
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36

Related

Should I have a wrapping function that simply passes arguments through to another function, or assign the other function directly? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Edit: If the answer to this question is simply a matter of style or preference, then that's ok, I'll just pick one. What I'm really after though is whether anyone can point out a good reason for why the second way would be a bad choice. They both work.
If I have a reference to a function that takes some parameter(s) and returns the result of calling another function with that same given parameter(s), is it ok to assign the second function to the reference directly rather than having this
surperfluous 'pass-through' going on?
For example, instead of
const fn1 = x => fn2(x) // (1) pass-through call
I would have
const fn1 = fn2 // (2) assigning
Is there a reason why I should not do this?
One possible reason that I can think of off the top of my head is that I lose control over what parameters are passed to fn2. For example say that fn2 takes two parameters, like so
const fn2 = (x, y) => // do something, using y if it's given to produce a different result
where the second parameter y is optional.
In (1), when someone calls fn1 with a second argument it's ignored and fn2 is called with the first parameter x only. Ie I have control and force a single argument only to be passed to fn2.
In (2), on the other hand, when someone calls fn1 they're in control of whether one or two arguments are passed through to fn2, since they're actually calling fn2 directly.
Is (2) considered bad? Or maybe it's preferred even?
In case someone wonders why fn1 exists at all when it's just passing through to fn2, it's because I like to do this to improve the clarity of my code. For example, rather than calling
createFilledCircle(5)
I may call
createPositionMarker(5)
which simply calls createFilledCircle but makes it clearer what's going on. Ie I would have one of these, and I'm wondering if the second way is ok, preferred, or bad.
const createPositionMarker = radius => createFilledCircle(radius) // (1) pass-through call
const createPositionMarker = createFilledCircle // (2) assigning
Thanks for any input! :)

Bluebird Error: Generator Function Must Be A Function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am getting the error:
bluebird.js:2118 Uncaught TypeError: generatorFunction must be a function
But I don't understand why this error is occurring, as I am passing it a generatorFunction.
export class Welcome {
fetch() {
Promise.coroutine(this.userData());
}
userData = function* getData() {
this.lotsData = yield this.testApi.getMock();
this.lotsData = JSON.stringify(this.lotsData, null, 4);
}
}
So a click event calls fetch() and that calls this.userData(). This is the console dump of this.userData:
GeneratorFunctionPrototype {}
_invoke: invoke(method, arg)
__proto__: GeneratorFunctionPrototype
Which tells me it most certainly is a generator. I am using all of this in an aurelia class if that somehow makes any difference (which it shouldn't I don't think). So why is it erroring that the generatorFuction must be a function?
The limited amount of code you posted is riddled with errors, but there is not enough to know what is correct and what is incorrect.
One thing is for sure this.userData() is a function call and not a reference to a function, which is what .coroutine() is expecting.
Whatever type returned by this.testApi.getMock() is what is being yielded, which we have no idea given what you posted, but that is probably not even relevant at this point, because what is returned is probably unknown/null anyway because you are assigning the yield to a variable of questionable scope. Your code is nowhere near the example from the documentation
PingPong.prototype.ping = Promise.coroutine(function* (val) {
console.log("Ping?", val)
yield Promise.delay(500)
this.pong(val+1)
});
The documentation has a very clear and well defined example you should follow, explicitly until you understand what you are actually doing.

Call Back Concept in Javascript [closed]

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.

Why does the new Function() return this output? [closed]

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.

Difference between console.log and return in javascript? [closed]

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 9 years ago.
Improve this question
What are the instances when you would use console.log and return in javascript?
I've just started learning javascript and I want to know what are some instances when I'd use them?
Actually there's nothing in common between them.
return - returns execution to the caller with optional result
console.log() - logs out information in console.
From http://blogs.msdn.com/b/cdndevs/archive/2011/05/26/console-log-say-goodbye-to-javascript-alerts-for-debugging.aspx
console.log will display the parameter passed to the log method in the
console window. Use this method to display a string or variable in the
console window.
You can use the console class in your code as well, much like we can
use JavaScript alerts.
<script type = "text/javascript">
function tryConsole() {
console.log("hello world");
}
</script>
When using the return statement, the function will stop executing, and return the specified value.
Console.log emits a message to your browsers Console, and is usually used to emit debugging messages (research your browser's developer tools)
return is a keyword that terminates a function and possibly returns a value to the caller of that function.
console.log prints the string in firebug console. Just found the below link, you can refer
What is console.log and how do I use it?
and
return just return from the function without processing further code or you can say, A function immediately stops at the point where return is called.
They're for completely different purposes, console.log will return the value to the browser's console if it's supported, return will return a value from the javascript function
console.log will not influence the flow of your code. Return values will cause reactions in your script, it really matters if you return false or true or whatever. For debugging I strongly suggest using console.log.
Inside a clousure the return will return some value, and console.log will log some value in browser console. Console.log is like a debug tool for not good browsers like IE.

Categories

Resources