The Afterlife: Languages after JavaScript


jennz0r / @mybluewristband

Eventbrite

(Human) Wasteland

Developers, Developers

Way Back

  • Fortran
  • MATLAB
  • G-Code
  • Embedded C

2010 - 2012

2013

Jenn learns JavaScript.

And uses it.

2016

Jenn learns Python.

And is confused by it.

Think back...

{ } ;

Rules?!

A Quick History

Python

Python is a high-level, dynamic, interpreted, programming language. It emphasizes code readability, and its syntax expresses concepts in fewer lines of code than possible in languages such as C++ or Java.

- Wikipedia on Python

JavaScript

JavaScript is a high-level, dynamic, interpreted, and untyped, programming language.

- Wikipedia on JavaScript
Python
JavaScript
Paradigm
functional, imperative, object-oriented, procedural, reflective event-driven, functional, imperative, object-oriented (prototype), scripting
Appeared
20 February 1991 23 May 1995
Influences
ABC, ALGOL 68, C, C++, Dylan, Haskell, Icon, Java, Lisp, Modula‑3, Perl AWK, C, HyperTalk, Java, Lua, Scheme, Perl, Python, Self
Influenced
Boo, Cobra, CoffeeScript, D, F#, Falcon, Genie, Go, Groovy, JavaScript, Julia, Nim, Ruby, Swift ActionScript, AtScript, CoffeeScript, Dart, JScript .NET, LiveScript, Objective-J, Opa, Perl 6, QML, TypeScript

Let's start small.

Comments


// Inline Comment

/*
Multiple
Line
Comment
*/
							

# Inline Comment

'''
Multiple
Line
Comment
'''
							

Comments


''' '''
 /* */
  //
   #
						

Whitespace

It doesn't really matter!
- JavaScript

Whitespace

It does matter!
- Python

Whitespace

I'm confused.
- Jenn

Primitives

JavaScript
Python
Boolean
true, false True, False
Nothing
Null None
Empty Value
Undefined
Number
Number int, float, long, complex
Sequences
Array, tuple list, tuple, bytearray, buffer, xrange
Key/Value Store
Object Dictionary

Capitalization matters.

Primitives

What are all these things?

Numbers

int
Plain integers, 32 bits of precision, implemented using a long in C
float
Implemented using a double in C
long
Long integers, unlimited precision
complex
Have a real and imaginary part, each of which are floats

Sequences

List
Constructed with [ ]
Tuple
Constructed with ( ), immutable
bytearray
Mutable sequence of integers in the range 0 <= x < 256
buffer / memoryview
Replaced by memoryview, memoryview objects allow Python code to access the internal data of an object that supports the buffer protocol without copying
xrange
Immutable sequence which is commonly used for looping, always takes the same amount of memory, must be created using xrange() function.=

Tradeoffs

Faster development with more runtime errors versus slower development with fewer runtime errors.

Take your pick.

Concatenation

Type Coersion


// You can coerce an integer into string in JavaScript
var coerced = 1;
var concatenated = coerced + 'string';
						

# You can't coerce an integer into a string in Python
not_coerced = 1
concatenated = str(not_coerced) + 'string'
						

Functions

Functions & Conditionals


function drSeuss(catInTheHat, thing1, thing2) {
  if (catInTheHat == true &&
    thing1 == true &&
    thing2 == true) {
    console.log('is cray');
  } else if (catInTheHat != true) {
    console.log('boring');
  } else {
    console.log('so boring');
  }
}
							
def dr_seuss(cat_in_the_hat, thing1, thing2):
  if cat_in_the_hat == True and
    thing2 == True and
    thing2 == True:
    print 'is cray'
  elif cat_in_the_hat != True:
    print 'boring'
  else:
    print 'so boring'

							

Functions & Methods

Oh, there's a difference?
- Jenn

Functions & Methods (JavaScript)

The global Function object has no methods or properties of its own. However, it does inherit some methods and properties through the prototype chain from Function.prototype.

- MDN on functions

Methods in JavaScript

  • Function.prototype.apply()
  • Function.prototype.bind()
  • Function.prototype.call()
  • Function.prototype.isGenerator()
  • Function.prototype.toSource()
  • Function.prototype.toString()

Declared or "Created" Functions

vs.

Inherited or "Built In" Methods

Functions & Methods

In most respects functions and methods are identical except for two key differences:

  1. A method is implicitly passed the object on which it was called.
  2. A method is able to operate on data that is contained within the class.

Functions & Methods (Python)


def fish_and_chips():
  ingredients = ['fish', 'potatoes', 'batter']
  print 'cooking %s together' % (', '.join(ingredients))

# cooking fish, potatoes, batter

class Baking(object):
  def __init__(self, supplies):
    self.supplies = supplies

  def bakewell_tart(self):
    ingredients = ['almonds', 'raspberry', 'icing sugar']
    print self
    print 'baking %s' % (', '.join(ingredients))

# <__main__.Baking object at 0x10d6e0510>
# baking almonds, raspberry, icing sugar
						

Ternary



var doILikeChildren = wellBehaved ? 'yes' : 'no'
						

do_i_like_children = 'yes' if well_behaved else 'no'
						

A little bigger now.

Prototypes

Inheritance and the Prototype Chain

When it comes to inheritance, JavaScript only has one construct: objects. Each object has an internal link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. null, by definition, has no prototype, and acts as the final link in this prototype chain.

- MDN on Inheritance and the Prototype Chain
Image of a JavaScript prototype chain

from Beej's Bit Bucket

Prototypes vs. Classes


var Mammal = function() {
  this.neoCortex = true;
};

var Cat = function(name, years) {
  this.name = name;
  this.years = years;
};

Cat.prototype = new Mammal;
Cat.prototype.eat = function(food) {
  console.log('nom ' + food);
}

var fryCat = new Cat('Fry', 7);
fryCat.eat('steak');
							
class Mammal(object):
  neo_cortex = True

class Cat(Mammal):
  def __init__(self, name, years):
    self.name = name
    self.years = years
  def eat(self, food):
    print 'nom %s' % (food)

fry_cat = Cat('Fry', 7)

fry_cat.eat('steak')


							

Prototypes vs. Classes


var Mammal = function() {
  this.neoCortex = true;
}
							

class Mammal(object):
  neo_cortex = True
							

Prototypes vs. Classes


var Cat = function(name, years) {
  this.name = name;
  this.years = years;
};

Cat.prototype = new Mammal;
Cat.prototype.eat = function(food) {
  console.log('nom ' + food);
}
						

class Cat(Mammal):
  def __init__(self, name, years):
    self.name = name
    self.years = years

  def eat(self, food):
    print 'nom %s' % (food)

						

Prototypes vs. Classes


var fryCat = new Cat('Fry', 7);

fryCat.eat('steak');
						

fry_cat = Cat('Fry', 7)

fry_cat.eat('steak')
						

Scope

Python
JavaScript
Scope
Lexical Lexical
Namespace
Functions, Classes, Modules Functions, Classes, Modules
New Identifiers
Variables, Functions, Classes Variables, Functions

This vs. Self

This vs. Self

this is from JavaScript.

self is from Python.

Are they the same?

man shrugs holding 'free shrugs' sign

This vs. Self

this is a special keyword.

self is not a special keyword.

This vs. Self

this can refer to the global object or the containing object depending on the execution context.

self is just convention, is the explicit first argument of a function, and refers to the instance.

MDN


(function() {

  function f3() {
    return this;
  }
  f3.call(this) === window; // global object

  function f4() {
    this.herp = "derp";
  }

  function Thing(){
    this.thisIsEasyToUnderstand = "just kidding";
    f4.call(this);
  }
  var thing = new Thing();
  // thing = { thisIsEasyToUnderstand : "just kidding", herp: "derp" };

})();
						

Window.self


function foo() {
  console.log(
    window.self === window, // is self window?
    window.self === this,   // is self this?
    this === window         // is this window?
  );
}

foo(); // true true true
						

So this could be self if you're in the global scope!

This vs. Self

Confusing?

Yes.

Hoisting

Hoisting


var boba = 'passion green tea';
console.log(boba);

function jennsOrder() {
  // Variable declaration is hoisted.
  // As if var boba; was here.
  console.log(boba);
  var boba = 'mango green milk tea';
  console.log(boba);
}

jennsOrder();

// 'passion green tea'
//  undefined
// 'mango green milk tea'
						

Hoisting


def jenns_order:
  print boba
  boba = 'mango green milk tea'

# This is not possible because Python does not allow
# variables to be unassigned and hoisting does not exist
# in Python.
						
*Boba is also known as bubble tea, pearl milk tea, boba milk tea, and boba juice.

ES6!

ECMAScript 6

A new standard released in 2015 by Ecma International.

Prior to that, JavaScript hadn't released a fully new version since 2009.

Ecma International

vs.

Python Software Foundation

Block Scope

Moar confusion

Block Scope

With the addition of const and let, we now have block scope in JavaScript.


function simpleExample(value) {
  if (value) {
    var varValue = value;
    let letValue = value;

    console.log(varValue, letValue); // value value
  }

  // varValue is available even though it was defined
  // in if-block because it was "hoisted" to function scope
  console.log(varValue); // value

  // letValue is a ReferenceError because it
  // was defined within the if-block
  console.log(letValue); // Uncaught ReferenceError: letValue is not defined
}
						
Code adapted from BenMVP
Python
JavaScript
Scope
Lexical Lexical
Namespace
Functions, Classes, Modules Functions, Classes, Modules, Blocks
New Identifiers
Variables, Functions, Classes Variables, Functions

Template Literals

String literals allowing embedded expressions. They were called "template strings" in prior editions of the ES2015 specification.

Template Literals


let exclamation = 'Whoa!',
    sentence = `They're really similar to Python.`;

console.log(`Template Literals: ${exclamation} ${sentence}`);

// Template Literals: Whoa! They're really similar to Python.
						

Template Literals


print '.format(): {} {}'.format('Yup.', 'Quite!')

# .format(): Yup. Quite!
						

Template Literals


let exclamation = 'Whoa!',
    sentence = `They're really similar to Python.`;

console.log(`Template Literals: ${exclamation} ${sentence}`);

// Template Literals: Whoa! They're really similar to Python.
						

print '.format(): {} {}'.format('Yup.', 'Quite!')

# .format(): Yup. Quite!
						

Default Parameters

Default Parameters


function nom(food="ice cream") {
  console.log(`Time to eat ${food}`);
}

nom(); // Time to eat ice cream
						
Pattern via Dorottya Porkolab

Default Parameters


def nom(food="ice cream"):
  print 'Time to eat {}'.format(food)

nom() # Time to eat ice cream
						

Default Parameters


function nom(food="ice cream") {
  console.log(`Time to eat ${food}`);
}

nom(); // Time to eat ice cream
						

def nom(food="ice cream"):
  print 'Time to eat {}'.format(food)

nom() # Time to eat ice cream
						

...Rest Parameters & *args

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

...Rest Parameters & *args


function joke(question, ...phrases) {
  console.log(question);
  for (let i = 0; i < phrases.length; i++) {
    console.log(phrases[i]);
  }
}

let es6Joke = "Why does JS single out one parameter?"
joke(es6Joke, "Because it doesn't", 'really like', 'all the REST of them!');

// Why does JS single out one parameter?
// Because it doesn't
// really like
// all the REST of them!
						

...Rest Parameters & *args


def pirate_joke(question, *args):
  print question
  for arg in args:
    print arg

python_joke = "What's a Pyrate's favorite parameter?"

pirate_joke(python_joke, "*args!", "*arrgs!", "*arrrgs!")

# What's a Pyrate's favorite parameter?
# *args!
# *arrgs!
# *arrrgs!
						

Classes

Syntactic sugar

"Classes" vs. Classes


class Mammal {
  constructor() {
    this.neocortex = true;
  }
}

class Cat extends Mammal {
  constructor(name, years) {
    super();
    this.name = name;
    this.years = years;
  }

  eat(food) {
    console.log('nom ' + food);
  }
}

let fryCat = new Cat('Fry', 7);
fryCat.eat('steak');
							
class Mammal(object):
  neo_cortex = True




class Cat(Mammal):
  def __init__(self, name, years):
    self.name = name
    self.years = years

  def eat(food):
    print 'nom %s' % (food)




fry_cat = Cat('Fry', 7)
fry_cat.eat('steak')

Conclusion

What I Learned

JavaScript

Free for all... kinda.

Python

Some rules... can be good!

Thank you!


jennz0r / @mybluewristband