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
- Naming Conventions
- Declaring variables
- Data types
- Data Type Conversions
- Expressions
- Mathematical Operators
- Bitwise Operators
- Utilities
- Strings
- Arrays/Lists
- Objects/Dictionaries
- Classes
- Loops
Naming Conventions
Javascript | Python |
---|---|
camelCase | snake_case |
PascalCase | PascalCase |
SCREAMING_SNAKE_CASE | SCREAMING_SNAKE_CASE |
Declaring Variables
Javascript | Python |
---|---|
var count = 0 | global count = 0 |
let count = 0 | count = 0 |
const count = 0 | |
let a = 5, b = a, c = b | a = b = c = 5 |
Data Types
Javascript | Python |
---|---|
true / false | True / 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() | |
null | None |
undefined | |
Symbol('a') | |
b'hi' | |
bytearray(4) | |
memoryview(bytes('a')) |
Converting Data Types
Javascript | Python |
---|---|
!!'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
Javascript | Python |
---|---|
'1' == 1 | |
10 === 10 | 10 == 0 |
true != false | |
true !== false | True != False |
10 < 20 | 10 < 20 |
15 <= 20 | 15 <= 20 |
30 > 15 | 30 > 15 |
50 >= 25 | 50 >= 25 |
10 > 5 && isTrue === true | 10 > 5 and isTrue == True |
20 > 30 || isFalse === false | 20 > 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
Javascript | Python |
---|---|
5 + 8 | 5 + 8 |
num += 5 | num += 5 |
i++ | |
13 - 5 | 13 - 5 |
num -= 5 | num -= 5 |
i-- | |
3 * 5 | 3 * 5 |
num *= 5 | num *= 5 |
num ** 2 | num ** 2 |
num @ 2 | |
num @= 2 | |
3 / 5 | 3 / 5 |
num /= 5 | num /= 5 |
3 // 5 | |
num //= 5 | |
num % 2 | num % 2 |
num %= 2 | num %= 2 |
a, b = divmod(23, 5) |
Bitwise Operators (a.k.a. Binary Black Magic)
Javascript | Python |
---|---|
& | & |
&= | &= |
| | | |
|= | |= |
^ | ^ |
^= | ^= |
~ | ~ |
>> | >> |
>>= | >>= |
<< | << |
<<= | <<= |
Functions
Javascript | Python |
---|---|
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 + b | add = 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
Javascript | Python |
---|---|
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
Javascript | Python |
---|---|
const styling = 'css' | styling = 'css' |
const markup = "html" | markup = "html" |
"text".length | len("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
Javascript | Python |
---|---|
const a = new Array() | a = list() |
const a = [1, 2] | a = [1, 2] |
a[0] | a[0] |
a[0] = 4 | a[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].length | len([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.size | len(uniqueSet) |
x = (1, 2, 3) |
Objects/Dictionaries
Javascript | Python |
---|---|
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.keyName | getattr(dict, key_name) |
len(dict) | |
'key_name' in dict | 'keyName' in obj |
const a = {name: 'yuri'} const b = {name: 'yuri'} a == b // false | a = {name: 'yuri'} b = {name: 'yuri'} a == b # True |
delete obj['key'] | del obj['key'] |
{...objA, ...objB} | {**dictA, **dictB} |
Classes
Javascript | Python |
---|---|
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
Javascript | Python |
---|---|
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); |