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.
Related
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 11 months ago.
Improve this question
Let's say I have this function in JavaScript:
function foo(a) {
a.item = "four"
return a
}
b = {
item: "three"
}
b = foo(b)
console.log(b)
Since JavaScript is a call-by-sharing language there is no need to return a, the object b would have the same final value with the below code:
function foo(a) {
a.item = "four"
return a
}
b = {
item: "three"
}
foo(b)
console.log(b)
Is it bad practice to use return b for better readability even though it is not needed
Are there any downsides to returning the object?
You're correct, in your example the return statement is unnecessary, strictly speaking. Also, just as a point of clarification, while JS passes objects by reference, primitive types are passed by value.
However, it is considered a JS best practice to avoid mutating function parameters. It can very quickly get very confusing when you have many functions performing actions on the same object that is getting passed around and mutated. So, in fact, I would consider it a bad practice to write a mutating function that does not involve returning a value.
Following that idea, your example would look like:
function foo(a) {
// Copy our input (assuming 'a' only contains primitive values)
const output = { ...a };
output.item = 'four';
return output;
}
const b = { item: 'three' };
const c = foo(b);
// b is unchanged
The built-in Array.prototype.sort() method returns the array even though it's sorting it in place.
Whether this provides better readability is a matter of personal preference. But it can make it easier to work with arrays/objects that are created on the fly, e.g.
sorted_words = string.split(" ").sort();
If it didn't return the array, you'd have to do this in two steps:
sorted_words = string.split(" ")
sorted_words.sort();
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 5 years ago.
Improve this question
In ES6, it's possible to use ...arguments to pass all arguments of one function to another, e.g.
function foo(a, b) {
return bar(...arguments);
}
function bar(a, b) {
return a + b;
}
foo(1, 2); // returns 3
I "discovered" this idiom myself, and am wondering if there are any downsides to it, or whether it's considered a bad practice?
...am wondering if there are any downsides to it...
Not really, other than a couple of points to be aware of:
arguments in loose mode has some minor performance problems (nothing to worry about in normal situations).
Arrow functions don't have their own arguments, so that won't work in an arrow function; you'll either get a ReferencError (if the arrow function is at the top level) or the arguments from the nearest containing function function (or method) (because arrows close over arguments [and this and super]), which may not be what you want.
You're using spread notation, so you might consider using rest notation as well:
function foo(...args) {
return bar(...args);
}
function bar(a, b) {
return a + b;
}
console.log(foo(1, 2)); // returns 3
That doesn't have the (minor) performance issues with arguments, works in arrow functions, and is clear about what you mean.
not really any downsides, you just have to make sure that if your arguments is an array, that it is in the right order for the arguments of the function that you are calling.
arguments variable in the function contains all arguments passed to the function. This can be used if you have various number of parameters and you don't know how many.
Starting from ES6 if you want to pass into the function various number of parameters, you can use rest parameters.
function foo(...rest) {
return bar(...rest);
}
function bar(a, b) {
return a + b;
}
foo(1, 2);
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.
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.