ebook img

Just Javascript PDF

123 Pages·2021·5.969 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Just Javascript

01 Mental Models Read this code: let a = 10; let b = a; a = 0; What are the values of  a  and  b  a�er it runs? Work it out in your head before reading further. If you’ve been writing JavaScript for a while, you might object: “This snippet is much simpler than the code I’m writing every day. What’s the point?” The goal of this exercise isn’t to introduce you to variables. We assume you’re already familiar with them. Instead, it is to make you notice and reflect on your mental model. What’s a Mental Model? Read the code above again with an intention to really be sure what the result is. (We’ll see why this intention is important a bit later.) While you’re reading it for the second time, pay close a�ention to what’s happening in your head, step by step. You might notice a monologue like this: let a = 10; Declare a variable called  a . Set it to  10 . let b = a; Declare a variable called  b . Set it to  a . Wait, what’s  a  again? Ah, it was  10 . So  b  is  10  too. a = 0; Set the  a  variable to  0 . So  a  is  0  now, and  b  is  10 . That’s our answer. Maybe your monologue is a bit different. Maybe you say “assign” instead of “set,” or maybe you read it in a slightly different order. Maybe you arrived at a different result. Pay a�ention to how exactly it was different. Note how even this monologue doesn’t capture what’s really happening in your head. You might say “set  b  to  a ,” but what does it even mean to set a variable? You might find that for every familiar fundamental programming concept (like a variable) and operations on it (like se�ing its value), there is a set of deep-rooted analogies that you associated with it. Some of them may come from the real world. Others may be repurposed from other fields you learned first, like numbers from math. These analogies might overlap and even contradict each other, but they still help you make sense of what’s happening in the code. For example, many people first learned about variables as “boxes”—containers that hold your stuff. Even if you don’t vividly imagine boxes anymore when you see a variable, they might still behave “boxily” in your imagination. These approximations of how something works in your head are known as “mental models.” It may be hard if you’ve been programming for a long time, but try to notice and introspect your mental models. They’re probably a combination of visual, spatial, and mechanical mental shortcuts. These intuitions (like “boxiness” of variables) influence how we read code our whole lives. Unfortunately, sometimes our mental models are wrong. Maybe a tutorial we read early on sacrificed accuracy in order to make a concept easier to explain. Maybe, when we started learning JavaScript, we incorrectly “brought over” an expected behavior from a language we learned earlier. Maybe we inferred a mental model from some piece of code but never really verified it was accurate. Identifying and fixing these problems is what Just JavaScript is all about. We will gradually build (or possibly rebuild) your mental model of JavaScript to be accurate and useful. A good mental model will give you confidence in your own code, and it will let you understand (and fix) code that someone else wrote. (By the way, a being 0 and b being 10 is the correct answer.) Coding, Fast and Slow “Thinking, Fast and Slow” is a book by Daniel Kahneman that explores the two different “systems” humans use when thinking. Whenever we can, we rely on the “fast” system, which is good at pa�ern matching and “gut reactions.” We share this system (which is necessary for survival!) with many animals, and it gives us amazing powers like the ability to walk without falling over. But it’s not good at planning. Uniquely, thanks to the development of the frontal lobe, humans also possess a “slow” thinking system. This “slow” system is responsible for complex step-by-step reasoning. It lets us plan future events, engage in arguments, or follow mathematical proofs. Because using the “slow” system is so mentally draining, we tend to default to the “fast” one—even when dealing with intellectual tasks like coding. Imagine that you’re in the middle of a lot of work, and you want to quickly identify what this function does. Take a glance at it: function duplicateSpreadsheet(original) { if (original.hasPendingChanges) { throw new Error('You need to save the file before you can duplicate it.' } let copy = { created: Date.now(), author: original.author, cells: original.cells, metadata: original.metadata, }; copy.metadata.title = 'Copy of ' + original.metadata.title; return copy; } You’ve probably noticed that: This function duplicates a spreadsheet. It throws an error if the original spreadsheet isn’t saved. It prepends “Copy of” to the new spreadsheet’s title. What you might not have noticed (great job if you did!) is that this function also accidentally changes the title of the original spreadsheet. Missing bugs like this is something that happens to every programmer, every day. Now that you know a bug exists, will you read the code differently? If you used the “fast” thinking system at first, you might switch to the more laborious “slow” system when you realize there’s a bug in the code. When we use the “fast” system, we guess what the code does based on its overall structure, naming conventions and comments. Using the “slow” system, we retrace what the code does step by step—a tiring and time-consuming process. This is why having an accurate mental model is so important. Simulating a computer in your head is hard, and when you have to fall back to the “slow” thinking system, your mental model is all you can rely on. With the wrong mental model, you’ll fundamentally misunderstand what to expect from your code, and all your effort will be wasted. Don’t worry if you can’t find the bug at all—it just means you’ll get the most out of this course! Over the next modules, we’ll rebuild our mental model of JavaScript together, so that you can catch bugs like this immediately. In the next module, we’ll start building mental models for some of the most fundamental JavaScript concepts—values and expressions. Finished reading? Mark this episode as learned to track your progress. Mark as learned UP NEXT The JavaScript Universe → 02 The JavaScript Universe In the beginning was the Value. What is a value? It’s hard to say. What is a point in geometry? What is a word in human language? A value is a fundamental concept in JavaScript—so we can’t define it through other terms. Instead, we’ll define it through examples. Numbers and strings are values. Objects and functions are values, too. There are also a lot of things that are not values, like the pieces of our code—our if statements, loops, and variable declarations, for example. Values and Code As we start building our mental model, one of the first common misconceptions we need to clear up is that values are our code. Instead, we need to think of them separately—our code interacts with values, but values exist in a completely separate space. To distinguish between values and code in my JavaScript program, I like to imagine this drawing of the Li�le Prince by Antoine de Saint-Exupéry: I’m standing on a small planet, holding a list of instructions. This list is my program—my code. As I read through my list of instructions, I can see a lot going on—there are if statements, variable declarations, commas and curly braces. My code contains instructions like “make a function call,” “do this thing many times,” or even “throw an error.” I read through these instructions step by step from the surface of my li�le world. But every once in a while, I look up. On a clear night, I see the different values in the JavaScript sky: booleans, numbers, strings, symbols, functions and objects, null and undefined —oh my! I might refer to them in my code, but they don’t exist inside my code. In our JavaScript universe, values float in space. “Hold on,“ you might say, “I always thought of values as being inside of my code!” Here, I’m asking you to take a leap of faith. It will take a few more modules for this mental model to pay off. Give it five minutes. I know what I’m doing. Values Broadly, there are two kinds of values. Primitive Values Primitive values are like stars—cold and distant, but always there when I need them. Even from the surface of my small planet, I can find them and point them out. They can be numbers and strings, among other things. All primitive values have something in common: They are a permanent part of our JavaScript universe. I can point to them, but I can’t create, destroy, or change them. To see primitive values in practice, open your browser’s console and log them: console.log(2); console.log("hello"); console.log(undefined); Objects and Functions Objects and functions are also values but, unlike primitive values, I can manipulate them from my code. If primitive values are like distant stars, then objects and functions are more like asteroids floating around my planet. They’re not part of my code, but they’re close enough to manipulate. Fun Fact Functions are objects, but because they include a few unique additional features, we’re going to refer to them separately to avoid confusion. Go ahead and log a few of them to the browser console:

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.