
Guil Hernandez
June 26, 2020
-
9 min read
🚀 We’ve updated this blog for 2025! Check out the new version here:
Programming in a new language can feel unfamiliar, intimidating, and tricky to navigate at first. There are new rules, syntax, and nuances to learn.
I recently started learningPython again after years of programming inJavaScript. After diving back in in 2020, I noticed that, as with many programming languages, Python and JavaScript share a lot of the same basic features, data structures, and design patterns.
If you’re familiar with JavaScript and wondering if you should learn Python, your knowledge of JavaScript can help you quickly get up to speed. This article covers some of the essential concepts, mechanics, and features of the two languages. I’ll provide just enough of the basics to pique your curiosity and help kick off your polyglot learning journey.
Contents
JavaScript and Python areinterpreted programming languages, meaning their runtime environments use an interpreter (or engine) that parses and executes code one statement at a time.
The two languages are also “object-based” — everything is (or can be treated as) an object: strings, numbers, data structures, functions, etc.
First up, JavaScript and Python have similar built-in data types. For example, both use numeric data types (integers and floats), strings and Booleans.
// JavaScript data types const pi = 3.14; const age = 31; const greeting = "good morning";const isAdmin = true;
# Python data types pi = 3.14 age = 13 greeting = "good morning" is_admin = True
Python and JavaScript are “dynamically typed” languages, which means you do not have to set the type of a variable explicitly. The data type is set when you assign a value to a variable.
In JavaScript, you use thetypeof operator to verify the data type of a variable. Python provides a similar built-in function,type().
// JavaScript const greeting = "good morning"; typeof greeting; // "string"
# Python pi = 3.14 type(pi) # float
You can convert from one type to another, like a string to a number, in Python with theint() andfloat() functions:
# Python input = input('Enter a number: ') #'2'# convert string to int int(input) # 2JavaScript includes the methodsparseInt() andparseFloat() for the same purpose:
// JavaScript const input = prompt('Enter a number:'); // '4' parseInt(input); // 4To convert cased characters in a string from uppercase to lowercase (and the reverse), use Python’supper() andlower() functions:
# Python user_name = input('What is your name? ') # GUIL user_name.lower() # 'guil'greeting = "good evening" greeting.upper() # 'GOOD EVENING'JavaScript supplies thetoUpperCase() andtoLowerCase() methods to convert strings:
// JavaScript const greeting = "good evening"; const userName = prompt("What is your name?"); // "gUiL"greeting.toUpperCase(); // "GOOD EVENING" userName.toLowerCase(); // "guil"Template literals in JavaScript let you replace${} placeholders with values inside of a string literal. This process is called string interpolation:
// JavaScript const greeting = "Good evening"; const name = "Guil"; console.log(`${greeting}, ${name}!`); // Good evening, Guil!The Python stringformat() method inserts values into a template string containing{} replacement fields. You pass the method the values to interpolate. For example:
# Python strings greeting = "Good evening" name = "Guil" print( "{}, {}!".format(greeting, name) ) # Good evening, Guil!Each set of curly braces gets replaced with the values passed toformat() in sequential order.
Python’s formatted string literal (f-String) offers a more concise syntax to accomplish the same. It looks like a regular string that’s prepended by the characterf, and you include the value to interpolate directly inside the string.
# Python strings greeting = "Good evening" name = "Guil" print(f"{greeting}, {name}!") # Good evening, Guil!Learn more built-in string methods in our Python Basics course.
JavaScript and Python give you comparable structures to store and organize your data.
Like a JavaScript array, a Python list stores a collection of values in a single container. The values can be different data types like strings, integers, Booleans, etc.
# Python list students = ['Lee', 'Toni', 'Marie', 'Agata'] # return length of list len(students) # 4 students[2] # 'Marie'
// JavaScript array const students = ['Lee', 'Toni', 'Marie', 'Agata']; students.length; // 4 students[0]; // Lee
Notice how both languages have similar ways of returning the length of a list and retrieving a value by index.
Since arrays and lists are considered objects in their respective language, there are various properties and methods you can use on them. For example, a common way to add elements to the end of an array in JavaScript is with thepush() method:
// JavaScript const instruments = ['piano', 'drums', 'trumpet']; instruments.push('guitar'); // ['piano', 'drums', 'trumpet', 'guitar']You add an item to the end of a Python list with theappend() method:
# Python instruments = ['piano', 'drums', 'trumpet'] instruments.append('guitar') # ['piano', 'drums', 'trumpet', 'guitar']JavaScript arrays and Python lists have apop() method for removing and returning items. Callingpop() on a JavaScript array removes the last element:
// JavaScript arrays const instruments = ['piano', 'drums', 'trumpet']; instruments.pop(); // "trumpet"
While JavaScript’spop() method does not accept arguments, Python’s does! For instance, passpop() the index of the item you want to remove:
# Python lists instruments = ['piano', 'drums', 'trumpet'] instruments.pop(1) # 'drums'
In JavaScript, you use the spread operator (...) to copy, combine and manipulate arrays:
// JavaScript arrays const studentsA = ['Lee', 'Toni', 'Marie']; const studentsB = ['Meg', 'Jesse', 'Anwar'];const students = [...studentsA, ...studentsB]; // ['Lee', 'Toni', 'Marie', 'Meg', 'Jesse', 'Anwar']
In a similar way, you can “unpack” items from one Python list into another using an asterisk (*):
# Python lists students_a = ['Lee', 'Toni', 'Marie'] students_b = ['Meg', 'Jesse', 'Anwar']students = [*students_a, *students_b] # ['Lee', 'Toni', 'Marie', 'Meg', 'Jesse', 'Anwar']
Both create a copy of a list or array, preserving the original values.
One handy aspect of the JavaScript spread operator is that you can pass arrays as arguments to functions.
// JavaScript const numbers = [10, 20, 30, 40]; Math.max(...numbers); // 40
Likewise, you have the ability to unpack items in a Python list for function calls:
# Python numbers = [1, 10] list(range(*numbers)) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
Both expand an array or list into separate arguments.
If you’re familiar with JavaScript objects, you’ll recognize Python dictionaries. You write both using curly brackets holding related data in the form of key/value pairs.
// JavaScript object const pet = { name: 'Joey', type: 'Dog', breed: 'Australian Shepherd', age: 8 };# Python dictionary pet = { 'name': 'Joey', 'type': 'Dog', 'breed': 'Australian Shepherd', 'age': 8 }Lists and dictionaries, like arrays and objects aremutable, which means that you can change the data inside them without changing their identity. Once you create an object, its type and identity (or the address in memory it’s pointing to) does not change.
JavaScript’s spread operator copies key/value pairs from one object literal to another. It’s comparable to the double asterisks (**) operator in Python, which copies and merges dictionaries:
// JavaScript objects const name = { firstName: 'Reggie', lastName: 'Williams' };const developer = { ...name, // place the 'name' key/values here title: 'Software developer', skills: ['JavaScript', 'HTML', 'CSS'] };# Python dictionaries name = { 'firstName': 'Reggie', 'lastName': 'Williams' }developer = { **name, # place the 'name' key/values here 'title': 'Software developer', 'skills': ['JavaScript', 'HTML', 'CSS'] }Both languages take full advantage of functions for code reuse. Python uses thedef keyword compared tofunction in JavaScript.
# Python function def add(a, b=10): val = a + b return val
// JavaScript function function add(a, b = 10) { const val = a + b; return val; }Notice how both use thereturn keyword to return a value, and you’re able to specify default parameters in each function definition.
Arrow functions in JavaScript offer a concise syntax for creating functions. More so, if your function body is only one line of code, you can omit thereturn keyword and place everything on one line:
// JavaScript arrow function const add = (a, b) => a + b;
In Python, thelambda keyword provides syntactic sugar for defining functions as single-line expressions:
# Python lambda add = lambda a,b : a + b
These single-line functions are common when you want to pass an anonymous function as an argument to another (higher-order) function. For example, they’re used with the built-in Python and JavaScript functionsmap(),filter(), andreduce().
// JavaScript arrow function const states = ['ca', 'fl', 'hi', 'ny']; states.map( s => s.toUpperCase() ); // ["CA", "FL", "HI", "NY"]
# Python lambda states = ['ca', 'fl', 'hi', 'ny'] list( map(lambda s: s.upper(), states) ) # ['CA', 'FL', 'HI', 'NY']
Python’s flow control statements also look and work similarly to theif/else you know from #"">// JavaScript conditional let score = 4;if ( score === 5 ) { console.log("Gold Medal!"); } else if ( score >= 3 ) { console.log("Silver Medal"); } else if ( score >= 1 ) { console.log("Bronze Medal"); } else { console.log("No Medal :("); }
# Python conditional score = 5if score == 5: print("Gold Medal!") elif score >= 3: print("Silver Medal") elif score >= 1: print("Bronze Medal") else: print("No Medal :(")Like JavaScript’selse if clause, you can specify any number ofelif clauses, and the optionalelse clause should appear last.
Lastly, Python has awhile loop, which looks and works almost the same as its JavaScript counterpart:
# Python password = input("Enter the secret password: ") while password != 'sesame': password = input("Invalid password. Try again: ")// JavaScript let password = prompt("Enter the secret password:"); while (password !== 'sesame') { password = prompt("Invalid password. Try again: "); }Data types like strings, lists, and dictionaries are also iterable objects in Python; you use afor loop to iterate over them:
# Python for loop students = ['Lee', 'Toni', 'Marie', 'Jesse', 'Anwar'] for student in students: print(student)
// JavaScript for...of loop const students = ['Lee', 'Toni', 'Marie', 'Jesse', 'Anwar'] for (let student of students) { console.log(student); }You also use thebreak keyword in either to exit (or break out of) awhile andfor loop.
# Python scores = [50, 20, 30, 0, 10, 15, 35] for score in scores: print(f"Score: {score}"); if score == 0: print("You may not continue if you have a 0 score.") break// JavaScript while (true) { let response = prompt("Type 'exit' to make this stop."); if (response === 'exit') { break; } }These were some of the similarities I’ve discovered whileexploring the Python language. If there are more you’d like to share, feel free to keep it going in the comments.
You may have noticed that there are no curly braces for code blocks or keywords for variable declarations in Python vs. JavaScript. Python’s syntax is concise and a bit more prescribed than JavaScript. For example, Python requires specific indentation for code blocks, which are always preceded by a colon, making it easier to read and understand.
Expanding your programming toolset and identifying and applying programming concepts under a different context strengthens your programming skills and might help you solve problems in new, more efficient ways.
Happy learning!

GET STARTED NOW
Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you’ve been dreaming about.
Get StartedThank You so much for this detailed comparison, it was useful while choosing which “code” to choose! Great job!
As an experienced web designer and web development specialist, I like Python better compared to JavaScript because it’s easy to learn, and fast to implement. All JavaScript projects, I outsource to fellow web developers, so we work and make money, together.
You might also like other posts...

Career Advice
August 7, 2022
∙ 9 min read
Front-End vs. Back-End: The Complete Guide
If you're new to coding, you may be wondering what the difference is between front-end vs. back-end. Find your answers in our latest Treehouse blog.

Jason Gilmore

Learn
June 7, 2022
∙ 6 min read
Should I Learn HTML Before Python?
Starting your coding journey and wondering if you should learn HTML before Python? We've got you covered. Keep reading to learn the key differences in our latest blog.

Lindsey Rogerson

Learn
January 18, 2023
∙ 10 min read
How to Use the Browser Developer Tools Console
The developer console can help you debug your front-end web applications. Learn more about the browser developer tools in this quick and simple guide.
Matt West

Learn how to use JavaScript to add interactivity to websites.
Learn more