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.

Filter by
Sorted by
Tagged with
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 ...
Richard Garside's user avatar
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. ...
John Duff's user avatar
  • 38.3k
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>&...
Imran's user avatar
  • 89.2k
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: ...
Tilendor's user avatar
  • 48.5k
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 ...
Samuel Liew's user avatar
  • 78.1k
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 ...
lYriCAlsSH's user avatar
  • 57.8k
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: ...
stivlo's user avatar
  • 84.5k
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?
Sebastian Otto's user avatar
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"
X10's user avatar
  • 17.6k
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 ...
Royi Namir's user avatar
  • 147k
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 ...
devoured elysium's user avatar
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?
sker's user avatar
  • 18.1k
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 ...
meade's user avatar
  • 23.1k
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 ...
Josip Codes's user avatar
  • 9,483
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, ...
imperium2335's user avatar
  • 23.8k
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 ...
Mark Biek's user avatar
  • 149k
831 votes
23 answers
578k views

What is the use of the JavaScript 'bind' method?

What is the use of bind() in JavaScript?
Sandy's user avatar
  • 14k
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?
andrewrk's user avatar
  • 30.7k
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
user2977230's user avatar
  • 9,267
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' &...
gadss's user avatar
  • 22.1k
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, ...
Rob's user avatar
  • 7,740
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 = ...
bigbug's user avatar
  • 57.9k
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?
user avatar
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(...
falek.marcin's user avatar
  • 10.1k
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> &...
Joshua Ulrich's user avatar
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 ...
Slava V's user avatar
  • 17.1k
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/...
hamze torabzade's user avatar
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)
Timo's user avatar
  • 7,285
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)) ...
wim's user avatar
  • 350k
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 ...
user avatar
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 ...
mindia's user avatar
  • 7,371
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 ...
Chuck Testa's user avatar
  • 6,117
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(); ...
Tomas F's user avatar
  • 7,446
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 ...
Steven's user avatar
  • 5,833
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 ...
user3818620's user avatar
  • 5,713
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?
lecodesportif's user avatar
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 ...
Faisal Vali's user avatar
  • 33.2k
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 {...
Dave Hillier's user avatar
  • 18.6k
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....
Senseful's user avatar
  • 89.4k
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, ...
Leif Andersen's user avatar
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?
Jakub Arnold's user avatar
  • 86.4k
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({...
Robin Maben's user avatar
  • 22.7k
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):...
Thalia's user avatar
  • 14.2k
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 ...
Yahoo-Me's user avatar
  • 4,993
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? ...
Mat's user avatar
  • 84.4k
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 ...
Steven's user avatar
  • 4,273
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....
Terence Ponce's user avatar
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 ...
naser's user avatar
  • 4,387
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 ...
Danil K's user avatar
  • 3,897

1
2 3 4 5
2227