DEV Community

Masataka Arai
Masataka Arai

Posted on • Edited on

JavaScript is almost pythonic

Multi-line String

  • Python3.6
print("""string text line 1
string text line 2""")
Enter fullscreen mode Exit fullscreen mode
  • ES2017
console.log(`string text line 1
string text line 2`)
Enter fullscreen mode Exit fullscreen mode

Expression Interpolation

  • Python3.6
a = 5
b = 10
print(f'Fifteen is {a + b} and not {2 * a + b}.')
Enter fullscreen mode Exit fullscreen mode
  • ES2017
var a = 5
var b = 10
console.log(`Fifteen is ${a + b} and not ${2 * a + b}.`)
Enter fullscreen mode Exit fullscreen mode

Arrow function

  • Python3.6
numbers = [1, 2, 3, 4]

list(map(lambda x: x * 2, numbers))
# or [x * 2 for x in numbers]
Enter fullscreen mode Exit fullscreen mode
  • ES2017
var numbers = [1, 2, 3, 4]
numbers.map(v => v * 2)
Enter fullscreen mode Exit fullscreen mode

Destructuring

  • Python3.6
numbers = (1, 2, 3)
x, y, z = numbers
Enter fullscreen mode Exit fullscreen mode
  • ES2017
var numbers = [1, 2, 3]
var [x, y, z] = numbers
Enter fullscreen mode Exit fullscreen mode

Spread Operator

  • Python3.6
import datetime
date_fields = (2017, 12, 4)
date = datetime.date(*date_fields)

numbers = [1, 2, 3, 4]
first, *remaining = numbers

first = [1, 2]
second = [3, 4]
combined = first + second
Enter fullscreen mode Exit fullscreen mode
  • ES2017
var dateFields = [2017, 12, 4]
var date = new Date(...dateFields)

var numbers = [1, 2, 3, 4]
var [first, ...remaining] = numbers

var first = [1, 2]
var second = [3, 4]
var combined = [...first, ...second]
Enter fullscreen mode Exit fullscreen mode

Rest Operator

  • Python3.6
from functools import reduce
def product(*numbers):
    return reduce(lambda x, y: x * y, numbers)

print(product(1, 2, 3, 4))
Enter fullscreen mode Exit fullscreen mode
  • ES2017
function product(...numbers) {
    return numbers.reduce((x, y) => x * y)
}
console.log(product(1, 2, 3, 4))
Enter fullscreen mode Exit fullscreen mode

Default Parameter

  • Python3.6
def multiply(a, b=1):
    return a * b
Enter fullscreen mode Exit fullscreen mode
  • ES2017
function multiply(a, b = 1) {
  return a * b
}
Enter fullscreen mode Exit fullscreen mode

Class

  • Python3.6
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __str__(self):
        return f"({self.x}, {self.y})"
Enter fullscreen mode Exit fullscreen mode
  • ES2017
class Point {
    constructor(x, y) {
        this.x = x
        this.y = y
    }
    toString() {
        return `(${this.x}, ${this.y})`
    }
}
Enter fullscreen mode Exit fullscreen mode

Sub Class

  • Python3.6
class ColorPoint(Point):
    def __init__(self, x, y, color):
        super().__init__(x, y)
        self.color = color
    def __str__(self):
        return "{} in color {}".format(super().__str__(), self.color)
Enter fullscreen mode Exit fullscreen mode
  • ES2017
class ColorPoint extends Point {
    constructor(x, y, color) {
        super(x, y)
        this.color = color
    }
    toString() {
        return `${super.toString()} in ${this.color}`
    }
}
Enter fullscreen mode Exit fullscreen mode

Getter & Setter

  • Python3.6
class SmartPoint(Point):
    @property
    def hypotenuse(self):
        return sqrt(self.x ** 2 + self.y ** 2)

    @hypotenuse.setter
    def hypotenuse(self, z):
        self.y = sqrt(z ** 2 - self.x ** 2)
Enter fullscreen mode Exit fullscreen mode
  • ES2017
class SmartPoint extends Point {
    get hypotenuse() {
        return Math.sqrt(this.x ** 2 + this.y ** 2)
    }
    set hypotenuse(z) {
        this.y = Math.sqrt(z ** 2 - this.x ** 2)
    }
}
Enter fullscreen mode Exit fullscreen mode

Module

  • Python3.6
import math
print(math.log(42))

from math import log
print(log(42))

from math import *
print(log(42))
Enter fullscreen mode Exit fullscreen mode
  • ES2017
import math from 'math'
console.log(math.log(42))

import { log } from 'math'
console.log(log(42))

import * from 'math'
console.log(log(42))
Enter fullscreen mode Exit fullscreen mode

Async Function

  • Python3.6
async def getProcessedData(url):
    try:
        v = await downloadData(url)
    except Exception:
        v = await downloadFallbackData(url)
    await processDataInWorker(v)
Enter fullscreen mode Exit fullscreen mode
  • ES2017
async function getProcessedData(url) {
  let v
  try {
    v = await downloadData(url) 
  } catch (e) {
    v = await downloadFallbackData(url)
  }
  return processDataInWorker(v)
}
Enter fullscreen mode Exit fullscreen mode

Reference

Latest comments (49)

Collapse
 
kzagoris profile image
Konstantinos Zagoris

It looks more like C#. if you consider Typescript instead of JavaScript is uncanny similar

Collapse
 
lewiscowles1986 profile image
Lewis Cowles

:( Kinda gutted that JS extends syntax looked a lot cleaner.

I have to fight to not use braces if I switch between Python & JS, even though they waste space and the language doesn't enforce (eslint is a tool, it's not language enforced like python).

Here's my tweet response twitter.com/LewisCowles1/status/10...

Collapse
 
erebos-manannan profile image
Erebos ManannΓ‘n

It takes more than a few specific capabilities to be "Pythonic".

PEP-20 for example is pretty core to Python: python.org/dev/peps/pep-0020/

I find it unlikely that JS's poor organization will ever reach a level where they could be considered Pythonic, even though they do make (often sloppy) copies of features from (among other things) Python.

Collapse
 
prasad_h profile image
Prasad Honavar

Wow didn't know JavaScript became cool😁

Collapse
 
lepinekong profile image
lepinekong

Great that's what I just needed ;)

Collapse
 
paddy3118 profile image
Paddy3118

Just waiting for ES202? == Python, you might as well...

Collapse
 
yellow844 profile image
y_hashi

I was worried that the variable declaration of the sample code is var though using ES2017.

Collapse
 
zalithka profile image
Andre Greeff

Very interesting comparison, thanks for the nice clear examples.. :)

Collapse
 
r0f1 profile image
Florian Rohrer

To add to the Getter & Setter examples: You can use this in Python instead of self. It is just a convention, that people refer to the current instance as self. Also, instead of sqrt in both languages, you can write **0.5. With both modifications, that codes look even more similar.

About the classes example: They might look similar, but they are not. __init__ is not a constructor. __init__ is an initializer. The constructor in Python is called __new__. Also, usually you override __repr__ to get a representation of the object instead of __str__.

Collapse
 
webknjaz profile image
Sviatoslav Sydorenko πŸ‡ΊπŸ‡¦

Yeah, I've noticed this some time ago.
Don't forget that you also can omit semicolons in JS as well :)