Repository: sayazamurai/python-vs-javascript Branch: master Commit: 53387b23f054 Files: 5 Total size: 85.8 KB Directory structure: gitextract_4h1cm22n/ ├── LICENSE ├── README.md ├── index.html └── static/ ├── app.js └── prism-base16-atelierplateau.light.css ================================================ FILE CONTENTS ================================================ ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2018 Saya Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # [How to write X in both Python 3 and JavaScript (ES2015)](https://sayazamurai.github.io/python-vs-javascript/) [![](static/images/og.jpg)](https://sayazamurai.github.io/python-vs-javascript/) ================================================ FILE: index.html ================================================ How to write X in both Python 3 and JavaScript (ES2015)

How to write X in both Python 3 and JavaScript (ES2015)

Python and JavaScript are two of the most popular programming languages. If you're a Python programmer learning JavaScript, or a JavaScript programmer learning Python, this handy cheat sheet might help you.

This page is open sourced on GitHub. Pull requests are welcome!

Star

About the Author

I'm Saya, a jewelry designer and a junior JavaScript/Python developer living in Tokyo. Find me on Twitter: @sayajewels

If you're are Python programmer learning JavaScript, or a JavaScript programmer learning Python, this handy cheat sheet might help you. Pull requests are welcome! 🐥 ✨

How to write X in both Python 3 and JavaScript (ES2015)https://t.co/F3MScUMheC

— Saya (@sayajewels) September 14, 2018

See also: Ilya Schurov has made a similar page - check it out!

Table of Contents

Math: Absolute Value

Python 3 / abs

# 100
print(abs(-100))
# 50
print(abs(50))

JavaScript (ES2015) / abs

// 100
console.log(Math.abs(-100))
// 50
console.log(Math.abs(50))

Math: Round Numbers

Python 3 / ceil, floor, round

import math

# 2
print(math.ceil(1.5))
# 1
print(math.floor(1.5))
# 2
print(round(1.5))

JavaScript (ES2015) / ceil, floor, round

// 2
console.log(Math.ceil(1.5))
// 1
console.log(Math.floor(1.5))
// 2
console.log(Math.round(1.5))

Math: Max and Min

Python 3 / max, min

# 100
print(max(100, 50))
# 40
print(min(80, 40))

JavaScript (ES2015) / max, min

// 100
console.log(Math.max(100, 50))

// 40
console.log(Math.min(80, 40))

Control Flow: If else

Python 3 / if

some_number = 3

# Number is 3
if some_number == 1:
    print("Number is 1")
elif some_number == 2:
    print("Number is 2")
elif some_number == 3:
    print("Number is 3")
else:
    print("?")

JavaScript (ES2015) / if

const someNumber = 3

// Number is 3
if (someNumber === 1) {
  console.log('Number is 1')
} else if (someNumber === 2) {
  console.log('Number is 2')
} else if (someNumber === 3) {
  console.log('Number is 3')
} else {
  console.log('?')
}

Control Flow: Ternary

Python 3

x = 2
y = 3

# even
print("even" if x % 2 == 0 else "odd")
# odd
print("even" if y % 2 == 0 else "odd")

JavaScript (ES2015) / Conditional Operator

const x = 2
const y = 3

// even
console.log(x % 2 === 0 ? 'even' : 'odd')
// odd
console.log(y % 2 === 0 ? 'even' : 'odd')

Control Flow: Boolean

Python 3

# yes
if "abc" == "abc":
    print("yes")
else:
    print("no")

# yes
if "abc" != "def":
    print("yes")
else:
    print("no")

# no
if True and False:
    print("yes")
else:
    print("no")

# yes
if True or False:
    print("yes")
else:
    print("no")

# yes
if not False:
    print("yes")
else:
    print("no")

# no
if 0:
    print("yes")
else:
    print("no")

# no
if "":
    print("yes")
else:
    print("no")

# no
if []:
    print("yes")
else:
    print("no")

# no
if None:
    print("yes")
else:
    print("no")

# yes
if not not not None:
    print("yes")
else:
    print("no")

JavaScript (ES2015) / Falsy Values

// yes
if ('abc' === 'abc') {
  console.log('yes')
} else {
  console.log('no')
}

// yes
if ('abc' !== 'def') {
  console.log('yes')
} else {
  console.log('no')
}

// no
if (true && false) {
  console.log('yes')
} else {
  console.log('no')
}

// yes
if (true || false) {
  console.log('yes')
} else {
  console.log('no')
}

// yes
if (!false) {
  console.log('yes')
} else {
  console.log('no')
}

// no
if (0) {
  console.log('yes')
} else {
  console.log('no')
}

// no
if ('') {
  console.log('yes')
} else {
  console.log('no')
}

// no
if (undefined) {
  console.log('yes')
} else {
  console.log('no')
}

// no
if (null) {
  console.log('yes')
} else {
  console.log('no')
}

// yes
if (!!!null) {
  console.log('yes')
} else {
  console.log('no')
}

Control Flow: Exceptions

Python 3 / Errors

# foo is not defined
try:
    foo()
except NameError:
    print("foo is not defined")

JavaScript (ES2015) / try...catch

// foo is not defined
try {
  foo()
} catch (error) {
  console.log('foo is not defined')
}

Control Flow: Continue / Break

Python 3 / break/continue

# 1
# 2
# Fizz
# 4
# Buzz
for number in range(1, 101):
    if number == 3:
        print("Fizz")
        continue
    if number == 5:
        print("Buzz")
        break
    print(number)

JavaScript (ES2015) / continue, break

// 1
// 2
// Fizz
// 4
// Buzz
for (let i = 1; i <= 100; i = i + 1) {
  if (i === 3) {
    console.log('Fizz')
    continue
  }

  if (i === 5) {
    console.log('Buzz')
    break
  }

  console.log(i)
}

String: Length

Python 3 / len

some_string = "abcd"

# 4
print(len(some_string))

JavaScript (ES2015) / length

const someString = 'abcd'

// 4
console.log(someString.length)

String: Interpolation

Python 3

x = "Hello"

# Hello World
print(f"{x} World")

JavaScript (ES2015)

const x = 'Hello'

// Hello World
console.log(`${x} World`)

String: Multiline

Python 3

x = """------
Line 1
Line 2
Line 3
------"""

# ------
# Line 1
# Line 2
# Line 3
# ------
print(x)

JavaScript (ES2015) / Multiline Strings

const x = `------
Line 1
Line 2
Line 3
------`

// ------
// Line 1
// Line 2
// Line 3
// ------
console.log(x)

String: String to Integer

Python 3 / int

string_1 = "1"
number_1 = int(string_1)

# 3
print(number_1 + 2)

JavaScript (ES2015) / parseInt

const string1 = '1'
const number1 = parseInt(string1)

// 3
console.log(number1 + 2)

String: Contains

Python 3 / in

# 2 is in the string
if "2" in "123":
    print("2 is in the string")

# 2 is not in the string
if "2" not in "456":
    print("2 is not in the string")

JavaScript (ES2015) / includes

// 2 is in the string
if ('123'.includes('2')) {
  console.log('2 is in the string')
}

// 2 is not in the string
if (!'456'.includes('2')) {
  console.log('2 is not in the string')
}

String: Substring

Python 3 / [i:j]

some_string = "0123456"

# 234
print(some_string[2:5])

JavaScript (ES2015) / substring

const someString = '0123456'

// 234
console.log(someString.substring(2, 5))

String: Join

Python 3 / join

some_list = ["a", "b", "c"]

# a,b,c
print(",".join(some_list))

JavaScript (ES2015) / join

const someList = ['a', 'b', 'c']

// a,b,c
console.log(someList.join(','))

String: Strip

Python 3 / strip

some_string = "   abc   "

# abc
print(some_string.strip())

JavaScript (ES2015) / trim

const someString = '   abc   '

// abc
console.log(someString.trim())

String: Split

Python 3 / split

some_string = "a,b,c"
some_string_split = some_string.split(",")

# a
print(some_string_split[0])
# b
print(some_string_split[1])
# c
print(some_string_split[2])

JavaScript (ES2015) / split

const someString = 'a,b,c'
const someStringSplit = someString.split(',')

// a
console.log(someStringSplit[0])
// b
console.log(someStringSplit[1])
// c
console.log(someStringSplit[2])

String: Replace

Python 3 / replace

some_string = "a b c d e"

# a,b,c,d,e
print(some_string.replace(" ", ","))

JavaScript (ES2015) / Regular Expressions, replace

const someString = 'a b c d e'

// Only changes the first space
// a,b c d e
// console.log(someString.replace(' ', ','))

// Use / /g instead of ' ' to change every space
console.log(someString.replace(/ /g, ','))

String: Search

Python 3 / search

import re

# Has a number
if re.search(r"\d", "iphone 8"):
    print("Has a number")

# Doesn't have a number
if not re.search(r"\d", "iphone x"):
    print("Doesn't have a number")

JavaScript (ES2015) / Regular Expressions, match

// Has a number
if ('iphone 8'.match(/\d/g)) {
  console.log('Has a number')
}

// Doesn't have a number
if (!'iphone x'.match(/\d/g)) {
  console.log("Doesn't have a number")
}

List/Array: Iteration

Python 3

some_list = [6, 3, 5]

# 6
# 3
# 5
for item in some_list:
    print(item)

JavaScript (ES2015) / forEach

const someList = [6, 3, 5]

// 6
// 3
// 5
someList.forEach(element => {
  console.log(element)
})

List/Array: Length

Python 3 / len

some_list = [1, 4, 9]

# 3
print(len(some_list))

JavaScript (ES2015) / length

const someList = [1, 4, 9]

// 3
console.log(someList.length)

List/Array: Enumerate

Python 3 / enumerate, list

some_list = [6, 3, 5]

# 0 6
# 1 3
# 2 5
for i, item in enumerate(some_list):
    print(f"{i} {item}")

# If you're not using this in a for loop, use list()
# list(enumerate(some_list)) # [(0, 6), (1, 3), (2, 5)]

JavaScript (ES2015) / forEach, map

const someList = [6, 3, 5]

// 0 6
// 1 3
// 2 5

someList.forEach((element, index) => {
  console.log(`${index} ${element}`)
})

List/Array: Contains

Python 3 / in

# 2 is in the list
if 2 in [1, 2, 3]:
    print("2 is in the list")

# 2 is not in the list
if 2 not in [4, 5, 6]:
    print("2 is not in the list")

JavaScript (ES2015) / includes

// 2 is in the list
if ([1, 2, 3].includes(2)) {
  console.log('2 is in the list')
}

// 2 is not in the list
if (![4, 5, 6].includes(2)) {
  console.log('2 is not in the list')
}

List/Array: Reverse

Python 3 / reversed, list

some_list = [1, 2, 3, 4]

# reversed(some_list) is just an iterable.
# To convert an iterable into a list, use list()
reversed_list = list(reversed(some_list))

# 4
# 3
# 2
# 1
for item in reversed_list:
    print(item)

# You can use an iterable instead of a list in a for loop
# for item in reversed(some_list):

JavaScript (ES2015) / reverse

const someList = [1, 2, 3, 4]

someList.reverse()

// 4
// 3
// 2
// 1
someList.forEach(element => {
  console.log(element)
})

List/Array: Range Iteration

Python 3 / range

# 0
# 1
# 2
# 3
for i in range(4):
    print(i)

# 4
# 5
# 6
# 7
for i in range(4, 8):
    print(i)

# 6
# 5
# 4
for i in range(6, 3, -1):
    print(i)

JavaScript (ES2015)

// 0
// 1
// 2
// 3
for (let i = 0; i < 4; i++) {
  console.log(i)
}

// 4
// 5
// 6
// 7
for (let i = 4; i < 8; i++) {
  console.log(i)
}

// 6
// 5
// 4
for (let i = 6; i > 3; i--) {
  console.log(i)
}

List/Array: Append with Modification

Python 3 / append

some_list = [1, 2]

some_list.append(3)

# 1
# 2
# 3
for x in some_list:
    print(x)

JavaScript (ES2015) / push

const someList = [1, 2]

someList.push(3)

// 1
// 2
// 3
someList.forEach(element => {
  console.log(element)
})

List/Array: Append without Modification

Python 3 / Unpacking

original_list = [1, 2]

# [original_list, 3] -> [[1, 2], 3]
# [*original_list, 3] -> [1, 2, 3]
new_list = [*original_list, 3]
original_list[0] = 5

# 1
# 2
# 3
for x in new_list:
    print(x)

JavaScript (ES2015) / Spread

const originalList = [1, 2]

// [originalList, 3] -> [[1, 2], 3]
// [...originalList, 3] -> [1, 2, 3]
const newList = [...originalList, 3]
originalList[0] = 5

// 1
// 2
// 3
newList.forEach(element => {
  console.log(element)
})

List/Array: Extend with Modification

Python 3 / extend

some_list = [1]

some_list.extend([2, 3])

# 1
# 2
# 3
for x in some_list:
    print(x)

JavaScript (ES2015) / Spread

const someList = [1]

someList.push(...[2, 3])

// 1
// 2
// 3
someList.forEach(element => {
  console.log(element)
})

List/Array: Extend without Modification

Python 3 / List addition

original_list = [1]
new_list = original_list + [2, 3]
original_list[0] = 5

# 1
# 2
# 3
for x in new_list:
    print(x)

JavaScript (ES2015) / concat

const originalList = [1]
const newList = originalList.concat([2, 3])
originalList[0] = 5

// 1
// 2
// 3
newList.forEach(element => {
  console.log(element)
})

List/Array: Prepend

Python 3 / insert

some_list = [4, 5]

some_list.insert(0, 3)

# 3
# 4
# 5
for x in some_list:
    print(x)

JavaScript (ES2015) / unshift

const someList = [4, 5]
someList.unshift(3)

// 3
// 4
// 5
someList.forEach(element => {
  console.log(element)
})

List/Array: Remove

Python 3 / del

some_list = ["a", "b", "c"]
del some_list[1]

# a
# c
for x in some_list:
    print(x)

JavaScript (ES2015) / splice

const someList = ['a', 'b', 'c']
someList.splice(1, 1)

// a
// c
someList.forEach(element => {
  console.log(element)
})

List/Array: Pop

Python 3 / pop

some_list = [1, 2, 3, 4]

# 4
print(some_list.pop())
# 1
print(some_list.pop(0))

# 2
# 3
for x in some_list:
    print(x)

JavaScript (ES2015) / pop, shift

const someList = [1, 2, 3, 4]

// 4
console.log(someList.pop())

// 1
console.log(someList.shift())

// 2
// 3
someList.forEach(element => {
  console.log(element)
})

List/Array: Index

Python 3 / index

some_list = ["a", "b", "c", "d", "e"]

# 2
print(some_list.index("c"))

JavaScript (ES2015) / indexOf

const someList = ['a', 'b', 'c', 'd', 'e']

// 2
console.log(someList.indexOf('c'))

List/Array: Copy

Python 3 / [i:j]

original_list = [1, 2, 3]
new_list = original_list[:]  # or original_list.copy()

original_list[2] = 4

# 1
# 2
# 3
for x in new_list:
    print(x)

JavaScript (ES2015) / Spread

const originalList = [1, 2, 3]
const newList = [...originalList]

originalList[2] = 4

// 1
// 2
// 3
newList.forEach(element => {
  console.log(element)
})

List/Array: Map

Python 3 / List Comprehensions

original_list = [1, 2, 3]
new_list = [x * 2 for x in original_list]

# 2
# 4
# 6
for x in new_list:
    print(x)

JavaScript (ES2015) / map

const originalList = [1, 2, 3]

// You can also do this:
// const newList = originalList.map(x => { return x * 2 })
const newList = originalList.map(x => x * 2)

// 2
// 4
// 6
newList.forEach(element => {
  console.log(element)
})

List/Array: Map (Nested)

Python 3 / List Comprehensions

first_list = [1, 3]
second_list = [3, 4]
combined_list = [[x + y for y in second_list] for x in first_list]

# 4
print(combined_list[0][0])
# 5
print(combined_list[0][1])
# 6
print(combined_list[1][0])
# 7
print(combined_list[1][1])

JavaScript (ES2015) / map

const firstList = [1, 3]
const secondList = [3, 4]

const conbinedList = firstList.map(x => {
  return secondList.map(y => {
    return x + y
  })
})

// 4
console.log(conbinedList[0][0])
// 5
console.log(conbinedList[0][1])
// 6
console.log(conbinedList[1][0])
// 7
console.log(conbinedList[1][1])

List/Array: Filter

Python 3 / List Comprehensions

original_list = [1, 2, 3, 4, 5, 6]
new_list = [x for x in original_list if x % 2 == 0]

# 2
# 4
# 6
for x in new_list:
    print(x)

JavaScript (ES2015) / filter

const originalList = [1, 2, 3, 4, 5, 6]
const newList = originalList.filter(x => x % 2 == 0)

// 2
// 4
// 6
newList.forEach(element => {
  console.log(element)
})

List/Array: Sum

Python 3 / sum

some_list = [1, 2, 3]

# 6
print(sum(some_list))

JavaScript (ES2015) / reduce

const someList = [1, 2, 3]
const reducer = (accumulator, currentValue) => accumulator + currentValue

// 6
console.log(someList.reduce(reducer))

List/Array: Zip

Python 3 / zip

list_1 = [1, 3, 5]
list_2 = [2, 4, 6]

# 1 2
# 3 4
# 5 6
for x, y in zip(list_1, list_2):
    print(f"{x} {y}")

JavaScript (ES2015) / map

const list1 = [1, 3, 5]
const list2 = [2, 4, 6]

// [[1, 2], [3, 4], [5, 6]]
const zippedList = list1.map((x, y) => {
  return [x, list2[y]]
})

zippedList.forEach(element => {
  console.log(`${element[0]} ${element[1]}`)
})

List/Array: Slice

Python 3 / [i:j]

original_list = ["a", "b", "c", "d", "e"]
new_list = original_list[1:3]
original_list[1] = "x"

# b
# c
for x in new_list:
    print(x)

JavaScript (ES2015) / slice

const originalList = ['a', 'b', 'c', 'd', 'e']
const newList = originalList.slice(1, 3)
originalList[1] = 'x'

// b
// c
newList.forEach(element => {
  console.log(element)
})

List/Array: Sort

Python 3 / sorted

some_list = [4, 2, 1, 3]

# 1
# 2
# 3
# 4
for item in sorted(some_list):
    print(item)

JavaScript (ES2015) / sort

const someList = [4, 2, 1, 3]

// 1
// 2
// 3
// 4
someList.sort().forEach(element => {
  console.log(element)
})

List/Array: Sort Custom

Python 3 / sorted

some_list = [["c", 2], ["b", 3], ["a", 1]]

# a 1
# c 2
# b 3
for item in sorted(some_list, key=lambda x: x[1]):
    print(f"{item[0]} {item[1]}")

JavaScript (ES2015) / sort

const someList = [['c', 2], ['b', 3], ['a', 1]]

// a 1
// c 2
// b 3
someList
  .sort((a, b) => {
    return a[1] - b[1]
  })
  .forEach(element => {
    console.log(`${element[0]} ${element[1]}`)
  })

Dictionary/Object: Iteration

Python 3 / items

some_dict = {"one": 1, "two": 2, "three": 3}

# one 1
# two 2
# three 3
# NOTE: If you're not using this in a for loop,
# convert it into a list: list(some_dict.items())
for key, value in some_dict.items():
    print(f"{key} {value}")

JavaScript (ES2015) / entries

const someDict = { one: 1, two: 2, three: 3 }

// one 1
// two 2
// three 3

Object.entries(someDict).forEach(element => {
  console.log(`${element[0]} ${element[1]}`)
})

Dictionary/Object: Contains

Python 3 / in

some_dict = {"one": 1, "two": 2, "three": 3}

# one is in the dict
if "one" in some_dict:
    print("one is in the dict")

# four is not in the dict
if "four" not in some_dict:
    print("four is not in the dict")

JavaScript (ES2015) / hasOwnProperty

const someDict = { one: 1, two: 2, three: 3 }

// one is in the dict
if (someDict.hasOwnProperty('one')) {
  console.log('one is in the dict')
}

// four is not in the dict
if (!someDict.hasOwnProperty('four')) {
  console.log('four is not in the dict')
}

Dictionary/Object: Add with Modification

Python 3

original_dict = {"one": 1, "two": 2}
original_dict["three"] = 3

# one 1
# two 2
# three 3
for key, value in original_dict.items():
    print(f"{key} {value}")

JavaScript (ES2015)

const originalDict = { one: 1, two: 2 }
originalDict.three = 3

// one 1
// two 2
// three 3
Object.entries(originalDict).forEach(element => {
  console.log(`${element[0]} ${element[1]}`)
})

Dictionary/Object: Add without Modification

Python 3 / Unpacking

original_dict = {"one": 1, "two": 2}
new_dict = {**original_dict, "three": 3}
original_dict["one"] = 100

# one 1
# two 2
# three 3
for key, value in new_dict.items():
    print(f"{key} {value}")

JavaScript (ES2015) / Spread

const originalDict = { one: 1, two: 2 }
const newDict = { ...originalDict, three: 3 }
originalDict.one = 100

// one 1
// two 2
// three 3
Object.entries(newDict).forEach(element => {
  console.log(`${element[0]} ${element[1]}`)
})

Dictionary/Object: Keys

Python 3 / keys

some_dict = {"one": 1, "two": 2, "three": 3}

# one
# two
# three
# NOTE: If you're not using this in a for loop,
# convert it into a list: list(some_dict.keys())
for x in some_dict.keys():
    print(x)

JavaScript (ES2015) / keys

const someDict = { one: 1, two: 2, three: 3 }

// one
// two
// three
Object.keys(someDict).forEach(element => {
  console.log(element)
})

Dictionary/Object: Values

Python 3 / values

some_dict = {"one": 1, "two": 2, "three": 3}


# 1
# 2
# 3
# NOTE: If you're not using this in a for loop,
# convert it into a list: list(some_dict.values())
for x in some_dict.values():
    print(x)

JavaScript (ES2015) / values

const someDict = { one: 1, two: 2, three: 3 }

// 1
// 2
// 3
Object.values(someDict).forEach(element => {
  console.log(element)
})

Dictionary/Object: Remove

Python 3 / del

some_dict = {"one": 1, "two": 2, "three": 3}

del some_dict["two"]

# one 1
# three 3
for key, value in some_dict.items():
    print(f"{key} {value}")

JavaScript (ES2015) / delete

const someDict = { one: 1, two: 2, three: 3 }

delete someDict.two

Object.entries(someDict).forEach(element => {
  console.log(`${element[0]} ${element[1]}`)
})

Dictionary/Object: Get

Python 3 / get

some_dict = {"one": 1, "two": 2, "three": 3}

# some_dict["four"] will be KeyError

# Doesn't exist
print(some_dict.get("five", "Doesn't exist"))

JavaScript (ES2015) / ||

const someDict = { one: 1, two: 2, three: 3 }

// Doesn't exist
console.log(someDict.five || "Doesn't exist")

Dictionary/Object: Map

Python 3 / Dictionary Comprehensions

original_list = {"one": 1, "two": 2}

# {"one": 1, "two": 4}
new_list = {key: value * value for key, value in original_list.items()}

# one 1
# two 4
for key, value in new_list.items():
    print(f"{key} {value}")

JavaScript (ES2015) / entries

const originalDict = { one: 1, two: 2 }
const newDict = {}

Object.entries(originalDict).forEach(element => {
  // newDict.element[0] doesn't work - for variable key use []
  newDict[element[0]] = element[1] * element[1]
})

// one 1
// two 4
Object.entries(newDict).forEach(element => {
  console.log(`${element[0]} ${element[1]}`)
})

Dictionary/Object: Copy

Python 3 / copy

original_dict = {"one": 1, "two": 2, "three": 3}
new_dict = original_dict.copy()
original_dict["one"] = 100

# one 1
# two 2
# three 3
for key, value in new_dict.items():
    print(f"{key} {value}")

JavaScript (ES2015) / Spread

const originalDict = { one: 1, two: 2, three: 3 }
const newDict = { ...originalDict }
originalDict.one = 100

// one 1
// two 2
// three 3
Object.entries(newDict).forEach(element => {
  console.log(`${element[0]} ${element[1]}`)
})

Dictionary/Object: Dictionary/Object to JSON string

Python 3 / json.dumps

import json

some_dict = {"one": 1, "two": 2, "three": 3}

# {
#   "one": 1,
#   "two": 2,
#   "three": 3
# }
print(json.dumps(some_dict, indent=2))

JavaScript (ES2015) / JSON.stringify

const someDict = { one: 1, two: 2, three: 3 }

// {
//   "one": 1,
//   "two": 2,
//   "three": 3
// }
console.log(JSON.stringify(someDict, null, 2))

Dictionary/Object: JSON string to Dictionary/Object

Python 3 / json.loads

import json

some_json = """{
  "one": 1,
  "two": 2,
  "three": 3
}"""

dict_from_json = json.loads(some_json)

# 2
print(dict_from_json["two"])

JavaScript (ES2015) / JSON.parse

const someJson = `{
  "one": 1,
  "two": 2,
  "three": 3
}`

const dictFromJson = JSON.parse(someJson)

// 2
console.log(dictFromJson.two)

Dictionary/Object: Variable Key

Python 3

some_variable = 2
some_dict = {(some_variable + 1): "three"}

# three
print(some_dict[3])

JavaScript (ES2015) / Computed Property Names

const someVariable = 2
const someDict = { [someVariable + 1]: 'three' }

// three
console.log(someDict[3])

Function: Definitions

Python 3

def add(x, y):
    print(f"Adding {x} and {y}")
    return x + y


# Adding 1 and 2
# 3
print(add(1, 2))

JavaScript (ES2015)

const add = (x, y) => {
  console.log(`Adding ${x} and ${y}`)
  return x + y
}
// Adding 1 and 2
// 3
console.log(add(1, 2))

Function: Keyword Arguments

Python 3

def add(a, b, c):
    return a + b + c


# 6
print(add(b=1, a=2, c=3))

JavaScript (ES2015)

const add = ({ a, b, c }) => {
  return a + b + c
}

// 6
console.log(
  add({
    b: 1,
    a: 2,
    c: 3
  })
)

Function: Default Arguments

Python 3

def greet(name, word="Hello"):
    print(f"{word} {name}")


# Hello World
greet("World")

# Goodbye World
greet("World", "Goodbye")

JavaScript (ES2015) / Default Parameters

const greet = (name, word = 'Hello') => {
  console.log(`${word} ${name}`)
}

// Hello World
greet('World')

// Goodbye World
greet('World', 'Goodbye')

Function: Default Keyword Arguments

Python 3

def greet(name="World", word="Hello"):
    print(f"{word} {name}")


# Goodbye World
greet(word="Goodbye")

# Hello Programming
greet(name="Programming")

JavaScript (ES2015) / Default Value

const greet = ({ name = 'World', word = 'Hello' }) => {
  console.log(`${word} ${name}`)
}

// Goodbye World
greet({ word: 'Goodbye' })

// Hello Programming
greet({ name: 'Programming' })

Function: Positional Arguments

Python 3 / Arbitrary Argument Lists

def positional_args(a, b, *args):
    print(a)
    print(b)
    for x in args:
        print(x)


# 1
# 2
# 3
# 4
positional_args(1, 2, 3, 4)

JavaScript (ES2015) / Rest Parameters

const positionalArgs = (a, b, ...args) => {
  console.log(a)
  console.log(b)
  args.forEach(element => {
    console.log(element)
  })
}

// 1
// 2
// 3
// 4
positionalArgs(1, 2, 3, 4)

Function: Variable Keyword Arguments

Python 3 / Keyword Arguments

def func_1(**kwargs):
    for key, value in kwargs.items():
        print(f"{key} {value}")


def func_2(x, *args, **kwargs):
    print(x)
    for arg in args:
        print(arg)
    for key, value in kwargs.items():
        print(f"{key} {value}")


# one 1
# two 2
func_1(one=1, two=2)

# 1
# 2
# 3
# a 4
# b 5
func_2(1, 2, 3, a=4, b=5)

JavaScript (ES2015) / Rest Parameters

const func1 = kwargs => {
  Object.entries(kwargs).forEach(element => {
    console.log(`${element[0]} ${element[1]}`)
  })
}

//  ...args must be the last argument
const func2 = (x, kwargs, ...args) => {
  console.log(x)
  args.forEach(element => {
    console.log(element)
  })
  Object.entries(kwargs).forEach(element => {
    console.log(`${element[0]} ${element[1]}`)
  })
}

// one 1
// two 2
func1({ one: 1, two: 2 })

// 1
// 2
// 3
// a 4
// b 5
func2(1, { a: 4, b: 5 }, 2, 3)

Class: Basics

Python 3 / Classes

class Duck:
    def __init__(self, name):
        self.name = name

    def fly(self):
        print(f"{self.name} can fly")

    # not @classmethod: call a method on an instance
    # duck = Duck(...)
    # duck.create(...)
    #
    # @classmethod: call a method on a class
    # Duck.create(...)
    @classmethod
    def create(cls, name, kind):
        if kind == "mallard":
            return MallardDuck(name)
        elif kind == "rubber":
            return RubberDuck(name)
        else:
            # cls = Duck
            return cls(name)


class MallardDuck(Duck):
    # @property:
    # use duck.color instead of duck.color()
    @property
    def color(self):
        return "green"


class RubberDuck(Duck):
    def __init__(self, name, eye_color="black"):
        super().__init__(name)
        self.eye_color = eye_color

    def fly(self):
        super().fly()
        print(f"Just kidding, {self.name} cannot fly")

    @property
    def color(self):
        return "yellow"


regularDuck = Duck("reggie")
# reggie can fly
regularDuck.fly()

mallardDuck = Duck.create("mal", "mallard")
# mal
print(mallardDuck.name)
# green
print(mallardDuck.color)

rubberDuck = RubberDuck("vic", "blue")
# vic can fly
# Just kidding, vic cannot fly
rubberDuck.fly()
# yellow
print(rubberDuck.color)
# blue
print(rubberDuck.eye_color)

JavaScript (ES2015) / Classes, Method Definitions, static, get, super

class Duck {
  constructor(name) {
    this.name = name
  }

  fly() {
    console.log(`${this.name} can fly`)
  }

  // not static: call a method on an instance
  // const duck = new Duck(...)
  // duck.create(...)
  //
  // static: call a method on a class
  // Duck.create(...)
  static create(name, kind) {
    if (kind === 'mallard') {
      return new MallardDuck(name)
    } else if (kind === 'rubber') {
      return new RubberDuck(name)
    } else {
      // this = Duck
      return new this(name)
    }
  }
}

class MallardDuck extends Duck {
  // get:
  // use duck.color instead of duck.color()
  get color() {
    return 'green'
  }
}

class RubberDuck extends Duck {
  constructor(name, eyeColor = 'black') {
    super(name)
    this.eyeColor = eyeColor
  }

  fly() {
    super.fly()
    console.log(`Just kidding, ${this.name} cannot fly`)
  }

  get color() {
    return 'yellow'
  }
}

const regularDuck = new Duck('reggie')
// reggie can fly
regularDuck.fly()

const mallardDuck = Duck.create('mal', 'mallard')
// mal
console.log(mallardDuck.name)
// green
console.log(mallardDuck.color)

rubberDuck = new RubberDuck('vic', 'blue')
// vic can fly
// Just kidding, vic cannot fly
rubberDuck.fly()

// yellow
console.log(rubberDuck.color)

// blue
console.log(rubberDuck.eyeColor)
================================================ FILE: static/app.js ================================================ $(function() { $('.js-bottom-right-button-link').click(function(e) { $('html, body').animate({ scrollTop: 0 }, 'slow') // デフォルトのhref="#"の挙動をなくす // function()をfunction(e)にする必要がある e.preventDefault() }) // https:// か http:// ではじまるリンクは新しいタブで開く $("a[href^='https://'], a[href^='http://']").attr('target', '_blank') }) ================================================ FILE: static/prism-base16-atelierplateau.light.css ================================================ /* Name: Base16 Atelier Plateau Light Author: Bram de Haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/plateau) Prism template by Bram de Haan (http://atelierbram.github.io/syntax-highlighting/prism/) Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */ code[class*="language-"], pre[class*="language-"] { font-family: Consolas, Menlo, Monaco, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", "Courier New", Courier, monospace; font-size: 14px; line-height: 1.375; direction: ltr; text-align: left; white-space: pre; word-spacing: normal; word-break: normal; -moz-tab-size: 4; -o-tab-size: 4; tab-size: 4; -webkit-hyphens: none; -ms-hyphens: none; hyphens: none; background: #f4ecec; color: #585050; } pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection, code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection { text-shadow: none; background: #e7dfdf; } pre[class*="language-"]::selection, pre[class*="language-"] ::selection, code[class*="language-"]::selection, code[class*="language-"] ::selection { text-shadow: none; background: #e7dfdf; } /* Code blocks */ pre[class*="language-"] { padding: 1em; margin: .5em 0; overflow: auto; } /* Inline code */ :not(pre) > code[class*="language-"] { padding: .1em; border-radius: .3em; } .token.comment, .token.prolog, .token.doctype, .token.cdata { color: #7e7777; } .token.punctuation { color: #585050; } .token.namespace { opacity: .7; } .token.operator, .token.boolean, .token.number { color: #b45a3c; } .token.property { color: #a06e3b; } .token.tag { color: #7272ca; } .token.string { color: #5485b6; } .token.selector { color: #8464c4; } .token.attr-name { color: #b45a3c; } .token.entity, .token.url, .language-css .token.string, .style .token.string { color: #5485b6; } .token.attr-value, .token.keyword, .token.control, .token.directive, .token.unit { color: #4b8b8b; } .token.statement, .token.regex, .token.atrule { color: #5485b6; } .token.placeholder, .token.variable { color: #7272ca; } .token.deleted { text-decoration: line-through; } .token.inserted { border-bottom: 1px dotted #1b1818; text-decoration: none; } .token.italic { font-style: italic; } .token.important, .token.bold { font-weight: bold; } .token.important { color: #ca4949; } .token.entity { cursor: help; } pre > code.highlight { outline: 0.4em solid #ca4949; outline-offset: .4em; } .line-numbers .line-numbers-rows { border-right-color: #e7dfdf !important; } .line-numbers-rows > span:before { color: #8a8585 !important; } .line-highlight { background: rgba(27, 24, 24, 0.2) !important; background: -webkit-linear-gradient(left, rgba(27, 24, 24, 0.2) 70%, rgba(27, 24, 24, 0)) !important; background: linear-gradient(to right, rgba(27, 24, 24, 0.2) 70%, rgba(27, 24, 24, 0)) !important; }