| Topic | Python | both | JavaScript |
|---|---|---|---|
| comments | #""" """ |
///* */ |
|
| declaration | my_var = 5 |
var myVar = 5let myVar = 5 const myVar = 5 |
|
| operators | // |
+-***/% |
|
| assignment | =+=-=*=**=/=%= |
||
| deletion | del(my_var) |
delete(myVar) |
|
| increment decrement |
++-- |
||
| equivalence | is |
==!= |
===!== |
| equivalence rules | []==[] returns True |
[]==[] returns false (because not referring to the same instance) |
|
| casting | str()int()float()bool() |
String()Number()Boolean() |
|
| special types | without imports, float('inf')float(nan) |
NaNundefinednullInfinity |
|
| type checking | type() |
typeof()isNaN()isFinite() |
|
| array data structure | [] is called a 'list' but is implemented as an array |
[1,2,3] | [] is aptly referred to as an array |
| indexing | [1,2][0][0] returns TypeError |
[1,2][0] returns 1 |
[1,2][0][0] returns undefined |
| immutable arrays | (1,2,3) called a tuple |
(2,3) is syntactically valid but not useful (returns last element only (3)) |
|
| inserting array element | a=[]a[0]=10 returns SyntaxError |
var a = []a[0]=10a[100]=20returns length 101 array ( [10, <99 empty items>, 20]) |
|
| removing array element | arr=['h','i','!']del arr[1]returns ['h','!'] |
var arr=['h','i','!'];delete arr[1]returns ['h','!'] |
|
| array length | len([1,2,3]) |
[1,2,3].length |
|
| access last array element | [1,2,3][-1] |
arr=[1,2,3];arr[arr.length-1]; |
|
| slicing | [1,2,3][:1][1,2,3][1:] |
[1,2,3].slice(null,2)[1,2,3].slice(1) |
|
| clear array | arr.clear() |
arr.length = 0; |
|
| array methods | arr.append(5)arr.extend([5,6]).insert().remove().index() |
.reverse().sort().pop() |
arr.push(5)arr.push(5,6).filter() .map() .reduce().every() .some().keys().shift() .unshift() |
| in | in refers to values |
in |
in refers to indexes |
| range array | x=list(range(10))or as a list comprehension x=[i for i in range(10)]or in Python3 with unpacking operator x=[*range(10)] |
x=[];for (i=0;i<10;i++) {x[i]=i}; |
|
| string element indexing | 'hello'[1] returns 'e' |
||
| string overloaded ops | * |
+ |
'2'*'50' returns type number 100so does '2'*50 |
| string methods | capitalize()find()upper() lower()isupper() islower()split() count() |
.length (no parens).indexOf() .lastIndexOf().slice(,) .replace(,).toUpperCase() .toLowerCase().concat(,) .charAt().split() |
|
| array-of-string concatenation | ['hello'] + [' world'] |
['hello'].concat([' world']) |
|
| string casting | list('hi') returns ['h','i']tuple('hi') returns ('h','i') |
var arr = new Array('4') returns ['4']this next one is not sting casting, but var arr = new Array(4) returns length 4 array [,,,,] (note that JS ignores the last comment when there is no data between it and the bracket) |
|
| regular expressions | not built in, import re |
var a = myStr.search(/mySearchStr/i) |
|
| JSON-like syntax | i,j='k',1b={i:j} returns hash table (dictionary) {'k':1} |
i='k';j=1; b={i:j} returns object {i:'k',j:1} |
|
| printing | print() |
console.log() |
|
| datetime | import datetime as dtd=dt.datetime.now().timestamp()gets seconds with millisecond precision since 1970 |
var d = new Date()d.getTime();gets milliseconds since 1970 |
|
| control flow keywords | pass |
continuebreak |
|
| if | if (conditions):elif (conditions):else: |
if(conditions) { }else if (conditions) { }else { }; |
|
| while | while(conditions): |
while(conditions) { }; |
|
| do-while | not built inwhile True:.... #code.... if (condition):........ break |
do {]while(conditions) { }; |
|
| for | for i in range(5):for items in list: |
for ( var i=0; i<5; i++) { }; |
|
| switch | not built in | switch(myCase) { case 1: break;.... default: }; |
|
| try-catch | try:except:finally: |
try { throw "myErr";}catch(err) { }finally { }; |
|
| doctests | def sum(a,b):.... """ >>> sum(2,2).... 4 """ |
not built innpm install doctest |
|
| object properties (attributes and methods) | class MyClass(object):.... def __init__(self):........ self.attrib=5.... def myMethod(self):........ passmyInstance = MyClass() |
there is a lot more to properly comparing OOP between JS and Python - I will update soon.myInst={myAttrib:5,myMethod:function(){},}; |
|
| promises | not built in | var promise1 = new Promise(function(resolve, reject) {.... setTimeout(function() {........ resolve('foo'); }, 300); });promise1.then(function(value) {.... console.log(value); });console.log(promise1); |
|
| lambdas | def addTen(myNum):.... return myNum + 10can be written as addTen = lambda myNum: myNum + 10 |
function addTen(myNum) { return myNum + 10 };can be written as const addTen = (myNum) => myNum + 10; |
|
| map example | def double(x):.... return x*2y=map(double,[1,2,3])can be written as y= list(map(lambda x: x*2, [1,2,3]))or as a list comprehension (not a map) y=[i*2 for i in [1,2,3]] |
const y=[1,2,3].map(x => x*2); |
Created
April 3, 2020 14:15
-
-
Save asa55/3bc818a88eb9b44d60545874392e19a0 to your computer and use it in GitHub Desktop.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
initial commit