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
Data and Your Friend, JSON

It's time to learn the specifics of how JavaScript deals with data internally. Most of these structures are (nearly) identical to Python, but there are differences in syntax and usage. We touched on them in Chapter 3, Nitty-Gritty Grammar, but now it's time to take a deeper dive into how we work with data and use methods and properties. Understanding how to work with data is foundational to using JavaScript, especially when doing advanced work such as working with APIs and Ajax.

The following topics will be covered in this chapter:

  • Data types – both JavaScript and Python are dynamically typed!
  • Exploring data types
  • Arrays and sets
  • Objects and JSON
  • The HTTP verbs
  • API calls from the frontend – Ajax

Technical requirements

Data types – both JavaScript and Python are dynamically typed!

In Chapter 3, Nitty-Gritty Grammar, we discussed using typeof() to ascertain what a variable's data type is and using let and const to define them. There's an interesting fact about JavaScript that Python shares: both are dynamically typed. As opposed to statically typed languages such as Java, JavaScript's variable types can change over the course of a program. This is one reason why typeof() can come in handy.

Let's take a look at a quick example contrasting JavaScript with Java:

Java JavaScript
int age;
age = 38;
age = "thirty-eight";
let age
age = 38
age = "thirty-eight"

If we tried to run the Java code, we'd get an error stating that the types are incompatible. In Java, variables have a type. When we run the JavaScript code, however, everything's just fine. In JavaScript, values have a type.

It's also important to know that JavaScript is weakly typed...

Exploring data types

Let's take a deeper dive into the primitive data types because they'll be crucial to our work in JavaScript. We not only need to know what we're using, but the why is also important. Our primitives are the building blocks of the rest of the language: Booleans, numbers, and strings. The rest of JavaScript is built upon these primitive data types. We'll start with Booleans.

Booleans

The Boolean is possibly the simplest and most universal data type since it's inherently tied to the 1s and 0s of binary logic. In JavaScript, a Boolean is written simply as true or false. It's not recommended to use 1 or 0 for Boolean values, as they'll be interpreted as numbers and thus fail strict equality. Boolean values are a specific data type, as opposed to in Python, where, at the core of the language, Boolean inherits from a number.

Remember in Chapter 3, Nitty-Gritty Grammar, where we learned that almost everything in JavaScript is an object? The...

Arrays and sets

Any programming language has some conception of an array or a collection of items that all share some common features or use. JavaScript has a few of them: arrays and sets. Both of these structures contain items, and in many ways, they are similar in usage, too, in that they can be enumerated, iterated over, and displayed for purposes of logical construction.

Let's first look at arrays.

Arrays

Arrays can contain different data types. This is a fully viable array:

const myArray = ['hello',1,'goodbye',null,true,1,'hello',{ 0 : 1 }]

It contains strings, numbers, Booleans, null, and an object. This is fine! While in practice you may not be mixing data types, there's nothing preventing you from doing so.

There is a quirk about using typeof() on arrays: since they're not true primitives, typeof(myArray) will return object. You should keep that in mind as you write JavaScript.

As we saw before in Chapter 3, Nitty-Gritty Grammar, ...

Objects and JSON

Objects! Objects are at the core of JavaScript. As mentioned before in Chapter 3, Nitty-Gritty Grammar, almost everything in JavaScript is, at its core, an object. Objects may be intimidating at first, but they're easy enough to grasp in theory:

Here's the skeleton of an object:

const myObject = { key: value }

An object is a collection of key/value pairs. They're useful for many reasons, especially to contain and organize data. Let's look at the example of Captain Picard from the Chapter 3, Nitty-Gritty Grammar:

const captain = {
"name": "Jean-Luc Picard",
"age": 62,
"serialNumber": "SP 937-215",
"command": "NCC 1701-D",
"seniorStaff": ['Riker','Data','Worf', 'Troi']
}

As we saw, we can use dot notation to access the properties of an object, like so:

captain.command // equals "NCC 1701-D"

We can also use other data types...

The HTTP verbs

Let's take a quick look at the HTTP verbs that allow us to communicate back and forth with APIs:

HTTP Verb CRUD Equivalent
POST Create
GET Read
PUT Update/Replace
PATCH Update/Modify
DELETE

Delete

While the actual verbs used in an API depend on the API's design, these are the standard REST terms that many APIs today use. REST stands for REpresentational State Transfer and is a standard description of how to format APIs. Now, REST or RESTful APIs don't always have to communicate with JSON—REST is agnostic to format. Let's take a look at API calls in practice.

API calls from the frontend – Ajax

Ajax (also spelled AJAX) stands for Asynchronous JavaScript and XML. These days, however, you're more likely to work with JSON than XML, so the name is a bit misleading. On to code: take a look at https://github.com/PacktPublishing/Hands-on-JavaScript-for-Python-Developers/blob/master/chapter-4/ajax/swapi.html. Open this locally, and in your developer tools, you should see a JSON object as follows:

Figure 4.7 – SWAPI Ajax result

Congratulations! You've made your first Ajax call! Let's break down the following code:

fetch('https://swapi.co/api/people/1/')
.then((response) => {
return response.json()
})
.then((json) => {
console.log(json)
})

fetch is a fairly new API in ES6 that essentially replaces the older, more complicated way of making Ajax calls with XMLHttpRequest. As you can see, the syntax is fairly concise. What might not be obvious is the role that the .then() functions play—or even...

Summary

Data is at the heart of every program, and your JavaScript programs are no different:

  • JavaScript is loosely typed, which means variable types can mutate if needed.
  • Booleans are simple true/false statements.
  • Numbers are non-differentiated between integers, floats, or other types of numbers.
  • Arrays and sets can contain a lot of data and make organizing our data easier.
  • Objects are key-value pairs that efficiently store data for O(1) retrieval.
  • API calls are actually not that scary!

We've taken a closer look at data types, APIs, and JSON. What we've discovered is that data is very flexible in JavaScript, up to and including manipulating the prototypes of the objects themselves. Taking a look at JSON and APIs, we've successfully used fetch() to perform our first API calls.

In the next chapter, we'll dive further into writing JavaScript to make a more interesting application, as well as understanding the details of how to construct one!

Questions

For the following questions, select the correct option:

  1. JavaScript is inherently:
    1. Synchronous
    2. Asynchronous
    3. Both
  2. A fetch() call returns a:
    1. then
    2. next
    3. finally
    4. Promise
  1. With prototypal inheritance, we can (select all):
    1. Add methods to a base data type.
    2. Subtract methods from a base data type.
    3. Rename our data type.
    4. Cast our data into another format.
let x = !!1
console.log(x)
  1. From the preceding code, what will be the expected output?
    1. 1
    2. false
    3. 0
    4. true
const Officer = function(name, rank, posting) {
this.name = name
this.rank = rank
this.posting = posting
this.sayHello = () => {
console.log(this.name)
}
}

const Riker = new Officer("Will Riker", "Commander", "U.S.S. Enterprise")
  1. In the preceding code, what's the best way to output Will Riker?
    1. Riker.sayHello()
    2. console.log(Riker.name)
    3. console.log(Riker.this.name)
    4. Officer.Riker.name()

    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 $15.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