Questions tagged [function]
A function (also called a procedure, method, subroutine, or routine or macro) is a portion of code intended to carry out a single, specific task. Use this tag for questions which specifically involve creating or calling functions. For help implementing a function to perform a task, use [algorithm] or a task-specific tag instead. By creating function the logic can be isolated and can be called repeatedly.
111,303
questions
7636
votes
42
answers
1.2m
views
var functionName = function() {} vs function functionName() {}
I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent.
The previous developer used two ways ...
7619
votes
86
answers
1.6m
views
How do JavaScript closures work?
How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves?
I ...
3478
votes
24
answers
820k
views
What is the difference between call and apply?
What is the difference between using Function.prototype.apply() and Function.prototype.call() to invoke a function?
const func = function() {
alert("Hello world!");
};
func.apply() vs. ...
3160
votes
22
answers
659k
views
How do I make function decorators and chain them together?
How do I make two decorators in Python that would do the following?
@make_bold
@make_italic
def say():
return "Hello"
Calling say() should return:
"<b><i>Hello</i>&...
2659
votes
29
answers
1.5m
views
Set a default parameter value for a JavaScript function
I would like a JavaScript function to have optional arguments which I set a default on, which get used if the value isn't defined (and ignored if the value is passed). In Ruby you can do it like this:
...
2416
votes
31
answers
2.6m
views
JavaScript check if variable exists (is defined/initialized)
Which method of checking if a variable has been initialized is better/correct?
(Assuming the variable could hold anything (string, int, object, function, etc.))
if (elem) { // or !elem
or
if (typeof ...
2211
votes
27
answers
575k
views
What is the scope of variables in JavaScript?
What is the scope of variables in javascript? Do they have the same scope inside as opposed to outside a function? Or does it even matter? Also, where are the variables stored if they are defined ...
1487
votes
7
answers
1.8m
views
Passing parameters to a Bash function
I am trying to search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the command line.
I would like to pass parameters within my script. I tried:
...
1466
votes
8
answers
238k
views
What does the exclamation mark do before the function?
I found this code:
!function () {}();
What is the purpose of the exclamation mark here?
1081
votes
14
answers
859k
views
How to get a function name as a string?
How do I get a function's name as a string?
def foo():
pass
>>> name_of(foo)
"foo"
1007
votes
24
answers
589k
views
Javascript call() & apply() vs bind()?
I already know that apply and call are similar functions which set this (context of a function).
The difference is with the way we send the arguments (manual vs array)
Question:
But when should I use ...
987
votes
7
answers
572k
views
How to pass all arguments passed to my Bash script to a function of mine? [duplicate]
Let's say I have a function abc() that will handle the logic related to analyzing the arguments passed to my script.
How can I pass all arguments my Bash script has received to abc()? The number of ...
987
votes
17
answers
182k
views
What is the difference between a 'closure' and a 'lambda'?
Could someone explain? I understand the basic concepts behind them but I often see them used interchangeably and I get confused.
And now that we're here, how do they differ from a regular function?
985
votes
26
answers
589k
views
How are lambdas useful? [closed]
I'm trying to figure out Python lambdas. Is lambda one of those "interesting" language items that in real life should be forgotten?
I'm sure there are some edge cases where it might be ...
914
votes
4
answers
95k
views
JavaScript plus sign in front of function expression
I’ve been looking for information about immediately invoked functions, and somewhere I stumbled on this notation:
+function(){console.log("Something.")}()
Can someone explain to me what the + sign ...
866
votes
16
answers
1.0m
views
Pass a JavaScript function as parameter
How do I pass a function as a parameter without the function executing in the "parent" function or using eval()? (Since I've read that it's insecure.)
I have this:
addContact(entityId, ...
863
votes
28
answers
497k
views
Is there a better way to do optional function parameters in JavaScript? [duplicate]
I've always handled optional parameters in JavaScript like this:
function myFunc(requiredArg, optionalArg){
optionalArg = optionalArg || 'defaultValue';
// Do stuff
}
Is there a better way to ...
831
votes
23
answers
578k
views
What is the use of the JavaScript 'bind' method?
What is the use of bind() in JavaScript?
818
votes
10
answers
814k
views
How do you pass a function as a parameter in C?
I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C?
815
votes
19
answers
1.9m
views
How do I call a function from another .py file? [duplicate]
file.py contains a function named function. How do I import it?
from file.py import function(a,b)
The above gives an error:
ImportError: No module named 'file.py'; file is not a package
811
votes
8
answers
1.3m
views
How to change a string into uppercase?
How can I convert a string into uppercase in Python?
When I tried to research the problem, I found something about string.ascii_uppercase, but it couldn't solve the problem:
>>> s = 'sdsd'
&...
751
votes
27
answers
480k
views
Determine function name from within that function
Is there a way to determine a function's name from within the function?
def foo():
print("my name is", __myname__) # <== how do I calculate this at runtime?
In the example above, ...
745
votes
16
answers
1.1m
views
How to apply a function to two columns of Pandas dataframe
Suppose I have a function and a dataframe defined as below:
def get_sublist(sta, end):
return mylist[sta:end+1]
df = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3], 'col_2':[1,4,5]})
mylist = ...
730
votes
1
answer
379k
views
"Parameter" vs "Argument" [duplicate]
I got parameter and argument kind of mixed up and did not really pay attention to when to use one and when to use the other.
Can you please tell me?
726
votes
24
answers
542k
views
Decorators with parameters?
I have a problem with the transfer of the variable insurance_mode by the decorator. I would do it by the following decorator statement:
@execute_complete_reservation(True)
def test_booking_gta_object(...
696
votes
13
answers
439k
views
How can I view the source code for a function?
I want to look at the source code for a function to see how it works. I know I can print a function by typing its name at the prompt:
> t
function (x)
UseMethod("t")
<bytecode: 0x2332948>
&...
670
votes
11
answers
725k
views
What is a "static" function in C?
The question was about plain c functions, not c++ static methods, as clarified in comments.
I understand what a static variable is, but what is a static function?
And why is it that if I declare a ...
670
votes
17
answers
1.5m
views
Define a global variable in a JavaScript function
Is it possible to define a global variable in a JavaScript function?
I want use the trailimage variable (declared in the makeObj function) in other functions.
<html xmlns="http://www.w3.org/...
649
votes
13
answers
499k
views
JavaScript variable number of arguments to function
Is there a way to allow "unlimited" vars for a function in JavaScript?
Example:
load(var1, var2, var3, var4, var5, etc...)
load(var1)
649
votes
30
answers
726k
views
How to get the return value from a thread?
The function foo below returns a string 'foo'. How can I get the value 'foo' which is returned from the thread's target?
from threading import Thread
def foo(bar):
print('hello {}'.format(bar))
...
634
votes
15
answers
447k
views
How can I get the source code of a Python function?
Suppose I have a Python function as defined below:
def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
I can get the name of the function using foo.func_name. How can I ...
591
votes
12
answers
768k
views
Return value in a Bash function
I am working with a bash script and I want to execute a function to print a return value:
function fun1(){
return 34
}
function fun2(){
local res=$(fun1)
echo $res
}
When I execute fun2, it ...
590
votes
7
answers
427k
views
Why do some functions have underscores "__" before and after the function name?
This "underscoring" seems to occur a lot, and I was wondering if this was a requirement in the Python language, or merely a matter of convention?
Also, could someone name and explain which functions ...
577
votes
21
answers
428k
views
How to return a string value from a Bash function
I'd like to return a string from a Bash function.
I'll write the example in java to show what I'd like to do:
public String getSomeString() {
return "tadaa";
}
String variable = getSomeString();
...
576
votes
19
answers
966k
views
Run function from the command line
I have this code:
def hello():
return 'Hi :)'
How would I run this directly from the command line?
See also: What does if __name__ == "__main__": do? to explain the standard idiom for ...
567
votes
30
answers
538k
views
PHP mail function doesn't complete sending of e-mail
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: yoursite.com';
$to = '[email protected]';
$subject = 'Customer ...
547
votes
11
answers
578k
views
Difference between return and exit in Bash functions
What is the difference between the return and exit statement in Bash functions with respect to exit codes?
512
votes
5
answers
170k
views
What is the difference between a function expression vs declaration in JavaScript? [duplicate]
What is the difference between the following lines of code?
//Function declaration
function foo() { return 5; }
//Anonymous function expression
var foo = function() { return 5; }
//Named function ...
496
votes
4
answers
367k
views
Passing a dictionary to a function as keyword parameters
I'd like to call a function in python using a dictionary with matching key-value pairs for the parameters.
Here is some code:
d = dict(param='test')
def f(param):
print(param)
f(d)
This prints {...
485
votes
8
answers
197k
views
Static vs class functions/variables in Swift classes?
The following code compiles in Swift 1.2:
class myClass {
static func myMethod1() {
}
class func myMethod2() {
}
static var myVar1 = ""
}
func doSomething() {
myClass....
473
votes
14
answers
882k
views
How do Python functions handle the types of parameters that you pass in?
Unless I'm mistaken, creating a function in Python works like this:
def my_func(param1, param2):
# stuff
However, you don't actually give the types of those parameters. Also, if I remember, ...
470
votes
46
answers
356k
views
Simplest/cleanest way to implement a singleton in JavaScript
What is the simplest/cleanest way to implement the singleton pattern in JavaScript?
452
votes
14
answers
381k
views
Is there a way to provide named parameters in a function call in JavaScript?
C#, for example, allows using named parameters like so:
calculateBMI(70, height: 175);
I find this quite useful. How can I get a similar effect in JavaScript?
I've tried doing things like
myFunction({...
442
votes
8
answers
998k
views
How do I define a function with optional arguments?
I have a Python function which takes several arguments. Some of these arguments could be omitted in some scenarios.
def some_function (self, a, b, c, d = None, e = None, f = None, g = None, h = None):...
410
votes
34
answers
219k
views
How to explain callbacks in plain english? How are they different from calling one function from another function?
How to explain callbacks in plain English? How are they different from calling one function from another function taking some context from the calling function? How can their power be explained to a ...
404
votes
12
answers
324k
views
Ignore python multiple return value
Say I have a Python function that returns multiple values in a tuple:
def func():
return 1, 2
Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? ...
402
votes
3
answers
786k
views
How can I call a function within a class?
I have this code which calculates the distance between two coordinates. The two functions are both within the same class.
However, how do I call the function distToPoint in the function isNear?
class ...
400
votes
15
answers
373k
views
What is & How to use getattr() in Python?
I read an article about the getattr function, but I still can't understand what it's for.
The only thing I understand about getattr() is that getattr(li, "pop") is the same as calling li.pop....
397
votes
16
answers
1.6m
views
How to add an object to an array
How can I add an object to an array (in javascript or jquery)?
For example, what is the problem with this code?
function() {
var a = new array();
var b = new object();
a[0] = b;
}
I would like ...
385
votes
11
answers
611k
views
PHP append one array to another (not array_push or +)
How to append one array to another without comparing their keys?
$a = array( 'a', 'b' );
$b = array( 'c', 'd' );
At the end it should be: Array( [0]=>a [1]=>b [2]=>c [3]=>d )
If I use ...