Inside the Head of PyDanny

Hi, I'm Daniel Roy Greenfeld, and welcome to my blog. I write about Python, Django, and much more.

One of the things I noticed a long time ago with JavaScript is that when you create objects you can define keys outside of strings:

> var o = {city: "San Francisco"}

In JavaScript, this is valid. In Python, you'll get a NameError:

>>> o = {city: "San Francisco"}
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'city' is not defined

Normally this isn't too big of an issue, except when you want to use JavaScript to create object keys based off of values in a variable. Which means that while this code works fine in Python...

>>> region_name = 'state'
>>> o = {region_name: "Californa", "city": "San Francisco"}
>>> o["state"]
'Californa' fails in JavaScript:

> var region_name = 'state'
> var o = {region_name: "Californa", "city": "San Francisco"}
> o["state"]
> o["region_name"]

What this means is that if you want to define object keys dynamically in JavaScript, you need to add an extra line(s) of code:

> var region_name = "state""
> var o = {"city": "San Francisco"}
> o[region_name] = "California" // Add dynamic key here
> o["state"]


  • Python is consistent in how it deals with named objects. If you haven't named something, Python throws the NameError.
  • JavaScript seems to send out an undefined unless you are defining an object.

Published: 2012-08-19 3:00

Tags: python javascript vs


If you read this far, you might want to follow me on twitter or github and subscribe via email below (I'll email you new articles when I publish them).



Content Copyright © 2012-2018 Daniel Greenfeld. Proudly harnessed by Mountain, powered by Flask, and rendered by Frozen Flask, all of which take great advantage of Python.