How Python can help you learn ES6

How Python can help you learn ES6

In this post, we’ll look at how Python can help you learn ES6.

“Have you learned ES6 yet?”

Oof. I used to feel a sense of pressure when people would ask me that. In the end, I learned ES6 with the help of Python. Strange, huh? Turns out, a bunch of syntax is shared between the two languages, so they go hand in hand in a way.

Basic differences between Python and ES6

Before we get into how similar JavaScript and Python are, I first want to talk about some key differences. For example, whitespace in JavaScript doesn’t matter at compile time, but it sure does in Python. Python relies on indentation to determine the grouping of statements.

Primitives in JavaScript and **Python **are also quite different. Check out the table below which details the primitives of both languages. You’ll see that they overlap a bit with their representations of Booleans and nothing, but beyond that, they’re distinct.

Table of primitives in JavaScript** **versus Python

One last, basic difference to note about JavaScript** and Python **is that JavaScript allows type coercion. The following code blocks demonstrate coercing a number to a string in JavaScript, but an impossibility in Python!

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

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

Functions or.. methods?

Functions and conditionals have extremely similar structures in both **JavaScript **and Python. For example:

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'

I hadn’t thought too much about this, but with JavaScript, the idea of “methods” often refers to methods that are built into the specification of the language, e.g. Function.prototype.apply().

From MDN:

In most respects functions and methods are identical except for two key differences:> A method is implicitly passed the object on which it was called.> A method is able to operate on data that is contained within the class.
Because classes don’t truly exist in JavaScript, the function and method example below is represented in **Python **only (more on ES6 classes later in this article).

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>

A function versus a method in Python

Ok, onto some of the ways **Python **pushed me to learn more about ES6!

Block scope

When I first started learning JavaScript (back in “ancient” ES5 days), I thought many structures in the language created scope. I thought that blocks inside of conditionals statements created scope. I found that only functions create scope in JavaScript.

With the addition of const and let to ES6, we get block scope!

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

What else creates scope in JavaScript, ES6, and Python? And what type of scope do they use? Check out the following table:

Template literals

I often think of template literals as Mad Libs. In case you didn’t grow up with Mad Libs, they were short stories which you could fill in with your own content. Sentences were missing words, and you could write anything you wanted into those spaces. You only had to conform to the specified word type: noun, pronoun, verb, adjective, exclamation.

Mad Libs that read things like:

mothers sit around burping. Last summer, my little brother fell in a/an hairdo and got poison palmtree all over his butt. My family is going to Winsconsin, and I will..
Similar to Mad Libs, template literals are string literals that allow embedded expressions. They were originally called “template strings” in prior editions of the ES2015 specification.

Yup, these already existed in **Python **before **ES6 **was released. I had actually learned about literal string interpolation in Python, which made it that much easier for me to understand template literals in ES6. They are great because you no longer need the concatenation found in older versions of JavaScript which could get a bit ridiculous and coerce other types into strings.

let exclamation = 'Whoa!';
let sentence = `They are really similar to Python.`;
 
console.log(`Template Literals: ${exclamation} ${sentence}`);
// Template Literals: Whoa! They are really similar to Python.

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

Default parameters

Yup, Python has had these forever too. Default parameters set a default for function parameters. This is most effective for avoiding bugs that arise when arguments are missing. And with the advent of ES6, JavaScript gained default parameters too.

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

Rest parameter syntax allows us to represent an indefinite number of arguments as an array. In Python, they’re called *args, which again, I’d already learned before ES6! Are you sensing a pattern here?

Check out how each of the languages bundles parameters up in neat little packages:

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!

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

Now, let’s look at prototypal inheritance! ES6 classes are actually syntactic sugar and based on the prototype chain found in ES5 and previous iterations of JavaScript. So, what we can do with **ES6 **classes is not much different from what we do with ES5 prototypes.

Python has classes built in, allowing for quick and easy object-oriented programming. I always found the prototype chain extremely confusing in JavaScript, but looking at **Python **and **ES6 **classes side by side really made sense to me.

To explain what the JavaScript prototype is, here’s a quote from MDN:

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.
Let’s take a look at these ES6 “classes” based on the prototype chain:

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')

A big difference between ES6 Classes and ES5 Prototypes: you can inherit more easily with classes than with the prototype chain. This is very similar to Python’s structure. Neat!

So there you have it. A bunch of examples of how Python helped me learn all about ES6. Often with programming languages, many differences exist, but so do many similarities. And it’s in those similarities that we can more easily learn new languages!

JavaScript vs Python: Will Python Replace JavaScript popularity by 2020?

JavaScript vs Python: Will Python Replace JavaScript popularity by 2020?

JavaScript is currently the most commonly used programming language but now Python is dishing out some stiff competition. Python has been steadily increasing in popularity so much so that it is now the fastest-growing programming language. So will Python Replace JavaScript popularity by 2020?

This is the Clash of the Titans!!

And no…I am not talking about the Hollywood movie (don’t bother watching it…it’s horrible!). I am talking about JavaScript and Python, two of the most popular programming languages in existence today.

JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now Python is dishing out some stiff competition. Python has been steadily increasing in popularity so much so that it is now the fastest-growing programming language. So now the question is…Will Python Replace JavaScript popularity by 2020?

To understand the above question correctly, it is important to know more about JavaScript and Python as well as the reasons for their popularity. So let’s start with JavaScript first!

Why is JavaScript so popular?

JavaScript is a high-level, interpreted programming language that is most popular as a scripting language for Web pages. This means that if a web page is not just sitting there and displaying static information, then JavaScript is probably behind that. And that’s not all, there are even advanced versions of the language such as Node.js which is used for server-side scripting.

JavaScript is an extremely popular language. And if my word doesn’t convince you, here are the facts!!!

According to StackOverflow Developer Survey Results 2019, JavaScript is the most commonly used programming language, used by 69.7 % of professional developers. And this is a title it has claimed the past seven years in a row.

In addition to that, the most commonly used Web Frameworks are jQuery, Angular.js and React.js (All of which incidentally use JavaScript). Now if that doesn’t demonstrate JavaScript’s popularity, what does?!

Image Source: Stackoverflow

So now the question arises…Why is JavaScript so popular?

Well, some of the reasons for that are:

  • JavaScript is used both on the client-side and the server-side. This means that it runs practically everywhere from browsers to powerful servers. This gives it an edge over other languages that are not so versatile.
  • JavaScript implements multiple paradigms ranging from OOP to procedural. This allows developers the freedom to experiment as they want.
  • JavaScript has a large community of enthusiasts that actively back the language. Without this, it would have been tough for JavaScript to establish the number one position it has.
Can Python Replace JavaScript in Popularity?

Python is an interpreted, general-purpose programming language that has multiple uses ranging from web applications to data analysis. This means that Python can be seen in complex websites such as YouTube or Instagram, in cloud computing projects such as OpenStack, in Machine Learning, etc. (basically everywhere!)

Python has been steadily increasing in popularity so much so that it is the fastest-growing major programming language today according to StackOverflow Developer Survey Results 2019.

This is further demonstrated by this Google Trends chart showing the growth of Python as compared to JavaScript over the last 5 years:

As shown in the above data, Python recorded increased search interest as compared to JavaScript for the first time around November 2017 and it has maintained its lead ever since. This shows remarkable growth in Python as compared to 5 years ago.

In fact, Stack Overflow created a model to forecast its future traffic based on a model called STL and guess what…the prediction is that Python could potentially stay in the lead against JavaScript till 2020 at the least.

Image Source : Stackoverflow

All these trends indicate that Python is extremely popular and getting even more popular with time. Some of the reasons for this incredible performance of Python are given as follows:

  • Python is Easy To Use
    No one likes excessively complicated things and that’s one of the reasons for the growing popularity of Python. It is simple with an easily readable syntax and that makes it well loved by both seasoned developers and experimental students. In addition to this, Python is also supremely efficient. It allows developers to complete more work using fewer lines of code. With all these advantages, what’s not to love?!!
  • Python has a Supportive Community
    Python has been around since 1990 and that is ample time to create a supportive community. Because of this support, Python learners can easily improve their knowledge, which only leads to increasing popularity. And that’s not all! There are many resources available online to promote Python, ranging from official documentation to YouTube tutorials that are a big help for learners.
  • Python has multiple Libraries and Frameworks
    Python is already quite popular and consequently, it has hundreds of different libraries and frameworks that can be used by developers. These libraries and frameworks are really useful in saving time which in turn makes Python even more popular. Some of the popular libraries of Python are NumPy and SciPy for scientific computing, Django for web development, BeautifulSoup for XML and HTML parsing, scikit-learn for machine learning applications, nltk for natural language processing, etc.
So What’s the Conclusion?

While JavaScript is currently the most popular programming language, Python could soon outstrip it of this title based on its incredible growth rate. So it is entirely possible that Python could be the most popular programming language by 2020.

However, this will merely impact the relative popularity of these two languages and not specify which among them is the better language. That choice is entirely subjective and may depend on multiple factors such as project requirements, scalability, ease of learning as well as the future growth prospects.

JavaScript vs Python : Can Python outperform JavaScript in the next five years?

JavaScript vs Python : Can Python outperform JavaScript in the next five years?

JavaScript and Python are two influential programming languages for building a wide range of applications. While JavaScript has been the dominant programming language for many years, Python’s fast-growth threatens to dethrone the widely popular technology.

JavaScript and Python are two influential programming languages for building a wide range of applications. While JavaScript has been the dominant programming language for many years, Python’s fast-growth threatens to dethrone the widely popular technology.

This is the Clash of the Titans!!

And no…I am not talking about the Hollywood movie (don’t bother watching it…it’s horrible!). I am talking about JavaScript** and **Python, two of the most popular programming languages in existence today.

JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now Python is dishing out some stiff competition. Python has been steadily increasing in popularity so much so that it is now the fastest-growing programming language. So now the question is…Will Python Replace JavaScript popularity by 2020?

To understand the above question correctly, it is important to know more about JavaScript and Python as well as the reasons for their popularity. So let’s start with JavaScript first!

Why is JavaScript so popular?

JavaScript is a high-level, interpreted programming language that is most popular as a scripting language for Web pages. This means that if a web page is not just sitting there and displaying static information, then JavaScript is probably behind that. And that’s not all, there are even advanced versions of the language such as Node.js which is used for server-side scripting.

JavaScript is an extremely popular language. And if my word doesn’t convince you, here are the facts!!!

According to StackOverflow Developer Survey Results 2019, JavaScript is the most commonly used programming language, used by 69.7 % of professional developers. And this is a title it has claimed the past seven years in a row.

In addition to that, the most commonly used Web Frameworks are jQuery, Angular.js and React.js (All of which incidentally use JavaScript). Now if that doesn’t demonstrate JavaScript’s popularity, what does?!

Image Source: Stackoverflow

So now the question arises…Why is JavaScript so popular?

Well, some of the reasons for that are:
JavaScript is used both on the client-side and the server-side. This means that it runs practically everywhere from browsers to powerful servers. This gives it an edge over other languages that are not so versatile.JavaScript implements multiple paradigms ranging from OOP to procedural. This allows developers the freedom to experiment as they want.JavaScript has a large community of enthusiasts that actively back the language. Without this, it would have been tough for JavaScript to establish the number one position it has.

Can Python Replace JavaScript in Popularity?

Python is an interpreted, general-purpose programming language that has multiple uses ranging from web applications to data analysis. This means that Python can be seen in complex websites such as YouTube or Instagram, in cloud computing projects such as OpenStack, in Machine Learning, etc. (basically everywhere!)

Python has been steadily increasing in popularity so much so that it is the fastest-growing major programming language today according to StackOverflow Developer Survey Results 2019.

This is further demonstrated by this Google Trends chart showing the growth of Python as compared to JavaScript over the last 5 years:

As shown in the above data, Python recorded increased search interest as compared to JavaScript for the first time around November 2017 and it has maintained its lead ever since. This shows remarkable growth in Python as compared to 5 years ago.

In fact, Stack Overflow created a model to forecast its future traffic based on a model called STL and guess what…the prediction is that Python could potentially stay in the lead against JavaScript till 2020 at the least.

Image Source : Stackoverflow

All these trends indicate that Python is extremely popular and getting even more popular with time. Some of the reasons for this incredible performance of Python are given as follows:
Python is Easy To UseNo one likes excessively complicated things and that’s one of the reasons for the growing popularity of Python. It is simple with an easily readable syntax and that makes it well loved by both seasoned developers and experimental students. In addition to this, Python is also supremely efficient. It allows developers to complete more work using fewer lines of code. With all these advantages, what’s not to love?!!Python has a Supportive CommunityPython has been around since 1990 and that is ample time to create a supportive community. Because of this support, Python learners can easily improve their knowledge, which only leads to increasing popularity. And that’s not all! There are many resources available online to promote Python, ranging from official documentation to YouTube tutorials that are a big help for learners.Python has multiple Libraries and FrameworksPython is already quite popular and consequently, it has hundreds of different libraries and frameworks that can be used by developers. These libraries and frameworks are really useful in saving time which in turn makes Python even more popular. Some of the popular libraries of Python are NumPy and SciPy for scientific computing, Django for web development, BeautifulSoup for XML and HTML parsing, scikit-learn for machine learning applications, nltk for natural language processing, etc.## So What’s the Conclusion?

While JavaScript is currently the most popular programming language, Python could soon outstrip it of this title based on its incredible growth rate. So it is entirely possible that Python could be the most popular programming language by 2020.

However, this will merely impact the relative popularity of these two languages and not specify which among them is the better language. That choice is entirely subjective and may depend on multiple factors such as project requirements, scalability, ease of learning as well as the future growth prospects.

Linked Lists in JavaScript With ES6

Linked Lists in JavaScript With ES6

Linked Lists in JavaScript with ES6.This series is about data structure implementation in JavaScript using the ES6 specification.. Let's see how to make a singly linked list in Javascript… ... list in Javascript. We'll be using ES6 syntax throughout.

This is a continuation of a previous piece where we digested all surrounding concepts, pros and cons, Big O time complexity, real use cases, linked-list mainly operations, and all that kind of theory. If you have not read it yet, I recommend you read it first.

This series is about data structure implementation in JavaScript using the ES6 specification.

The aim of this second piece is to walk through the implementation of a linked list. Actually, the two pieces enclose a linked list itself since the prior piece is pointing to this one.

The Node Class

In the next code, we’re going to define our Node class with its constructor. Remember, the node is the basic building block to store the data and the next pointer.

This class will have to handle the node creation. Every time the class is instantiated, the constructor has the responsibility to initialize the two properties: data and next.


Node Class

Now the challenge is to create the next four nodes (just nodes creation, not how to connect them).


Linked List

Basically, we have to instantiate the Node class four times in order to create the four nodes.


Creating Nodes

At this point, we don’t care about the second parameter. Why? Because at this moment, we’re just learning how to create the node without having to worry about how they’ll be connecting together.

How Can We Connect the Nodes?

In the prior code, we just created nodes independently. Now is time to learn how to connect them to form the linked list.


Connecting nodes

We have defined the Node class. Next is to define a new class that will handle the nextpointer property and the main operations in the linked list. Let’s create the LinkedList class.


Linked List Class

In the above code, we have just defined a class called LinkedList with its constructor. This has the work of initializing the headproperty, to store the first node,and size, to keep track of the size of the linked list.

Next is to offer the ability to insert to the head, to the tail, or at any random position in the list.

Inserting Into the Head


Inserting to head

We have just created a simple method to add nodes to the head of the linked list. We are passing down to it the dataparameter and setting a value for the this.head property creating a new instance of the Node class.

Let’s do some tests of its implementation so far and see the results.

The output will be:


Linked list output

Inserting at the Tail

We just learned how to add nodes to the head. It’s time to know how to add nodes to the tail.


Inserting at the tail

In the aboveinsertToTail function, we are passing down the data parameter, and then we created a new instance of the Node class. After that, we are checking if the head is empty. If so, the head itself will be set to the new node we have just after created. Otherwise, set the tail with the head and then loop through the linked list to find the tail and update the tail’s next pointer.

Inserting at Random Position

Finally, we are going to see how to insert a new node in the linked list at a given random position. For this, we have to traverse the list until we find the desired position.

Inserting at a given random position

Now we are going to test this function using the next tests.

The output will be as below. As you can see, at the given index, the node (600) was added at the second index of the list.

The Whole Code

class Node {
  constructor(data, next = null) {
    this.data = data;
    this.next = next;
  }
}

//Let's create four nodes
let node1 = new Node(5);
let node2 = new Node(10);
let node3 = new Node(20);
let node4 = new Node(1);

//connecting nodes
node1.next = node2;
node2.next = node3;
node3.next = node4;

//LinkedList Class
class LinkedList {
  constructor() {
    this.head = null; //first node of the Linked List
    this.size = 0; //Track size of the linked list
  }
  //Insert to head
  insertToHead(data) {
    this.head = new Node(data, this.head);
    this.size++;
  }

  //Insert into the tail
  insertToTail(data) {
    const node = new Node(data);
    let tail = null;
    //if empty, make it head
    if (!this.head) {
      this.head = node;
    } else {
      tail = this.head;
      while (tail.next) {
        tail = tail.next;
      }
      tail.next = node;
    }
    this.size++;
  }

  //Insert at random position
  insertAt(data, index) {
    //if it's empty
    if (!this.head) {
      this.head = new Node(data);
      return;
    }
    //if it needs add to the front of the list
    if (index === 0) {
      this.insertToHead(data); //reuse insertToHead function
      return;
    }
    let node = new Node(data);
    let current, previous;
    let count = 0;
    // current will be first
    current = this.head;
    while (count < index) {
      previous = current;
      count++;
      current = current.next;
    }
    node.next = current;
    previous.next = node;
    this.size++;
  }
}

const linkedList = new LinkedList();
linkedList.insertToHead(100);
linkedList.insertToHead(200);
linkedList.insertToHead(300);
linkedList.insertToTail(400);
linkedList.insertAt(600, 2);

console.table(linkedList);

LinkedList.js

I hope you have gained more knowledge about data structure and especially with Linked list. That’s all for now.

Thanks for reading!