Learning Javascript as a Python Developer
Tags: python, javascript, beginners, programming
Published: 2023-04-26 10:35:48

My previous post [Learn Python as a Javascript developer](https://dev.to/kachiic/learn-python-as-a-javascript-developer-422j) was so popular I decided to write the same thing but reversed.

As previously stated, I'm a **`Javascript`** and **`Python`** fullstack developer and like most self-taught developers, I started by learning **`HTML`**, **`CSS`** and **`Javascript`** first.

When I learned **`Python`** it was pretty easy as it is less restrictive than javascript. Python is great for handling backend data and creating simple scripts like web-scrapers.

Python is commonly associated with data analysis and javascript with web development. However, the introduction of **`Node JS`** and the popularity of javascript amongst developers means you should probably learn it. Even just being able to read it would serve you well.

If you're nervous about learning **`Javascript`**, remember that **`Javascript`** is a high level programming language. This means it is around the same level of difficulty to learn as **`Python`**.

In this tutorial, I'll outline the main differences between the two coding languages.

## Set Up

If you're starting out, I recommend using a sandbox to test your code. [**`Run JS`**](https://runjs.app/) is a very useful tool as it logs

## Methods

The methods used in **`python`** and **`javascript`** are named differently.

Here are some examples of this:

In **`python`**:

```python
len("Hello world") # Length of a string
arr.append("new string") # Add new item to end of list
arr.sort() # Sort a list
```

In **`javascript`**:

```javascript
"Hello World".length; // Length of a string
arr.push("new string"); // Add new item to end of array
arr.sort((a, b) => a - b); // Sort an array
```

As you can see, the differences aren't huge and you of course don't need to remember all of them.

Here are some useful links for you to reference:

| Type               | Page                                                                                   |
| ------------------ | -------------------------------------------------------------------------------------- |
| Strings            | [Methods](https://www.w3schools.com/js/js_string_methods.asp)                          |
| List/Array         | [Methods](https://www.w3schools.com/jsref/jsref_obj_array.asp)                         |
| Build in Functions | [Keywords](https://www.tutorialspoint.com/javascript/javascript_builtin_functions.htm) |

## Output

When you want to print something in the console. Just change **`print`** to **`console.log`**!

In **`python`**:

```python
print("hello world")
```

In **`javascript`**:

```javascript
console.log("hello world");
```

## Comments

When leaving a comment or commenting something out change to **`#`** to **`//`**:

In **`python`**:

```python
"""python comment"""

# Multi
# Line
# Comment
```

In **`javascript`**:

```javascript
// javascript comment

/* multiline
javascript
comment */
```

## Variables

Variables is where the difference really begin to show. For those new to **`Javascript`**, it may take some time to adjust.

Here are the main differences.

- **`Javascript`** use **camel casing** and **`Python`** use **snake casing**.
- Cases for **`python`** , **`const`**, **`let`** and **`var`** for **`javascript`**.

In **`Python`**:

```python
my_example = "hello world" # basic variable
MY_EXAMPLE = "hello world" # Red flag to not change
```

In **`Javascript`**:

```javascript
// Any of these 3 can be used.
var myExample = "hello world";
let myExample = "hello world";
const myExample = "hello world";
```

Let's quickly break is down.

- **`var`** was used in all JavaScript code from 1995 to 2015, older browsers still only use var.
- The **`let`** and **`const`** keywords were added to JavaScript in 2015.

The general rule is declare variables with **`const`**, UNLESS you think the value of the variable will change - in that case use **`let`**.

Here is an example:

```javascript
let valOne = "hello javascript";
const valTwo = "This is javascript";

valOne = "hello world";
valTwo = "This is now new";

// valOne is now "hello world"
// valTwo is still "This is javascript"
```

The second value remains because it was declared using **`const`**

## List and Arrays

Lists in **`Javascript`** are referred to as **arrays**, similar to variables it must be declared with a **`const`** or **let**

In **`Python`**:

```python
my_list = [1, 3, 5]
```

In **`Javascript`**:

```javascript
const myList = [4, 5, 6];
```

## Functions

**`Python`** uses **`def`** followed by a colon **`:`** for their functions:

```python
def foo(str):
    print(str)
```

**`Javascript`** uses curly braces `{}` and **`function`** (or an _**`arrow function`**_):

```javascript
function foo(str) {
  console.log(str);
}
// OR an Arrow Function

const foo = (str) => console.log(str);
```

Unlike python, javascript is not a language which changes due to indentation. Although it is highly recommended that you indent your js code for readability, it is not a deal breaker and it won't stop your function from working.

If you use an arrow function, it must come before it's usage. This does rule not apply a regular javascript function.

```javascript
arrTestFunc();
// will throw an error saying "arrTestFunc" has not been declared.
regTestFunc();
// 'hello world' will be consoled'

const arrTestFunc = () => console.log("hello world");

function regTestFunc() {
  console.log("hello world");
}
```

## If Statements

In **`Python`** just uses colons **`:`** after each condition and an indented code block. Statements are separated by a **`elif`** and **`else`**:

```python
if condition_one:
  print("condition 1 met")
elif condition_two:
  print("condition 2 met")
else:
  print('else condition')
```

In **`Javascript`** wrap the condition in **`parenthesis`** `()` and the output for the condition in **`curly braces`** `{}`. Each condition can be separated with **`else if`** or **`else`**:

```javascript
if (condition1) {
  console.log("condition 1 met");
} else if (condition2) {
  console.log("condition 2 met");
} else {
  console.log("else condition");
}
```

### Logical Operators

When declaring conditions, we use the following:

| Python    | Javascript     |
| --------- | -------------- |
| **`or`**  | &#124;&#124;   |
| **`and`** | **&&**         |
| **`not`** | **!condition** |

In **`Python`**:

```python
if condition1 or condition2 # ||
if condition1 and condition2 # &&
if not condition ## !condition
```

In **`Javascript`**:

```javascript
if (condition1 || condition2) // or
if (condition1 && condition2) // and
if (!condition) // is not
```

Experiment with this in a sandbox as it can be confusing at times not using **`or`**, **`and`** and **`not`**.

## For Loop

In **`Python`** we replace that logic with **`in range(x)`**.

In **`Javascript`**, you are required to declare a variable and increment it using the for loop.

in **`Python`:**

```python
for i in range(5):
    print(i)
```

In **`Javascript`:**

```javascript
for (let i = 0; i < 5; i++) {
  console.log(i);
}
```

### If you want to access an object or item in an Array:

In **Python:**

```python
for obj in arr:
    print(obj)
```

In **Javascript:**

```javascript
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}
```

In this instance we're logging each item in array (list) by accessing each index starting at 0.

## Types

**`Primitive data`** types represent the fundamental values that we can work with in a programming language. **`JavaScript`** has 6 types to **`Python`**'s has 4.

- **`Python`** data types: Integers (`int`), Floats (`float`), Booleans (`bool`), and strings (`str`).
- **`JavaScript`** data types: `undefined`, `Boolean`, `String`, `Number`, `BigInt`, and `Symbol`.

To check types in **`javascript`**:

```python
type(instance);
```

To check types in **`python`**:

```javascript
typeof instance;
```

## Imports

Importing files are pretty similar, you just have to swap the order of **`import`** and **`from`**.

In **`Python`:**

```python
from django.db import models
```

In **`Javascript`:**

```javascript
import React from "react";
```

One of the main difference is that you must export things in javascript, this is not automatic like python.

You can either declare a default export or export multiple things from one file as an object.

Here is an example:

```javascript
// firstFile.js - export 2 functions

export const testFunc = () => console.log("hello world");
export function secondTestFunc() {
  console.log("hello world 2");
}

// secondFile.js - export 1 function by default
const uniqueFunc = () => console.log("hello world from another file");

export default uniqueFunc;

// index.js -

import { testFunc, secondTestFunc } from "firstFile.js";
import uniqueFunc from "secondFile.js";
```

Note: To avoid confusion, I imported named the import **`uniqueFunc`** from the **`secondFile`** but you name the import whatever you wish as it is the default import.

## Classes

In **`Python`**, the constructor that initialises the new instance is called **`__init__`**. This method is called automatically when an instance of the class is created to initialise its attributes. It's parameters list defines the values that we have to pass to create the instance. This list starts with self as the first parameter.

In **`JavaScript`**, the constructor method is called constructor and it has a parameters list as well. **`Javascript`** uses curly braces **`{}`** and **`Python`** uses colons **`:`**.

### Class format

In **`Python`**:

```python
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
```

In **`Javascript`**:

```javascript
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}
```

### Assign value to a Class

In **`Python`**:

```python
self.attribute = value
```

In **`Javascript`**:

```javascript
this.attribute = value;
```

### Create Class Instance

In **`Python`**:

```python
person_one = Person("John", 18)
```

In **`Javascript`**:

```javascript
personOne = new Person("John", 18);
```

## Summary

The honest truth is learning javascript as a python developer is harder the other way round. But if you have a good level of python, all you need to do is wrap your head around the usage as the logic is pretty much the same. The goal of this tutorial is to show you the subtle differences between **`python`** and **`javascript`**. The best way to learn is practice. Play around with a sandbox and write some basic code in javascript.

A good way to practice is trying solve a few problems in Javascript on [**`Code Wars`**](https://www.codewars.com/).

Thanks for reading and Good Luck on your coding journey!