JavaScript and Python comparison

When programming in several languages It is easy to mistake their methods. I provide here a comparison to draw a distinction between these two languages.


results
            

# this is Python
            

// this is JavaScript
            

some basics









Hello World!




10

3.141592
            

# single line comment
""" multiline
string or
comment
"""

# console output
print('Hello World!')


# naming conventions
this_is_a_variable = 10
>>> print(this_is_a_variable)
THIS_IS_A_CONSTANT = 3.141592
>>> print(THIS_IS_A_CONSTANT)

def this_is_a_function(argument1):
    # do something
    pass


class ThisIsAClass:
    # do something
    pass
            

// single line comment
/* multiline
comment */
`multiline
string`

// console output
console.log('Hello World!');


// naming conventions
let thisIsAVariable = 10
>>> console.log(thisIsAVariable);
const thisIsAConstant = 3.141592
>>> console.log(thisIsAConstant);

function thisIsAFunction(argument1) {
    // do something
}

class ThisIsAClass {
    constructor() { }
    // do something
}
            

numbers




6

5
7
3
2

25
25
5.0
5.0

10
2.5
2
2


2
2 (but JS = 3)
-2

2
3
-3
-2


0
1
(5, 0)




5
8
1
19
3.8
            

num = 5
num += 1
>>> print(num)
num -= 1
>>> print(num)
>>> print(5 + 2)
>>> print(5 - 2)
>>> print(abs(-2))

>>> print(5 ** 2)
>>> print(pow(5, 2))
>>> print(25 ** (1/2))
>>> print(pow(25, 1/2))

>>> print(5 * 2)
>>> print(5 / 2)
>>> print(5 // 2)
>>> print(int(5 / 2))

import math
>>> print(math.trunc(2.5))
>>> print(round(2.5))
>>> print(round(-2.5))

>>> print(math.floor(2.5))
>>> print(math.ceil(2.5))
>>> print(math.floor(-2.5))
>>> print(math.ceil(-2.5))

# remainder
>>> print(8 % 2)
>>> print(9 % 2)
>>> print(divmod(10, 2))


list_sample = [1, 7, 2, 8, 1]
# arithmetic aggregates
>>> print(len(list_sample))
>>> print(max(list_sample))
>>> print(min(list_sample))
>>> print(sum(list_sample))
>>> print(sum(list_sample) / len(list_sample))
            

let num = 5;
num++;
>>> console.log(num);
num--;
>>> console.log(num);
>>> console.log(5 + 2);
>>> console.log(5 - 2);
>>> console.log(Math.abs(-2));

>>> console.log(5 ** 2);
>>> console.log(Math.pow(5, 2));
>>> console.log(25 ** (1/2));
>>> console.log(Math.pow(25, 1/2));

>>> console.log(5 * 2);
>>> console.log(5 / 2);

>>> console.log(Math.trunc(5 / 2));


>>> console.log(Math.trunc(2.5));
>>> console.log(Math.round(2.5));
>>> console.log(Math.round(-2.5));

>>> console.log(Math.floor(2.5));
>>> console.log(Math.ceil(2.5));
>>> console.log(Math.floor(-2.5));
>>> console.log(Math.ceil(-2.5));

// remainder
>>> console.log(8 % 2);
>>> console.log(9 % 2);



let list_sample = [1, 7, 2, 8, 1];
// arithmetic aggregates
>>> console.log(list_sample.length);
>>> console.log(Math.max(...list_sample));
>>> console.log(Math.min(...list_sample));
>>> console.log(list_sample.reduce((a, b) => a + b, 0));
>>> console.log(list_sample.reduce((a, b) => a + b, 0) / list_sample.length);
            

strings




"

True
False
True
3

1
5
-1
-1
ValueError
ValueError



False
True
**************************************************
*                                                *




Mars has 2 moons




text case
TEXT CASE
TExT CaSE
Text case
Text Case

True
True
True


**************************************************
Text justification                                
                                Text justification
                Text justification                


>Text trim<
>Text trim  <
>  Text trim<
            

str = ''
str = ""
print('"')
str = 'banana'
>>> print('a' in str)
>>> print(str.startswith('a'))
>>> print(str.endswith('a'))
>>> print(str.count('a'))

>>> print(str.find('a'))
>>> print(str.rfind('a'))
>>> print(str.find('e'))
>>> print(str.rfind('e'))
>>> print(str.index('e'))
>>> print(str.rindex('e'))


# operators
>>> print('begin' > 'end')
>>> print('begin' < 'end')
>>> print('*' * 50)
>>> print('*' + ' ' * 48 + '*')

planet = 'Mars'
moons = ['Deimos', 'Phobos']
# format string
>>> print('%s has %d moon%s' % ('Mars', 2, 's'))


# case
str = 'teXt cAse'
>>> print(str.lower())
>>> print(str.upper())
>>> print(str.swapcase())
>>> print(str.capitalize())
>>> print(str.title())

>>> print(str.lower().islower())
>>> print(str.upper().isupper())
>>> print(str.title().istitle())

str = 'Text justification'
>>> print('*' * 50)
>>> print(str.ljust(50))
>>> print(str.rjust(50))
>>> print(str.center(50))

str = '  Text trim  '
>>> print('>' + str.strip() + '<')
>>> print('>' + str.lstrip() + '<')
>>> print('>' + str.rstrip() + '<')
            

let str = '';
str = "";
console.log('"');
str = 'banana';
>>> console.log(str.includes('a'));
>>> console.log(str.startsWith('a'));
>>> console.log(str.endsWith('a'));
>>> console.log((str.match(/a/g)||[]).length);

>>> console.log(str.indexOf('a'));
>>> console.log(str.lastIndexOf('a'));
>>> console.log(str.indexOf('e'));
>>> console.log(str.lastIndexOf('e'));




// operators
>>> console.log('begin' > 'end');
>>> console.log('begin' < 'end');
>>> console.log('*'.repeat(50));
>>> console.log('*' + ' '.repeat(48) + '*');

let planet = 'Mars'
let moons = ['Deimos', 'Phobos']
// template string
>>> console.log(`${planet} has ${moons.length} moon${moons.length > 1 ? 's': ''}`);


// case
str = 'teXt cAse';
>>> console.log(str.toLowerCase());
>>> console.log(str.toUpperCase());
// https://stackoverflow.com/questions/24471618/swap-case-on-javascript
>>> console.log(str.charAt(0).toUpperCase() + str.slice(1).toLowerCase());
// https://stackoverflow.com/questions/196972/convert-string-to-title-case-with-javascript

>>> console.log(str.toLowerCase() == str.toLowerCase());
>>> console.log(str.toUpperCase() == str.toUpperCase());


str = 'Text justification';
>>> console.log('*'.repeat(50));




str = '  Text trim  ';
>>> console.log('>' + str.trim() + '<');
>>> console.log('>' + str.trimStart() + '<');
>>> console.log('>' + str.trimEnd() + '<');
            

strings and lists



['E', 'a', 'r', 't', 'h']

Moon, Earth, Sun, Milky Way







['Cambridge University Press', 'University Printing House', 'Shaftesbury Road', 'Cambridge', 'CB2 8BS', 'United Kingdom']
['Cambridge University Press', 'University Printing House', 'Shaftesbury Road', 'Cambridge', 'CB2 8BS', 'United Kingdom']

York University Press
University Printing House
Shaftesbury Road
York
CB2 8BS
United Kingdom

York University Press
University Printing House
Shaftesbury Road
Cambridge
CB2 8BS
United Kingdom
            

str = 'Earth'
>>> print(list(str))

>>> print(', '.join(['Moon', 'Earth', 'Sun', 'Milky Way']))

address = """Cambridge University Press
University Printing House
Shaftesbury Road
Cambridge
CB2 8BS
United Kingdom"""
>>> print(address.splitlines())
>>> print(address.split('\n'))

>>> print(address.replace('Cambridge', 'York'))
            

let str = 'Earth';
>>> console.log([...str]); // Spread syntax

>>> console.log(['Moon', 'Earth', 'Sun', 'Milky Way'].join(', '));

const address = `Cambridge University Press
University Printing House
Shaftesbury Road
Cambridge
CB2 8BS
United Kingdom`;

>>> console.log(address.split('\n'));

>>> console.log(address.replace(/Cambridge/g, 'York')); // replaces all instances, uses regex






>>> console.log(address.replace('Cambridge', 'York')); // replaces only the first instance
            

Data structures 1/2: objects and lists











dict_keys(['moon', 'planet', 'star', 'galaxy'])
dict_values(['Moon', 'Earth', 'Sun', 'Milky Way'])
dict_items([('moon', 'Moon'), ('planet', 'Earth'), ('star', 'Sun'), ('galaxy', 'Milky Way')])
Moon, Earth, Sun, Milky Way


Earth


{'moon': 'Moon', 'planet': 'Earth', 'star': 'Sun', 'galaxy': 'Milky Way', 'supercluster': 'Laniakea'}

True
Laniakea


{'moon': 'Moon', 'planet': 'Earth', 'star': 'Sun', 'galaxy': 'Milky Way'}
somewhere over the rainbow




(1, 7, 2, 8, 1)

{8, 1, 2, 7}



[1, 7, 2, 8, 1, 10]
10
[1, 7, 2, 8, 1]


[10, 1, 7, 2, 8, 1]
10
[1, 7, 2, 8, 1]


[10, 1, 7, 2, 8, 1]

[1, 7, 2, 8, 1]


[1, 7, 'third item', 2, 8, 1]

[1, 7, 'third item', 2, 8, 1, [1, 2, 3]]

[1, 7, 'third item', 2, 8, 1, [1, 2, 3], 1, 2, 3]




['Moon', 'Earth', 'Sun', 'Milky Way']
Earth

['E', 'a', 'r', 't', 'h']
E
h

Ear
Ear
Erh
htraE




True




['Moon', 'Earth', 'Sun']
            

object = {}
list_sample = []
tuple_sample = ()

# OBJECTS
object = {'moon': 'Moon',
          'planet': 'Earth',
          'star': 'Sun',
          'galaxy': 'Milky Way'}
>>> print(object.keys())
>>> print(object.values())
>>> print(object.items())
>>> print(', '.join(object.values()))

# retrieve value
>>> print(object['planet'])
# create item or change value
object['supercluster'] = 'Laniakea'
>>> print(object)
# check item existence
>>> print('supercluster' in object)
>>> print(object.get('supercluster', 'somewhere over the rainbow'))
# remove item
del object['supercluster']
>>> print(object)
>>> print(object.get('supercluster', 'somewhere over the rainbow'))


# LISTS
list_sample = [1, 7, 2, 8, 1]
>>> print(tuple(list_sample))
set_sample = set(list_sample)
>>> print(set_sample)

# create/remove items
list_sample.append(10)
>>> print(list_sample)
>>> print(list_sample.pop())
>>> print(list_sample)

list_sample.insert(0, 10);
>>> print(list_sample)
>>> print(list_sample.pop(0))
>>> print(list_sample)

list_sample[:0] = [10]  # use a zero-width slice
>>> print(list_sample)
del list_sample[:1]
>>> print(list_sample)

list_sample.insert(2, 'third item')
>>> print(list_sample)
list_sample.append([1, 2, 3])
>>> print(list_sample)
list_sample.extend([1, 2, 3])
>>> print(list_sample)


# retrieve value
list_sample = ['Moon', 'Earth', 'Sun', 'Milky Way']
>>> print(list_sample)
>>> print(list_sample[1])
str = 'Earth'
>>> print(list(str))
>>> print(str[0])
>>> print(str[-1])
# slice
>>> print(str[0:3])
>>> print(str[0:-2])
>>> print(str[::2])
>>> print(str[::-1])

# create item or change value
list_sample.append('Laniakea')
# check item existence
>>> print('Laniakea' in list_sample)
# remove item by key
del list_sample[-1]
# remove items by value
list_sample.remove('Milky Way')
>>> print(list_sample)
            

let object = {};
let list_sample = [];
// JavaScript has no native tuple implementation

// OBJECTS
object = {'moon': 'Moon',
        'planet': 'Earth',
        'star': 'Sun',
        'galaxy': 'Milky Way'};
>>> console.log(Object.keys(object));
>>> console.log(Object.values(object));
>>> console.log(Object.entries(object));
>>> console.log(Object.values(object).join(', '));

// retrieve value
>>> console.log(object['planet']);
// create item or change value
object['supercluster'] = 'Laniakea';
>>> console.log(object);
// check item existence
>>> console.log('supercluster' in object);
>>> console.log('supercluster' in object ? object['supercluster'] : 'somewhere over the rainbow');
// remove item
delete object['supercluster'];
>>> console.log(object);
>>> console.log('supercluster' in object ? object['supercluster'] : 'somewhere over the rainbow');


// LISTS
list_sample = [1, 7, 2, 8, 1];

let set_sample = new Set(list_sample);
>>> console.log(set_sample);

// create/remove items
list_sample.push(10);
>>> console.log(list_sample);
>>> console.log(list_sample.pop());
>>> console.log(list_sample);

list_sample.unshift(10);
>>> console.log(list_sample);
>>> console.log(list_sample.shift());
>>> console.log(list_sample);

list_sample.splice( 0, 0, 10 );
>>> console.log(list_sample);
list_sample.splice(0, 1);
>>> console.log(list_sample);

list_sample.splice(2, 0, 'third item');
>>> console.log(list_sample);
list_sample.push([1, 2, 3]);
>>> console.log(list_sample);
list_sample.push(...[1, 2, 3]);
>>> console.log(list_sample);


// retrieve value
list_sample = ['Moon', 'Earth', 'Sun', 'Milky Way'];
>>> console.log(list_sample);
>>> console.log(list_sample[1]);
let str = 'Earth';
>>> console.log([...str]);
>>> console.log(str[0]);
>>> console.log(str.slice(-1));
// slice
>>> console.log(str.slice(0, 3));
>>> console.log(str.slice(0, -2));



// create item or change value
list_sample.push('Laniakea');
// check item existence
>>> console.log(list_sample.includes('Laniakea'));
// remove item by key
list_sample.splice(-1, 1);
// remove items by value ????????????????????????
list_sample = list_sample.filter(item => item != 'Milky Way');
>>> console.log(list_sample);
            

Data structures 2/2: tuples and sets





1 9

9 1




{1, 2, 5, 7}

{1, 2, 3, 5, 7}
True

{1, 2, 3, 5, 7}

{1, 3, 5, 7}

{1, 3, 4, 5, 7}



{1, 2, 4, 5, 6, 7}
{2}
{1, 5, 7}
            

# TUPLES
tuple_sample = 1, 9
x, y = tuple_sample
>>> print(x, y)
x, y = y, x
>>> print(x, y)


# SETS
set_sample = {1, 7, 2, 5, 1}
>>> print(set_sample)
set_sample.add(3)
>>> print(set_sample)
>>> print(2 in set_sample);
set_sample.add(2)
>>> print(set_sample)
set_sample.remove(2)
>>> print(set_sample)
set_sample.update([4, 5])
>>> print(set_sample)

# intersection, union and difference operations
set_sample2 = {2, 4, 6}
>>> print(set_sample | set_sample2)
>>> print(set_sample & set_sample2)
>>> print(set_sample - set_sample2)
            

// TUPLES JavaScript has no native tuple implementation
const tuple_sample = [1, 9];
let [x, y] = tuple_sample;
>>> console.log(x, y);
[x, y] = [y, x];
>>> console.log(x, y);


// SETS
let set_sample = new Set([1, 7, 2, 5, 1]);
>>> console.log(set_sample);
set_sample.add(3);
>>> console.log(set_sample);
>>> console.log(set_sample.has(2));
set_sample.add(2);
>>> console.log(set_sample);
set_sample.delete(2);
>>> console.log(set_sample);
set_sample.add(...[4, 5]);
>>> console.log(set_sample);

// there are no native intersection, union or difference operations
let set_sample2 = new Set([2, 4, 6]);
>>> console.log(new Set([...set_sample, ...set_sample2]));
>>> console.log(new Set([...set_sample].filter(x => set_sample2.has(x))));
>>> console.log(new Set([...set_sample].filter(x => !set_sample2.has(x))));
            

map, filter and reduce lists






[1, 49, 4, 64, 1]
['MOON', 'PLANET', 'STAR', 'GALAXY', 'MOON', 'EARTH', 'SUN', 'MILKY WAY']


[2, 8]
['Moon', 'Earth', 'Sun', 'Milky Way']



19
112
            

number_list = [1, 7, 2, 8, 1]
string_list = ['moon', 'planet', 'star', 'galaxy', 'Moon', 'Earth', 'Sun', 'Milky Way']

# Map
>>> print([num ** 2 for num in number_list])  # square numbers
>>> print([i.upper() for i in string_list])  # words to uppercase

# Filter
>>> print([num for num in number_list if num % 2 == 0])  # a number is divisible by another if the remainder is 0; an even number by 2
>>> print([i for i in string_list if i[0].isupper()])  # names begin with upper case

# Reduce
from functools import reduce
>>> print(reduce(lambda x, y: x + y, number_list, 0))  # equivalent to sum(number_list)
>>> print(reduce(lambda x, y: x * y, number_list, 1))  # equivalent to sum(number_list)
            

const number_list = [1, 7, 2, 8, 1]
const string_list = ['moon', 'planet', 'star', 'galaxy', 'Moon', 'Earth', 'Sun', 'Milky Way']

// Map
>>> console.log(number_list.map(num => Math.pow(num, 2)));
>>> console.log(string_list.map(item => item.toUpperCase()));

// Filter
>>> console.log(number_list.filter(num => num % 2 == 0));
>>> console.log(string_list.filter(item => item[0] == item[0].toUpperCase()));

// Reduce

>>> console.log(number_list.reduce((sum, item) => sum + item, 0));
>>> console.log(number_list.reduce((sum, item) => sum * item, 1));
            

functions






False


False









False



False





True
True
            

def divisible(dividend, divisor):
	return dividend % divisor == 0


>>> print(divisible(25, 4))








# lambda es una función anónima que admite en su cuerpo una sola expresión
divisible = lambda n, d: n % d == 0


>>> print(divisible(25, 4))






# partial allows us to create a new function that fills some of its arguments
from functools import partial
isEven = partial(divisible, d=2)
>>> print(isEven(25))
>>> print(isEven(4))
            

// function declaration
function isDivisible1(dividend, divisor) {
    return dividend % divisor === 0;
}
>>> console.log(isDivisible1(25, 4));

// anonymous function
>>> console.log(
    (function (dividend, divisor) {
        return dividend % divisor === 0;
    })(25, 4)
);

// function expression: starts with "const"
const isDivisible2 = function (dividend, divisor) {
    return dividend % divisor === 0;
};
>>> console.log(isDivisible2(25, 4));

// arrow function
const isDivisible3 = (dividend, divisor) => dividend % divisor === 0;
>>> console.log(isDivisible3(25, 4));


function isEven(dividend) {
    return isDivisible3(dividend, 2);
}
>>> console.log(isEven(25));
>>> console.log(isEven(4));
            

conditional sentences






25 it's an odd number







25 it's an odd number



25 it's an odd number

4 it's an even number
            

num = 25
if num % 2 == 0:
	print(str(num) + " it's an even number")
else:
	print(str(num) + " it's an odd number")


# we can implement a function
isEven = lambda n: n % 2 == 0
if isEven(num):
	print(str(num) + " it's an even number")
else:
	print(str(num) + " it's an odd number")


# ternary conditional operator
>>> print("%d it's an %s number" % (num, 'even' if isEven(num) else 'odd'))
num = 4
>>> print("%d it's an %s number" % (num, 'even' if isEven(num) else 'odd'))
            

let num = 25;
if (num % 2 == 0) {
    console.log(String(num) + " it's an even number");
} else {
    console.log(String(num) + " it's an odd number");
}

// we can implement a function
const isEven = (n) => n % 2 === 0;
if (isEven(num)) {
    console.log(String(num) + " it's an even number");
} else {
    console.log(String(num) + " it's an odd number");
}

// ternary conditional operator
>>> console.log(`${num} it's an ${isEven(num) ? 'even' : 'odd'} number`);
num = 4;
>>> console.log(`${num} it's an ${isEven(num) ? 'even' : 'odd'} number`);
            

loops


# same results
1
3
5
7
9
            

# All examples below retrieve even numbers from 1 to 10
count = 0
while count < 10:
	count += 1
	if count % 2 != 0:  # omit even numbers
		print(count)

# break and continue sample. Requires break because the loop never ends
count = 0
while True:
	count += 1
	if count > 10:
		break
	if count % 2 == 0:  # omit even numbers
		continue
	print(count)



# for loop
for count in range(1, 10):
	if count % 2 != 0:
		print(count)

# list comprehension
[print(count) for count in range(1, 10) if count % 2 != 0]
            

// All examples below retrieve even numbers from 1 to 10
let count = 0;
while (count < 10) {
    count++;
    if (count % 2 != 0) console.log(count); // omit even numbers;
}

// break and continue sample. Requires break because the loop never ends
count = 0;
while (true) {
    count++;
    if (count > 10) {
        break;
    } if (count % 2 == 0) { // omit even numbers;
        continue;
    }
    console.log(count);
}

// for loop
for (var count = 0; count <= 10; count++) {
    if (count % 2 != 0) console.log(count);
}




// forEach;
[...Array(10).keys()].forEach(function (count) {
    if (count % 2 != 0) console.log(count);
});

// simplest
for (var count = 1; count <= 10; count += 2) {
    console.log(count);
}