Blog

Links

Python and JavaScript: multi-paradigm languages

posted: May 23, 2020

tl;dr: Both Python and JavaScript allow you to write your program in the paradigm you decide is most appropriate...

The sixth in a series of posts highlighting the commonalities of Python and JavaScript.

Under the hood, both Python and JavaScript are highly object-oriented languages. Data of all types are objects that live in the memory space managed by the interpreter. Yet neither language forces the programmer to write in a traditional object-oriented way, by defining new classes, attributes, properties, and methods. This creates a situation I called an object-oriented paradox: a programmer can write Python or JavaScript in non-object-oriented styles or paradigms, even though they are object-oriented languages.

Because of this flexibility, Python and JavaScript are best termed “multi-paradigm languages”. Here are the main programming paradigms that can be used when writing in either language.

Scripts

A script can be a simple file of statements, without any functions or classes, that executes from start to finish, top to bottom. Without any functions, there are no local variables, so everything runs in the global namespace of the interpreter. Scripts can be (and should be) fast to create and easy to understand. They typically help automate or perform a simple task. Because of its richer standard library, I prefer Python to JavaScript/NodeJS for devops script tasks, and Python to bash, but all three can certainly be used for writing scripts.

Because of their ability to run scripts, both Python and JavaScript have short one-line “Hello, world” canonical examples:

print('Hello, world!') # Python

console.log('Hello, world!'); // JavaScript

Structured programing

The original definition of structured programming, as coined by Edsger Dijkstra, focused on isolating blocks of repeated code into functions or subroutines. Inside of functions, local variables can be used to avoid the challenges of keeping all data in global variables. Functions are one of the most widely used concepts in both Python and JavaScript. Here’s an example, in each language, of writing “Hello, world” by following the structured programming paradigm:

def hello_world(): # Python
    print('Hello, world!')
hello_world()

function helloWorld() { // JavaScript
  console.log('Hello, world!')
}
helloWorld();

Functional programming

There are several levels of functional programming. To get started with functional programming, a language needs to treat functions as first-class citizens, which both Python and JavaScript do. This means that functions are themselves objects that live in memory; can be referenced by names; and can be passed as arguments to other functions. As an example, both the Python print function and JavaScript’s console.log can be passed as arguments to other functions. So a functional programming example of “Hello, world” in each language is:

def call_once(f, arg): # Python
    f(arg)
call_once(print, 'Hello, world!')

function callOnce(f, arg) { // JavaScript
  f(arg);
}
callOnce(console.log, 'Hello, world!');

This style of functional programming is common in both Python and JavaScript, especially in asynchronous programming. Often a callback function needs to be passed in which is executed later, after an asynchronous operation has completed and returned a value.

Purely functional programming starts with functions as first-class citizens and extends much deeper into how functions should behave and be used. Pure functions are functions which, when given the same inputs, always return the same value, and which have no other side effects. A print statement is not a pure function, because the whole purpose of a print statement is to produce a side effect: some output on the user’s console.

Purely functional programming also treats all data as immutable, and both Python and JavaScript feature important data structures (lists/arrays, and dicts/objects) which are highly mutable. So neither Python nor JavaScript enforces all the paradigms of a purely functional language. But it is certainly possible to write Python and JavaScript programs in a purely functional style, by being careful to avoid the operations that would violate the purely functional programming paradigm.

Object-oriented programming

When I think of traditional object-oriented programming, I think of Java, because this is the one and only paradigm that Java supports. Everything in Java must be inside a class, which leads to the canonical Java “Hello, world” example:

class HelloWorld // Java
{
    public static void main(String args[])
    {
        System.out.println("Hello, world!");
    }
}

Python has had the ability for programmers to define their own classes and methods for a long time. JavaScript started with a slightly different object-oriented concept by using objects and prototypes, but in 2015 explicit class syntax was added to the language. This, plus optional static typing, makes it possible to write Python and JavaScript that looks a lot like Java, by following the object-oriented paradigm. Here is an object-oriented “Hello, world” example in each, using static methods:

class Greeting(): # Python
    @staticmethod
    def hello_world():
        print('Hello, world!')
Greeting.hello_world()

class Greeting { // JavaScript
  static helloWorld() {
    console.log('Hello, world!');
  }
}
Greeting.helloWorld();

I tend not to define new custom classes unless there is a strong need to do so, so I write most of my Python and JavaScript code by adhering to the structured and functional programming paradigms.

Synchronous and Asynchronous programming

Contrary to popular belief, JavaScript is not an entirely asynchronous language, and Python is not an entirely synchronous language. It is possible to write synchronous JavaScript programs and asynchronous Python programs. With the addition of the async and await keywords to both languages, doing asynchronous programming is even more similar than it used to be. That is a topic for another blog post.

Previous: Dicts and objects