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.
Python uses this as a convention for constants that shouldn't be reassigned. Because Javascript has 'const' assignments, this is usually reserved for naming variables that would be otherwise magic values, like PI.
Declaring Variables
Javascript
Python
Notes
Global variable
var count = 0
global count = 0
Scoped variable
let count = 0
count = 0
Immutable variable
const count = 0
Python doesn't have const, all variables are mutable and reassignable. Python offers some data types that have immutable values, like Tuples and Frozensets.
Multiple assignment
let a = 5, b = a, c = b
a = b = c = 5
Data Types
Javascript
Python
Notes
Boolean
true / false
True / False
Python capitalizes both boolean values.
Strings
'' / "" / ``
'' / "" / r'' / f''
Python can also use triple single-quotes or triple double-quotes to create a multiline string.
Integers
13
Floats
12.4
Complex
complex(1j)
Numbers
13 / 12.4
Javascript doesn't have separate type for integers or floats, they are all just Number.
BigInt
BigInt(bigNumberString)
Array/List
[]
[]
In Javascript, Arrays are technically, a subtype of Object.
Set
new Set(['a'])
set(['a'])
Like Arrays/Lists, but cannot contain duplicate values.
Frozenset
frozenset(('a'))
Immutable version of set().
Range
range(6)
Object/Dictionary
{key: 'value'}
{key: 'value'}
In Python, putting values inside curly braces without providing a key will create a set() instead.
Date
new Date()
Technically, a subtype of Object.
Null/None
null
None
Undefined
undefined
The closest equivalent in Python would be a Nonetype for whenever you assign a variable to the result of a function that doesn't return any value.
Symbol
Symbol('a')
Bytes
b'hi'
Bytearray
bytearray(4)
Memoryview
memoryview(bytes('a'))
Converting Data Types
Javascript
Python
Notes
Boolean
!!'word'
bool('word')
String (1)
String(10)
str(10)
String (2)
10.toString()
Number (1)
Number('10')
int('10')
Number (2)
parseInt('10')
Number (3)
+'10'
For this to work in Javascript, there must be no spaces between the plus symbol (Unary Operator) and the value/variable.
Number (4)
parseFloat('10')
Number (5)
'10' * 1
Javascript will attempt convert a String to a Number when it interacts with any mathematical operator other than the plus symbol (+).
Number (6)
~~'10'
Float
parseFloat('1.5')
float('1.5')
Javascript doesn't have floats or ints, it's all just Number.
Range
range(8)
Javascript doesn't have Range data types.
Expressions
Javascript
Python
Notes
Weak equality
'1' == 1
Python doesn't have weak equality checks.
Strict equality
10 === 10
10 == 0
Weak inequality
true != false
Python doesn't have weak inequality checks.
Strict inequality
true !== false
True != False
Less than
10 < 20
10 < 20
Less than or equal to
15 <= 20
15 <= 20
Greater than
30 > 15
30 > 15
Greater than or equal to
50 >= 25
50 >= 25
Both sides of expression must be true
10 > 5 && isTrue === true
10 > 5 and isTrue == True
Either side of expression must be true
20 > 30 || isFalse === false
20 > 30 or isFalse == False
Item present in Array/List
[1, 2, 3].includes(1)
1 in [1, 2, 3]
Text present in String
"Hello world!".includes("Hello")
"Hello" in "Hello World!"
Item missing from Array/List
![1, 2, 3].includes(1)
1 not in [1, 2, 3]
Same for strings in both languages.
Checking for unassigned variable
typeof a === 'undefined'
Python throws an error if you try to access a variable that wasn't previously created. If a Python variable is assigned to the result of a function that didn't return anything, it will be 'NoneType'd.
Mathematical Operators
Javascript
Python
Notes
Add
5 + 8
5 + 8
Shorthand addition
num += 5
num += 5
Increment
i++
Python doesn't have pre/post increment operators.
Subtract
13 - 5
13 - 5
Shorthand subtraction
num -= 5
num -= 5
Decrement
i--
Python doesn't have pre/post decrement operators.
Multiply
3 * 5
3 * 5
Shorthand multiplication
num *= 5
num *= 5
Exponent
num ** 2
num ** 2
Matrix multiplication
num @ 2
No Javascript equivalent
Matrix shorthand
num @= 2
No Javascript equivalent
Divide
3 / 5
3 / 5
After a division, all numbers in Python are converted to floats, even if the result is an integer.
Shorthand division
num /= 5
num /= 5
Floored divide
3 // 5
Floored division will return the closest integer rounded down. No 1:1 Javascript equivalent, but you can wrap the expression within a 'Math.floor()' function to achieve essentially the same.
Shorthand division
num //= 5
No Javascript equivalent.
Modulo
num % 2
num % 2
Shorthand modulo
num %= 2
num %= 2
Divmod
a, b = divmod(23, 5)
No Javascript equivalent.
Bitwise Operators (a.k.a. Binary Black Magic)
Javascript
Python
Notes
AND
&
&
&=
&=
OR
|
|
|=
|=
XOR
^
^
^=
^=
NOT
~
~
Right shift
>>
>>
>>=
>>=
Left shift
<<
<<
<<=
<<=
Functions
Javascript
Python
Notes
Functions
function multiplyByTwo(x) {
return x * 2
}
def multiplyByTwo(x):
return x * 2
Python defines scope through indentation, Javascript usually does it through the use of curly braces
try:
badFunction()
except ThrownException as error:
print('Sorry! {}'.format(error))
finally:
print('Finishing')
Single line comments
// comment
# comment
Multi line comments
/*
This is a multiline comment
*/
Python doesn't exactly have multi line comments, but you can use a multi line string to do basically the same thing.
Destructuring/Unpacking
const [a, b, ...rest] = [1, 2, 3, 4]
a, b, *rest = [1, 2, 3, 4]
In Javascript, the '...rest' argument must be the last one. Python doesn't have this restriction.
Spread
oneFunction(...args)
oneFunction(**args)
Type checking (1)
typeof 10 === 'number'
type(10) is int
Type checking (2)
isinstance(10, int)
Parse JSON
JSON.parse(jasonToParse)
import json
json.loads(jason_to_parse)
Built in for Javascript, requires a library import for Python.
Convert to JSON
JSON.stringify(objToJason)
import json
json.dumps(dict_to_jason)
Built in for Javascript, requires a library import for Python.
Replace match with Regex
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")
Built in for Javascript, requires a library import for Python.
Strings
Javascript
Python
Notes
Single quotes string
const styling = 'css'
styling = 'css'
Double quotes string
const markup = "html"
markup = "html"
Length
"text".length
len("text")
Concatenation
"two " + "strings"
"two " + "strings"
Escaping characters
'Don\'t repeat yourself'
'Don\'t repeat yourself'
Raw strings
r'\back\slash'
Javascript doesn't have raw strings.
Multiline strings
`
multiline
text
here
`
"""
multiline
text
here
"""
Python can use double or single quotes for multilines, as long as what you use at the start, you also use at the end. Javascript exclusively uses backticks.
Slicing (set range)
word.substring(1, 4)
word[1:4]
Slicing (start until set end)
word.substring(0, 3)
word[:3]
Slicing (set start until end)
word.slice(-3)
word[-3:]
String interpolation (1)
'My name is %s.' % (name)
String interpolation (2)
`My name is ${name}.`
f'My name is {name}.'
Python's f-strings require Python 3.6 or higher.
Text present in String
"Hello world!".includes("Hello")
"Hello" in "Hello World!"
Same for Arrays/Lists in both languages.
Join Array/List elements as single string
['Hello', 'world!'].join(' ')
hello = ['Hello', 'world!']
' '.join(hello)
Split a string into an Array/List
'Hello world!'.split(' ')
'Hello world!'.split()
Python will split on whitespace by default, if a separator is not provided. With Javascript, not providing a separator will cause every single character to become an Array element.
Trim
' word '.trim()
' word '.strip()
Python also allows you to pass parameters to strip in order to remove something else other than spaces. Javascript doesn't have that flexibility.
Trim leading spaces only
' word'.trimStart()
' word '.lstrip()
Trim trailing spaces only
'word '.trimEnd()
'word '.rstrip()
Uppercase entire string
'word'.toUpperCase()
'word'.upper()
Lowercase entire string
'SCREAMING'.toLowerCase()
'SCREAMING'.lower()
Uppercase first letter of first word, lowercase everything else
'two WORDS'.capitalize()
No Javascript equivalent.
Uppercase first letter of every word
'breaking news'.title()
No Javascript equivalent.
Arrays/Lists
Javascript
Python
Notes
New array/list (1)
const a = new Array()
a = list()
In Javascript, it's bad practice to initialize arrays like this.
New array/list (2)
const a = [1, 2]
a = [1, 2]
Accessing element by index
a[0]
a[0]
Modifying element at index
a[0] = 4
a[0] = 4
Adding element at final position
a.push(8)
a.append(8)
Python can use 'append' to place an item anywhere in the List, but Javascript's 'push' will only add the element after the final element.
Inserting at index
a.splice(1, 0, 'item added')
a.insert(1, 'item added')
The second argument for Javascript's '.splice()' is for how many elements you want to remove starting on the position of the first argument.
Removing last element
a.pop()
a.pop()
Removing first element with value
a.remove(4)
Javascript doesn't offer an easy way to do remove the first match and stop. You can do a 'for loop' to remove one and break after the first match or use '.findIndex()' and then '.splice()' on that element.
Join Array/List elements as single string
['Hello', 'world!'].join(' ')
hello = ['Hello', 'world!']
' '.join(hello)
Slicing (set range)
a.slice(1, 4)
a[1:4]
Slicing (start until set end)
a.slice(3)
a.[:3]
In Javascript, providing only one POSITIVE argument implies that is the end point.
Slicing (set start until end)
a.slice(-3)
a[-3:]
In Javascript, providing only one NEGATIVE argument implies that is the start point.
Sorting
a.sort()
a.sort()
Sorting descending
a.sort((a, b) => b - a)
a.sort(reverse=True)
Counting occurrences of element
a.count(4)
No Javascript equivalent.
Array/List length
[1, 2, 3].length
len([1, 2, 3])
New Set (1)
const uniqueSet = new Set([1, 2, 3])
uniqueSet = set((1, 2, 3))
New Set (2)
uniqueSet = {1, 2, 3}
Modifying (map) every element in an Array/List
[1, 2, 3].map(n => n * 2)
list(map(lambda n: n * 2, [1, 2, 3]))
Reduce an Array/List to single result
[1, 2, 3].reduce((total, curr) => total + curr)
reduce(lambda total, curr: total + curr, [1, 2, 3])
Count Set items
uniqueSet.size
len(uniqueSet)
Tuples
x = (1, 2, 3)
Javascript doesn't support Tuples yet, but there is a TC39 proposal to add them. Python's Tuples are also not modifiable. Once set, forever defined.
Objects/Dictionaries
Javascript
Python
Notes
New object/dict (1)
const o = {}
o = {}
New object/dict (2)
const o = new Object()
o = dict()
New object/dict (3)
const o = Object.create(null)
No Python equivalent.
Adding property (1)
obj['keyName'] = 'value'
dict['key_name'] = 'value'
Adding property (2)
obj.keyName = 'value'
setattr(dict, key_name, value)
Accessing property value (1)
obj['keyName']
dict['key_name']
Accessing property value (2)
obj.keyName
getattr(dict, key_name)
Length
len(dict)
Can't use obj.length in Javascript, but you can convert the Object to an Array using Object.entries(obj)/Object.keys(obj)/Object.values(obj) and then get the length of that.
Check if key exists
'key_name' in dict
'keyName' in obj
Comparing two objects/dictionaries
const a = {name: 'yuri'}
const b = {name: 'yuri'}
a == b // false
a = {name: 'yuri'}
b = {name: 'yuri'}
a == b # True
Python makes a deep equality check by default, Javascript instead compares if the reference in memory are the same.
Deleting a key
delete obj['key']
del obj['key']
Merging objects/dictionaries
{...objA, ...objB}
{**dictA, **dictB}
Classes
Javascript
Python
Notes
New Class
class Person {
constructor(name) {
this.name = name;
}
}
class Person:
def __init__(self, name):
self.name = name
Inheritance
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
Python has 'pass' for whenever you want to create/inherit a class, but not initialize properties.
Printing a class to console
class Person:
def __str__(self):
return f"Person {self.name} printed."
Javascript logs the object version of a class to the console, while Python outputs human-unreadable code if '__str__()' is not provided.
Loops
Javascript
Python
Notes
Looping through obj/dict keys
for (const key of Object.keys(obj)) {
console.log(key)
}
for key in dict.keys():
print(key)
Looping through obj/dict values
for (const value of Object.values(obj)) {
console.log(value)
}
for value in dict.values():
print(value)
Looping through obj/dict values
for (const val in obj) {
console.log(val)
}
for val in dict:
print(val)
Looping through obj/dict keys + values
for (const [k, v] of Object.entries(obj)) {
console.log(k, ':', v)
}
for k, v in dict.items():
print(k, ':', v)
Looping a set number of times
for (let i = 0; i < 10; i++) {
console.log(i)
}
for i in range(10):
print(i)
Looping Array/List (1)
for (let item of loopingArray) {
console.log(item)
}
for item in loopingList:
print(item)
Looping Array/List (2)
for (let i = 0; i < loopingArray.length; i++) {
console.log(loopingArray[i]);
}