You are here

JavaScript and Python, and their simple differences

A note:

[DRAFT] Differences between Javascript and Python.

Beneeth describes a bit going through the syntax of code.

Syntax

Comments

Javascript

/*multiline
comment */
// one-line comment
var x = 1; // inside line comment

Python

"""Multiline comment
Only as docstring
"""
# one-line comment
x = 1 # inside line comment

Code Blocks

JavaScript uses curly brackets to denote code blocks.

function f() {
 if (x == 2) {
 x = 1;
 }
}

Python uses indentation.

def f():
 if x == 2:
 x = 5

Statement Terminators

JavaScript uses semicolons ; to terminate statements.

var x = "S";
x.split();

Python uses newlines.

x = "S"
x.split()

Assignment

Javascript

var x = 5;
var s = "string";

Python

x = 5
s = "string"

Function Declarations

Javascript and Python could be defined or assigned to variable with name or an anonymous declaration.

Javascript

function f() {
 // definition
}
var fn = f; // assignment
var fa = function() {
 // anonymous
}

Python

def f():
 pass # definition
fn = f # assignment
fa = lambda : pass # anonymous

Function Arguments

JavaScript function do not care whether it is called with the arguments they are expecting or not. Any missing arguments get the value undefined, and any extra arguments end up in the special arguments object.

function f (x, y) {
}
f(5);
f(1, "s");
function f() {
 console.log(arguments); // arbitrary number of arguments
}

Python will raise an exception if a function is called with the wrong number of parameters. But it has another features for an arbitrary number of arguments as *args and **kwargs. And Python functions have default and named arguments.

def f(x, y):
 pass
f(1, 2)
f(y=2, x=1)
def fa(x, *args):
 print(args[1], args[0])
fa("X", 1, 2, 3, 4)
def fk(**kwargs):
 print(kwargs["a"])
fk(a=5)
def fd(x=5):
 pass
fd()

Method calling

Javascript

var x = "as sd";
x.split(" ");

Python x = "as sd" x.split()

If else

Javascript

if (x == 5){
 something(5);
} else if (x == 4){
 something(4);
}
else {
 something(0);
}

Python does not have to use brackets.

if x == 5:
 something(5)
elif x == 4:
 something(4)
else:
 something(0)

If else shortening

Javascript

var x = 5;
var a = (x % 2) ? "odd" : "even"

Python

x = 5
a = "odd" if x % 2 else "even"

Switch Case

Python does not have "swith-case" feature.

For loop

Javacript uses conditions and iterating in "for" loops.


Python uses only iterating in "for" loops.

for i in range(5): pass # range is generator as (0, 1, 3, 4, 5)
array = [1, 2, 3]
for el in array: pass

While loop

Javascript


Python


Equality and conversion

Javascript

1 == "1" // True
1 === "1" // False
Number("2.2")
String(2.2)

Python has only "=="

1 == "1" // False
float("2.2")
str(2.2)

Data types

Nothingness

Javascript JavaScript has two values that convey nothingness: undefined and null.

var n = null;
var x; // undefined

Python Python has only one value for nothingness: None.

n = None

Numbers

Javascript JavaScript has only one type of numbers. Numbers can be written with, or without decimals.

var x = 5; // Number
var y = 5.6; // Number

Python There are three distinct numeric types: integers, floating point numbers, and complex numbers.

i = 5 # int
f = 5.6 # float
c = 1 + 2j # complex

Strings

Javascript

var s = "Hello";
vas q = 'Hi "W"';

Python

s = "Hello"
q = 'Hi "W"'

Array => list/tuple

Javascript

var ar = [1, 2, 3, "a"];
ar.push(2);
ar[1] = 15;

Python has two built-in data types, list and tuple. Lists are an analog for JS arrays. Tuples are immutable lists and use round brackets.

ar = [1, 2, 3, "a"] # list
ar.append(2)
ar[1] = 15
tr = (1, 2, "b") # tuple

Hash table types

Javascript has no built-in hash-table support. Curly brackets are syntactic sugar for creating a new object, but this is not a hash-table type.

var d = {"a": 1, 2: 3}; // Object
d["a"] = 3; // with brackets
d.a = 4; // or with a dot

Python has built-in hash-table types, dict and set. Keys in dicts must be immutable. Sets are as dictionaries without values.

d = {"a": 1, 2: 3} # dict
d["a"] = 4 // only with brackets
d[2] = 4
s = {"a", 1, 2} # set

Boolean and logical operators

Javascript

var t = true;
var f = false;
if (t && f) {} // AND
if (t || f) {} // OR
if (!t) {} // NOT

Python

t = True
f = False
if t and f: pass # AND
if t or f: pass # OR
if not t: pass # NOT

More features

Exception handling

Javascript

try {
 a = x / y;
 if (b) {
 throw("Error");
 }
catch(err) {
 something();
}

Python give you more precious control by exceptions.

try:
 a = x / y
 if b:
 raise(ValueError);
except ZeroDivisionError: # We can choose exceptions
 print("zero")
except Exception as err: # assign name
 print(err)
except (RuntimeError, TypeError, NameError): # process several
 print("one of ...")
except: # or catch all
 print("Error!")
finally: # clean up
 a = 0

Classes

Javascript

function Foo(args) {
 this.args = args;
}
Foo.prototype.work = function () {
 // do something
};
foo = new Foo(data);
foo.();

Python

class Foo(object) {
 def __init__(self, args): # constructor
 self.args = args
 def work(self):
 # do something
 foo = Foo(data)
 foo.work()

Operator overloading

Javescript does not have this.

Python

class WeirdNumber(object):
 def __init__(self, n):
 self.n = n
 def __add__(self, other):
 return self.n + 2 * other
 def __str__(self):
 return "???"
w = WeirdNumber(3)
w + 4 # 11
str(w) # "???"

Array (list, dict, generator) comprehensions

Javascript 1.7

var numbers = [1, 4, 3, 21, 22, 30];
var processed = [i * 2 for (i of numbers) if (i % 3 === 1)];

Python

numbers = [1, 2, 3, 21, 22, 30]
processed = [i * 2 for i in numbers if i % 3 == 1] # list
g_processed = (i * 2 for i in numbers if i % 3 == 1) # generator
d_processed = {i: i * 2 for i in numbers if i % 3 == 1} # dict

Slices

Javascript

var n = [1, 2, 3, 4, 5];
n.slice(1, 3); // [2, 3]
n[n.length - 1]; // last element

Python

n = [1, 2, 3, 4, 5]
n[1:3] # [2,3]
n[-1] # last element
n[::-1] # reversed
n[0:4:2] # [1, 3]

Modules

JavaScript has few built-in modules: Math, Date, RegExp, and JSON. It have other functionality available through the host environment.

Math.ceil(5.5);
Math.random();
JSON.stringify(1);

Python is a “Batteries Included” language, and comes standard with a wide range of modules.

import math
from random import random
from json import * # avoid this practice
math.ceil(5.5)
random() # from random module
dumps(1) # it's json.dumps()

Closures

Javascript

function inc(x) {
 return function(y) {
 return
function inc(x) {
 return function (y) {
 return x + y
 }
}
var inc1 = inc(1);
inc1(2); // 3
function with_counter() {
 var i = 0;
 return function (x) {
 i++;
 return x + i;
 }
}
var c = with_counter(3);
c(0); // 1
c(0); // 2

Python

def inc(x):
 # without changing
 return lambda y: x + y
inc1 = inc(1)
inc1(2) # 3
def with_counter():
 # with changing
 i = 0
 def f(x):
 nonlocal i
 i += 1
 return x + i
 return f
c = with_counter(3)
c(0) # 1
c(0) # 2

Simple patterns

Empty lists, strings and None

Javascript

var array = [];
if (array.length === 0) {}
var s = "";
if (!s) {}
var n = 0;
if (!n) {}

Python

array = [];
if not array: pass
s = ""
if not s: pass
n = 0
if not n: pass

Max, min and sort

Javascript

var array = [1, 5, 3];
var n = 1;
var m = 2;
Math.max(n, m);
Math.min.apply(null, array);
array.sort()
array.sort(function(a,b) {return b - a}) // [5, 3, 1]

Python

array = [1, 5, 3]
n = 1
m = 2
max(n, m)
min(array)
array.sort() # or sorted(array) does not change original
array.sort(reverse=True)
array.sort(key=lambda x: -x)

Copy array

Javascript


Python

array = [1, 2, 3]
copy_array = array[:]
array2D = [[1, 2], [3, 4]]
copy_array2D = [ar[:] for ar in array2D]
# or
from copy import copy, deepcopy
copy_array = copy(array)
copy_array2D = deepcopy(array2D)

String formating and concat

Javascript

var name = "Alex";
var message = "My name is " + name + ". " + name + " - " + name.length + " letters.";
var array = [1, 3, 2];
var joined = array.join(";");

Python

name = "Alex"
message = "My name is {0}. {0} - {1} letters".format(name, len(name))
array = [1, 3, 2]
joined = ";".join(str(x) for x in array)