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
I'm new to JavaScript and working on a coding challenge as part of a bootcamp application process.
The question requires writing a single function to accomplish a task.
Although I've looked far and wide, I've yet to come across an answer.
If I write a function that contains other, nested functions, would that still be considered one function?
If I write a function that contains other, nested functions, would that still be considered one function?
Yes. A function is an encapsulation unit, it's a blackbox. You can call it, and get results back, but how it is implemented does not matter when looking from outside. A function that modularises its internal implementation into multiple local function is indistinguishable from one that does not as long as it behaves the same.
Yes.
From a technical perspective you can't even write a function that doesn't call use nested functions. The act of declaring variables alone is going to call a chain of functions to allocate memory which in turn eventually calls functions in assembly which then calls functions in your processor to which calls functions to your memory driver which calls.
Similarly calling operators to set or manipulate your variables are function calls which are all layered APIS calling a chain of functions.
Suppose you write a function min that looks like this:
function min(a,b) {
return Math.min(a,b);
}
This is still a single function even though it is calling a global function.
The same logic applies if you write an internal function for a complex object
function min(data) {
var smallest = function(a,b) {
if (a.x<b.x) { return a;}
else if (a.y>b.y) { return b;}
else if (a.y<b.y) return a;
return b;
}
return smallest(data[0],data[b]);
}
Related
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
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 7 years ago.
Improve this question
How to control which function JavaScript run first,
i don't always want that particular function run first but the other.
What to do?
Javascript is single threaded, whichever function that is called is being executed in that order. The only exception to this rule is how the event loop is being executed.
So a call to setTimeout or setInterval cannot give a real idea on which method will get called first. Even if you use a setTimeout with the same interval. In thoery, the first method should be executed first in the event queue but that might be subject to implementations.
If you want to synchronize evented function, you have a while range of tools and libraries that will just what you need.
The callback method can be used to call a continuation when some kind of work is finished. This pattern has been improved in a more complex datastructure called a Promise.
Promise are pretty much the same things as callbacks but they are syntactically nicer to use.
Callback:
function foo(id, callback){
//ajax.get('/data/' + id, callback)
ajax.get('/data/' + id, function (data) {
callback(data)
})
}
foo(id, function (data) {
alert(data)
})
Promise:
function foo(id) {
return promiseGet('/data' + id)
}
foo(4).then(function (data) {
alert(data)
})
The advantage of promises is that they can be chained and thus, you can use async apis, pretty much like usually sync apis. All of the "then" parts are going to be executed in the order you added them.
Here's the site of promisejs that does a quite good explanation of promises.
https://www.promisejs.org/
Use self invoking function expression
Eg:
(function (i) {
console.log(i):
})(5);
And make sure, this comes before any similar functions, including one in the external added script
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 7 years ago.
Improve this question
I'm trying to decide what style to use for module-level function definitions.
Here are the options I've considered:
// function expression using an arrow
const foo = (arg)=> {
// ...
};
// function expression with the `function` keyword
const bar = function(arg){
// ...
};
// function declaration
function baz(arg){
// ...
}
I prefer the foo style, but it seems to be non-standard. Are there considerations against it that I haven't considered? For example, are there significant performance penalties to using function expressions, const, or arrows, either natively or when transpiling?
Here's what I have so far:
Advantages of using const with a function expression instead of using a function declaration:
Nothing is ever hoisted if you only use const and let: it makes the language simpler to work with.
Using const makes the interpreter throw an error if you try to define two functions with the same name in the same scope (this has been surprisingly helpful).
Using const lets you say what you mean: most of the time, one wants to define a function, not assign to a variable.
Using const instead of a function declaration makes it clearer that functions are values in JS.
Disadvantages of function expressions:
A function declaration causes both the variable declaration and function body to be hoisted to the top of the current function body (I think). This may actually be helpful if you like to lay your JS files out with function-using code on top and function definitions at the bottom.
I couldn't find any cases where function expressions are harder to debug or where it was harder to use recursion with function expressions.
Advantages of using arrows instead of the function keyword:
The fat arrow has simpler semantics in this sense. It's probably better to not ask for new values of this and arguments unless they are really needed.
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.