Syntax Cheatsheet for Javascript/Python developers

7/12/2023, 9:40:33 AM

I enjoy watching tutorials on other languages before going to bed, for exposure. One of the things that I've spent my recent nights watching was Al Sweigart teaching how to Automate The Boring Stuff With Python on Udemy. While I don't see myself switching my working language to Python in the near future, I thought it would be interesting to keep an easy-to-reference cheatsheet of the syntax differences between both languages, in case me or other people need one.

Table of Contents

  1. Naming Conventions
  2. Declaring variables
  3. Data types
  4. Data Type Conversions
  5. Expressions
  6. Mathematical Operators
  7. Bitwise Operators
  8. Utilities
  9. Strings
  10. Arrays/Lists
  11. Objects/Dictionaries
  12. Classes
  13. Loops

Naming Conventions

JavascriptPython
camelCasesnake_case
PascalCasePascalCase
SCREAMING_SNAKE_CASESCREAMING_SNAKE_CASE

Declaring Variables

JavascriptPython
var count = 0global count = 0
let count = 0count = 0
const count = 0
let a = 5, b = a, c = ba = b = c = 5

Data Types

JavascriptPython
true / falseTrue / False
'' / "" / ``'' / "" / r'' / f''
13
12.4
complex(1j)
13 / 12.4
BigInt(bigNumberString)
[][]
new Set(['a'])set(['a'])
frozenset(('a'))
range(6)
{key: 'value'}{key: 'value'}
new Date()
nullNone
undefined
Symbol('a')
b'hi'
bytearray(4)
memoryview(bytes('a'))

Converting Data Types

JavascriptPython
!!'word'bool('word')
String(10)str(10)
10.toString()
Number('10')int('10')
parseInt('10')
+'10'
parseFloat('10')
'10' * 1
~~'10'
parseFloat('1.5')float('1.5')
range(8)

Expressions

JavascriptPython
'1' == 1
10 === 1010 == 0
true != false
true !== falseTrue != False
10 < 2010 < 20
15 <= 2015 <= 20
30 > 1530 > 15
50 >= 2550 >= 25
10 > 5 && isTrue === true10 > 5 and isTrue == True
20 > 30 || isFalse === false20 > 30 or isFalse == False
[1, 2, 3].includes(1)1 in [1, 2, 3]
"Hello world!".includes("Hello")"Hello" in "Hello World!"
![1, 2, 3].includes(1)1 not in [1, 2, 3]
typeof a === 'undefined'

Mathematical Operators

JavascriptPython
5 + 85 + 8
num += 5num += 5
i++
13 - 513 - 5
num -= 5num -= 5
i--
3 * 53 * 5
num *= 5num *= 5
num ** 2num ** 2
num @ 2
num @= 2
3 / 53 / 5
num /= 5num /= 5
3 // 5
num //= 5
num % 2num % 2
num %= 2num %= 2
a, b = divmod(23, 5)

Bitwise Operators (a.k.a. Binary Black Magic)

JavascriptPython
&&
&=&=
||
|=|=
^^
^=^=
~~
>>>>
>>=>>=
<<<<
<<=<<=

Functions

JavascriptPython
function multiplyByTwo(x) { return x * 2 }def multiplyByTwo(x): return x * 2
function logX(x = 'hi') { console.log(x) }def printX(x='hi'): print(x)
const add = (a, b) => a + badd = lambda a, b: a + b
function* timer(counter) { while (counter > 0) { yield counter; counter--; } }def timer(counter): while counter > 0: yield counter counter -= 1

Utilities

JavascriptPython
console.log('hi')print('hi')
if (condition === true) {if condition == True:
} else if (condition === true) {elif condition == True:
} else {else:
switch (arg){ case 'word': doThing(); break; default: doOtherThing(); }match arg: case 'word': doThing() case _: doOtherThing()
happy === true ? "smile" : "frown""smile" if happy == True else "frown"
try { badFunction(); } catch (error) { if (error instanceof ThrownException) { console.log('Sorry! ' + error.message); } } finally { console.log('Finishing'); }try: badFunction() except ThrownException as error: print('Sorry! {}'.format(error)) finally: print('Finishing')
// comment# comment
/* This is a multiline comment */
const [a, b, ...rest] = [1, 2, 3, 4]a, b, *rest = [1, 2, 3, 4]
oneFunction(...args)oneFunction(**args)
typeof 10 === 'number'type(10) is int
isinstance(10, int)
JSON.parse(jasonToParse)import json json.loads(jason_to_parse)
JSON.stringify(objToJason)import json json.dumps(dict_to_jason)
const phonePattern = /(\(?\d{3}\)?[- ]?\d{3}-?\d{4})/; "Please call me at (555) 444-9876".replace(phonePattern, "REDACTED PHONE NUMBER");import re phonePattern = re.compile(r'(\(?\d{3}\)?[- ]?\d{3}-?\d{4})') phonePattern.sub(phonePattern, "REDACTED PHONE NUMBER", "Please call me at (555) 444-9876")

Strings

JavascriptPython
const styling = 'css'styling = 'css'
const markup = "html"markup = "html"
"text".lengthlen("text")
"two " + "strings""two " + "strings"
'Don\'t repeat yourself''Don\'t repeat yourself'
r'\back\slash'
` multiline text here `""" multiline text here """
word.substring(1, 4)word[1:4]
word.substring(0, 3)word[:3]
word.slice(-3)word[-3:]
'My name is %s.' % (name)
`My name is ${name}.`f'My name is {name}.'
"Hello world!".includes("Hello")"Hello" in "Hello World!"
['Hello', 'world!'].join(' ')hello = ['Hello', 'world!'] ' '.join(hello)
'Hello world!'.split(' ')'Hello world!'.split()
' word '.trim()' word '.strip()
' word'.trimStart()' word '.lstrip()
'word '.trimEnd()'word '.rstrip()
'word'.toUpperCase()'word'.upper()
'SCREAMING'.toLowerCase()'SCREAMING'.lower()
'two WORDS'.capitalize()
'breaking news'.title()

Arrays/Lists

JavascriptPython
const a = new Array()a = list()
const a = [1, 2]a = [1, 2]
a[0]a[0]
a[0] = 4a[0] = 4
a.push(8)a.append(8)
a.splice(1, 0, 'item added')a.insert(1, 'item added')
a.pop()a.pop()
a.remove(4)
['Hello', 'world!'].join(' ')hello = ['Hello', 'world!'] ' '.join(hello)
a.slice(1, 4)a[1:4]
a.slice(3)a.[:3]
a.slice(-3)a[-3:]
a.sort()a.sort()
a.sort((a, b) => b - a)a.sort(reverse=True)
a.count(4)
[1, 2, 3].lengthlen([1, 2, 3])
const uniqueSet = new Set([1, 2, 3])uniqueSet = set((1, 2, 3))
uniqueSet = {1, 2, 3}
[1, 2, 3].map(n => n * 2)list(map(lambda n: n * 2, [1, 2, 3]))
[1, 2, 3].reduce((total, curr) => total + curr)reduce(lambda total, curr: total + curr, [1, 2, 3])
uniqueSet.sizelen(uniqueSet)
x = (1, 2, 3)

Objects/Dictionaries

JavascriptPython
const o = {}o = {}
const o = new Object()o = dict()
const o = Object.create(null)
obj['keyName'] = 'value'dict['key_name'] = 'value'
obj.keyName = 'value'setattr(dict, key_name, value)
obj['keyName']dict['key_name']
obj.keyNamegetattr(dict, key_name)
len(dict)
'key_name' in dict'keyName' in obj
const a = {name: 'yuri'} const b = {name: 'yuri'} a == b // falsea = {name: 'yuri'} b = {name: 'yuri'} a == b # True
delete obj['key']del obj['key']
{...objA, ...objB}{**dictA, **dictB}

Classes

JavascriptPython
class Person { constructor(name) { this.name = name; } } class Person: def __init__(self, name): self.name = name
class Student extends Person { constructor(name, age) { super(name); this.age = age } }class Student(Person): def __init__(self, name, age): super().__init__(name) self.age = age
class Person: def __str__(self): return f"Person {self.name} printed."

Loops

JavascriptPython
for (const key of Object.keys(obj)) { console.log(key) }for key in dict.keys(): print(key)
for (const value of Object.values(obj)) { console.log(value) }for value in dict.values(): print(value)
for (const val in obj) { console.log(val) }for val in dict: print(val)
for (const [k, v] of Object.entries(obj)) { console.log(k, ':', v) }for k, v in dict.items(): print(k, ':', v)
for (let i = 0; i < 10; i++) { console.log(i) }for i in range(10): print(i)
for (let item of loopingArray) { console.log(item) }for item in loopingList: print(item)
for (let i = 0; i < loopingArray.length; i++) { console.log(loopingArray[i]); }
loopingArray.forEach(function (item) { console.log(item); }) }
while (condition) { console.log('condition is true') }while condition: print('condition is true')
do { i++; console.log(i); } while (i < 5);