Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andy51002000/1a4614cd3521881f26012d39e7083eee to your computer and use it in GitHub Desktop.
Save andy51002000/1a4614cd3521881f26012d39e7083eee to your computer and use it in GitHub Desktop.
# Python3 VS ES6 syntax comparison

Python3 VS ES6 syntax comparison

Python 3.7

Javascript ES6

Comments

# single line comments

# multi line 
# comments
// single line comments

/**
 * multi line
 * comments
 */

Variables

my_var = 123
my_var = 'abc'
let myVar = 123;
myVar = 'abc';

// use 'const' to prevent reassignment
const myOtherVar = 456;
myOtherVar = 'def'; // TypeError: Assignment to constant variable.

Basic Types

a_bool = True
an_inverse_bool = not a_bool
a_number = 123
a_string = "abc"
a_list = [1, 2, 3]
a_tuple = (1, 2, 3)
a_set = {1, 2, 3}
a_dict = {"a": 1, "b": 2, "c": 3} # access keys with indexers: a_dict["a"]
an_object = SomeClass() # access keys with dot-access: an_object.a
const aBool = true;
const anInverseBool = !aBool;
const aNumber = 123;
const aString = 'abc';
const anArray = [1, 2, 3];
// Arrays are used as tuples in Javascript
const aSet = new Set([1, 2, 3]);
// Javascript does not differentiate between a dictionary and an object
const anObject = {a: 1, b: 2, c: 3}; // access keys with dot-access: anObject.a

Null Checking

# DICTS
d = {"a": 1}

d['a'] # returns '1'
d.get('b') # returns None
d['b'] # raises KeyError: 'b'

if d.get('b'):
  # does NOT execute

if d.get('a'):
  # DOES execute
  

# LISTS
l1 = []
l2 = [1]

# Empty lists are falsey:
if l1:
  # does NOT execute

if l2:
  # DOES execute
// OBJECTS (dicts)
const d = { a: 1 };

d['a'] // returns '1'
d.a // returns '1'

d['b'] // returns 'undefined' (does NOT raise)
d.b // returns 'undefined' (does NOT raise)

if (d.b) {
  // does NOT execute
}

if (d.a) {
  // DOES execute
}


// ARRAYS (lists)
const l1 = [];
const l2 = [1];

// empty arrays ARE STILL TRUTHY!
if (l1) {
  // THIS WILL EXECUTE
}

if (l2) {
  // THIS ALSO WILL EXECECUTE
}

// use the .length property to check for empty lists:
if (l1.length) {
  // does NOT execute
}

if (l2) {
  // DOES execute
}

String Interpolation

a = 1
b = 2
f"{a} + {b} = {a + b}"
const a = 1;
const b = 2;
`${a} + ${b} = ${a + b}`

Imports

import math
print(math.log(42))

from math import log
print(log(42))

from math import *
print(log(42))
import math from 'math';
console.log(math.log(42));

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

import * from 'math';
console.log(log(42));

Loops

while True:
  print('still true')

lst = [1, 2, 3, 4]

for x in lst:
  print(x)

for i, x in enumerate(lst):
  print(f"{i}: {x}")
while(true) {
  console.log('still true');
}

const arr = [1, 2, 3, 4];

for (x of arr) {
  console.log(x);
}

for (let i = 0, i < arr.length; i++) {
  x = arr[i];
  console.log(x);
}

// there is also a functional forEach available on most iterables:
arr.forEach(x => console.log(x));

If/Else

if True:
  print('still true')
elif not True:
  print('this is rather odd')
else:
  print('???')

# ternary operator:
1 if True else 0
if (true) {
  console.log('still true');
} else if (!true) {
  console.log('this is rather odd');
} else {
  console.log('???');
}

// ternary operator:
true ? 1 : 0;

Switch/Case

  • Python does not have a switch statement (😢)
function greet(timeOfDay) {
  let greeting = 'hello';
  switch (timeOfDay) {
    case 'morning':
      greeting += ', good morning';
      break;
    case 'afternoon':
      greeting += ', good afternoon';
      break;
    default:
      greeting += ', good evening';
      break;
  }
  console.log(greeting);
}

Functions

# defining
def add_numbers(a, b):
  return a + b

# calling
add_numbers(1, 2)
add_numbers(a=1, b=2)
// defining
function addNumbers(a, b) {
  return a + b;
}

// calling
addNumbers(1, 2);
// Javascript does not have named parameters

Lambdas

lambda a: a * 2
a => a * 2
  • => is often called a 'fat arrow'

Classes

  • Python has multiple inheritance; Javascript does not
  • Python refers to the instance as self; Javascript uses this
  • Python calls the initializer like a function; Javascript uses the new keyword to call constructors
# defining
class SpiderMan(Human, SuperHero):
    # term: initializer
    def __init__(self, age):
        super().__init__(age)
        self.age = age
    
    # instance methods
    def say_age(self):
        print(self.age)

    @classmethod
    def hello(cls):
      print('world')

# instantiating
spman = SpiderMan(123)
// defining
class SpiderMan extends SuperHero {
    // term: constructor
    constructor(age) {
        super();
        this.age = age;
    }

    // instance methods
    sayAge() {
        console.log(this.age);
    }

    // class/static methods
    hello() {
      console.log('world');
    }
}

// instantiating
const spman = new SpiderMan(123);

Spread

parameters = { "a": 1, "b": 2, "c": 3 }
search_db(**parameters)
# above and below are identical:
# search_db(a=parameters['a'], b=parameters['b'], c=parameters['c'])
const parameters = { a: 1, b: 2, c:3 };
searchDb(...parameters);
// above and below are identical:
// searchDb(parameters.a, parameters.b, parameters.c);

Destructuring

status, data, message, headers = getResult()
const [status, data, message, headers] = getResult();

// the spread operator can be used when destructuring to discard unused values:
const [status, data, ...] = getResult();

// objects can also be destructured in Javascript:
const {status, data, message, headers} = getResultObject();

Common Collection Operations (length/map/filter/sort/reduce)

lst = [1, 2, 3, 4]

# length
len(lst)

# map
map(lambda x: x*2, lst)
[x*2 for x in lst

# filter
filter(lambda x: x > 2, lst)
[x for x in lst if x > 2]

# sort
sorted(lst)
lst.sort()

# reduce
from functools import reduce
reduce(lambda acc, curr: acc + curr, lst, 0)
const arr = [1, 2, 3, 4];

// length
arr.length;

// map
arr.map(x => x * 2);

// filter
arr.filter(x => x > 2);

// sort
arr.sort();

// reduce
arr.reduce((acc, curr) => acc + curr, 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment