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
Hello World! and Beyond: Your First Application

Ah, the venerable "Hello World!" script. While very simple, it's a good first test of any language. Let's do a little more than just saying hello, though; let's work with several small applications that we'll use to get our hands dirty. After all, there's more to programming than just theory. We'll take a look at a common problem presented in coding challenges, as well as understand how our programs are working.

The following topics will be covered in this chapter:

  • I/O with the console and alert messages
  • Working with input in a function
  • Using objects as a datastore
  • Understanding scope

Technical requirements

I/O with the console and alert messages

So far, we've seen how JavaScript can output information to the user. Consider the following code:

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

Now, if we execute Riker.sayHello(), we will see the following in the console:

Figure 5.1 – Console output

Take a look for yourself in the chapter-5 directory in the repository: https://github.com/PacktPublishing/Hands-on-JavaScript-for-Python-Developers/blob/master/chapter-5/alerts-and-prompts/console.html.

OK, great. We have some console output, but that's not a very efficient way to get output, as users don't typically have the console open. There is a convenient method for output that, while not practical for a fully fledged web application, is useful for testing...

Working with input in a function

If we take a look at the preceding object, we'll see the following:

if (values.indexOf(answer) < 0) {
alert('Value not found')
} else {
alert(this[answer])
}
...

Since we're dealing with arbitrary input, the first thing we're doing is checking against our array of answers to see whether the property requested exists. If it does not, a simple error message is alerted. If it is found, then we can alert the value. If you remember from Chapter 3, Nitty-Gritty Grammar, object properties can be accessed via dot notation and bracket notation. In this case, we're working with a variable as the key, so we can't do this because it would be interpreted as the key. Thus, we use bracket notation to access the proper object value.

Exercise – Fibonacci sequence

For this exercise, construct a function to take a number. The end result should be the sum of numbers in the Fibonacci sequence (https://en.wikipedia.org/wiki/Fibonacci_number...

Using objects as a datastore

Here's an interesting problem that I've seen in programming interviews, as well as the most efficient way to solve it. It has an expensive input time, but an O(1) retrieval time, which is generally considered a metric of success for algorithmic complexities when you can expect more reads than writes.

Exercise – multiplication

Consider the following code (https://github.com/PacktPublishing/Hands-on-JavaScript-for-Python-Developers/tree/master/chapter-5/matrix/starter-code):

const a = [1, 3, 5, 7, 9]
const b = [2, 5, 7, 9, 14]

// compute the products of each permutation for efficient retrieval

const products = { }

// ...

const getProducts = function(a,b) {
// make an efficient means of retrieval
// ...
}

// bonus: get an arbitrary key/value pair. If nonexistent, compute it and store it.

So, what's the solution within the paradigm of using an object? Let's take a look, break it down, and then reverse-engineer our use of objects as a data...

Understanding scope

Let's discuss scope for a while before we build a larger application. Simply put, scope defines when and where we can use a variable or a function. Scope in JavaScript is broken down into two discrete categories: local and global. If we look at our previous multiplication program, we can see that there are three variables outside any functions; they're hanging out at the root level of our program:

01: const a = [1, 3, 5, 7, 9]
02: const b = [2, 5, 7, 9, 14]
03:
04: // compute the products of each permutation for efficient retrieval
05:
06: const products = { }
07:
08: const makeProducts = function(array1, array2) {
09: array1.forEach( (multiplicant) => {
10: if (!products[multiplicant]) {
11: products[multiplicant] = { }
12: }
13: array2.forEach( (multiplier) => {
14: if (!products[multiplier]) {
15: products[multiplier] = { }
16: }
17: products[multiplicant][multiplier]...

Summary

In order for our programs to be useful, they usually depend on input from the user or other functions. By scaffolding our programs to be flexible, we also need to keep in mind the idea of scope: when and where we can use a function or variable. We also took a look at how objects can be used to store data efficiently for retrieval.

Let's not forget closures, the seemingly complicated concept that is, in practice, just a way of describing scope.

In the next chapter, we'll explore the frontend more as we get into using the Document Object Model (DOM) and manipulating information on the page instead of only interacting with alerts and the console.

Questions

Consider the following code:

function someFunc() {
let bar = 1;

function zip() {
alert(bar); // 1
let beep = 2;

function foo() {
alert(bar); // 1
alert(beep); // 2
}
}

return zip
}


function sayHello(name) {
const sayAlert = function() {
alert(greeting)
}

const sayZip = function() {
someFunc.zip()
}

let greeting = `Hello ${name}`
return sayAlert
}
  1. How would you get an alert of Hello Bob?
    1. sayHello()('Bob')
    2. sayHello('Bob')()
    3. sayHello('Bob')
    4. someFunc()(sayHello('Bob'))
  2. What will alert(greeting) do in the preceding code?
    1. Alert greeting.
    2. Alert Hello Alice.
    3. Throw an error.
    4. None of the above.
  3. How would we get an alert message of 1?
    1. someFunc()()
    2. sayHello().sayZip()
    3. alert(someFunc.bar)
    4. sayZip()
  4. How would we get an alert message of 2?
    1. someFunc().foo().
    2. someFunc()().beep.
    3. We can't because it's not in the scope.
    4. We can't because it's not defined.
  5. How can we change someFunc to alert...
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