Python.v.JavaScript

JavaScript for Pythonistas. Python for JavaScripters

Functions

Functions are defined in Python and JavaScript in a similar way, but with subtle differences.

Python Javascript
Named parameters #
def foo(x, y):
    print("x =", x, " y =", y)
foo(2, 3)
foo(x=2, y=3)
foo(y=2, x=3)
x = 2  y = 3
x = 2  y = 3
x = 3  y = 2
function foo(x, y) {
    console.log("x = " + x + " y = " + y)
}
foo(2, 3);
foo(x=2, y=3);
foo(y=2, x=3);
console.log(x);
console.log(y);
x = 2 y = 3
x = 2 y = 3
x = 2 y = 3
3
2

You may be tempted to use a Pythonic syntax on named function arguments in Javascript. Unfortunately, it won't work. Moreover, JS doesn't support named function arguments at all. Line foo(x=2, y=3) in fact executes three commands: x=2, y=3 and then foo(2, 3), so variables x and y in the calling scope will be created/updated. Assignment operator returns the value, so the function will be called as foo(2, 3). The next line will call foo in the same way regardless of swapping of x and y.


function foo(args) {
    console.log("x = " + args.x + " y = " + args.y);
}
foo({x: 2, y: 3})
x = 2 y = 3
© Ilya V. Schurov and contributors, 2017
Licenses: CC BY (text), MIT (code).
contribute on github