Reader small image

You're reading from  Hands-on JavaScript for Python Developers

Product typeBook
Published inSep 2020
Reading LevelIntermediate
PublisherPackt
ISBN-139781838648121
Edition1st Edition
Tools
Right arrow
Author (1)
Sonyl Nagale
Sonyl Nagale
author image
Sonyl Nagale

Chicago-born, Iowa-raised, Los Angeles-seasoned, and now New York City-flavored, Sonyl Nagale started his career as a graphic designer focusing on web, which led down the slippery slope to becoming a full-stack technologist instead. With an eye toward the client use case and conversation with the creative side, he prides himself on taking a holistic approach to software engineering. Having worked at start-ups and global media companies using a variety of languages and frameworks, he likes solving new and novel challenges. Passionate about education, he's always excited to have great teachable moments complete with laughter and seeing the Aha! moments in students eyes.
Read more about Sonyl Nagale

Right arrow
Nitty-Gritty Grammar

When comparing two programming languages, there are bound to be structural and grammatical differences. The good news is that both Python and JavaScript are very human-readable languages, so the context switch from Python to JavaScript and Node.js shouldn't be too taxing.

Style is a good question, though: tabs or spaces? Semicolons or not? Many stylistic questions that arise when writing in any programming languages have been answered by the dicta contained within Python's PEP-8 style guide. While JavaScript doesn't have an official style guide, don't worry—it's not the Wild West out there.

Before we can write JavaScript, we must know what it is to be able to read it and understand it. All programming languages vary from one to another, and using your Python knowledge to learn a new language will require a bit of reframing of...

Technical requirements

To code along with the examples in this chapter, you have a few choices:

  • Code directly in the JavaScript console in your browser
  • Code in the Node command line
  • Use a web editor, such as jsfiddle.net or codepen.io

Using a web editor may be preferable as you can easily save your progress. You should familiarize yourself with bringing up the JavaScript console in the browser anyway, as we'll be using it for debugging output. This is usually in the View menu in your browser; consult your browser's documentation for how to find it if it's not immediately obvious, as some browsers require turning on Developer mode in Preferences.

You can find the code files for this chapter on GitHub at https://github.com/PacktPublishing/Hands-on-JavaScript-for-Python-Developers/tree/master/chapter-3/Linting.

A history of style

Every programming language has its own style, designed to ease legibility and comprehension of each line of code. Some languages are stricter than others; JavaScript in its vanilla form is one of the looser languages in adhering to style. The Elements of Programming Style by Brian W. Kernighan and P. J. Plauger, first published in 1974, has a number of aphorisms that have helped shape not only coding standards but also programming languages themselves.

You may be familiar with the PEP-20 aphorisms from The Zen of Python:

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Complex is better than complicated.
  • Flat is better than nested.
  • Sparse is better than dense.
  • Readability counts.
  • Special cases aren't special enough to break the rules.
  • Although practicality beats purity.
  • Errors should never pass silently.
  • Unless explicitly silenced.
  • In the face of ambiguity, refuse the temptation to guess.
  • There should be one—...

Grammar rules

Just like with any other programming language, JavaScript has grammar rules that are to be followed in order for the computer to understand what our code is trying to tell it. These rules are fairly straightforward and range from capitalizing and punctuating your code, which enhances the readability, to using specific structures within your code and avoiding common words that can confuse meaning. The rules of JavaScript syntax are fairly simple and straightforward; they include the following:

  • Capitalization
  • Reserved words
  • Variable syntax
  • Data types
  • Logic structures
  • Functions
  • Punctuation

Capitalization counts

As with most programming languages, capitalization makes a difference. The myNode and mynode variables will be interpreted as completely different variables. That is, the computer will absolutely see the relationship between myNode and mynode because they are capitalized differently.

Reserved words

There are a good number of words reserved in JavaScript that cannot...

Punctuation and readability

As with every language, JavaScript has conventions on punctuation and how spacing affects readability. Let's take a look at a few ideas:

  • Python:
def add_one(x):
x += 1
return x
  • Java:
int add_one(int val) {
val += 1;
return val;
}
  • C++:
int add_one (int val)
{
val += 1;
return val;
}
  • JavaScript:
function addOne(val) {
return ++val
}

In JavaScript, the conventions of the preceding example are as follows:

  • No space between the function name and the parentheses.
  • A single space before the curly brace, which is on the same line.
  • The closing curly brace is on its own line, aligned with the opening statement of function.

There's also one more modern point to make here about JavaScript and the examples we'll be using in this book versus what you may encounter in the field and examples online: semicolons.

With few exceptions, in modern JavaScript, semicolons at the end of statements are optional. It used to be a best practice to always terminate...

The elephant in the room – whitespace

OK, OK, we know that Python is whitespace-delimited: tabs matter! However, JavaScript really doesn't care about whitespace in most cases. As we saw before, indentation and whitespace is a matter of style, not syntax.

So here's the thing: when I was first learning Python, the idea of a language that was whitespace-dependent was abhorrent. "How could a language that could break with an improper IDE setting survive?", I thought. My opinions aside, the good news is that indentation in Python is parallel to indentation plus curly braces in JavaScript.

Here's an example:

Python JavaScript
def hello_world(x):
if x > 3:
x += 1
else:
x += 2
return x
function helloWorld(val) {
if (val > 3) {
return ++val
} else {
return val+2
}
}

If you notice, our if statement inside our Python function is indented in the same way that this JavaScript example is indented, albeit without the curly braces. So yay...

Existing standards – linting to the rescue!

We've looked at JavaScript's conventions and norms, but most rules have a caveat that "this could vary" or "this isn't technically required." So, how do we make sense of our code in a malleable, opinion-driven environment? One answer: linting.

Simply put, linting refers to the process of running your code through predefined rules to ensure that not only is it syntactically correct, but it also adheres to proper style rules. This isn't a practice limited to JavaScript; you may have linted your Python code, too. In modern JavaScript, linting has come to be seen as a best practice to ensure your code is consistent. Two of the main style guides in the community are AirBnB (https://github.com/airbnb/javascript) and Google (https://google.github.io/styleguide/jsguide.html). Your code editor probably supports using a linter, but we won't go into using them in practice right now, as each editor varies...

Summary

JavaScript has a rich grammar and syntax, developed over years of use and refinement. Using ES6, we have a whole host of data types, methods of declaring functions, and code standards. While writing JavaScript can seem to be playing very loose and fast, there are best practices, and the fundamentals of the language are as robust as other languages. Remember that capitalization counts; don't use reserved words for variable names; use const or let to declare your variables; even though JavaScript is loosely typed, data types are important; and conditionals, loops, and functions all help structure the logic of your code.

A mastery of the grammar and syntax of JavaScript is vital to understanding how to use this robust language, so take your time familiarizing yourself with the details and intricacies. Moving forward, we will presume you have fluency in JavaScript's style as we get into more difficult material.

In the next chapter, we will get our hands dirty with data and...

Questions

Try your hand at answering the following questions to test your knowledge:

  1. Which of the following is not a valid JavaScript variable declaration?
    1. var myVar = 'hello';
    2. const myVar = "hello"
    3. String myVar = "hello";
    4. let myVar = "hello"
  2. Which of these starts a function declaration?
    1. function
    2. const
    3. func
    4. def
  1. Which of these is not a basic loop type?
    1. for..in
    2. for
    3. while
    4. map
  1. True or false – JavaScript requires line delineation with semicolons.
    1. True
    2. False
  2. True or false – whitespace never counts in JavaScript.
    1. True
    2. False

Further reading

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Hands-on JavaScript for Python Developers
Published in: Sep 2020Publisher: PacktISBN-13: 9781838648121
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Sonyl Nagale

Chicago-born, Iowa-raised, Los Angeles-seasoned, and now New York City-flavored, Sonyl Nagale started his career as a graphic designer focusing on web, which led down the slippery slope to becoming a full-stack technologist instead. With an eye toward the client use case and conversation with the creative side, he prides himself on taking a holistic approach to software engineering. Having worked at start-ups and global media companies using a variety of languages and frameworks, he likes solving new and novel challenges. Passionate about education, he's always excited to have great teachable moments complete with laughter and seeing the Aha! moments in students eyes.
Read more about Sonyl Nagale