Hi 👋👋 I'm Avraham Asraf, a computer science student at the Hebrew University. I'm fascinated by data science, technological education, and the delicate art of keeping our robotic overlords appeased.
mylearning's Introduction
mylearning's People
mylearning's Issues
mental modleDan Abramov
In the beginning was the Value.
What is a value? It’s hard to say.
This is like asking what a number is in math, or what a point is in geometry. A value is a thing in the JavaScript universe.
Numbers are values — but so are a few other things, like objects and
functions. However, many things, such as an if statement or a variable
declaration, are not values.
Code and Values
To distinguish values from everything else in my JavaScript program, I like to
imagine this drawing of the Little Prince by Antoine de Saint-Exupéry
… 1/11
17/01/2021 Gmail - [Just JavaScript] 02. The JavaScript Universe
I’m standing on a small asteroid — it is the code of my program.
On its surface, I see the if statements and variable declarations, commas, curly braces, and all the other things one might find in the JavaScript code.
My code contains instructions like “make a function call” or “do this thing many times”, or even “throw an error”. I walk through these instructions step by step — running errands from my small asteroid.
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 my 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.
Back to values. Broadly, there are two kinds of them.
Primitive Values
Primitive Values are numbers and strings, among other things. Open your browser's console and print these primitive values using console.log():
console.log(2);
console.log("hello");
console.log(undefined);
All primitive values have something in common. There’s nothing I can do in my code that would affect them. This sounds a bit vague, so we’ll explore what this means concretely in the next module. For now, I’ll say that primitive values are like stars — cold and distant, but always there when I need them.
That’s the first kind of values.
Objects and Functions
Objects and Functions are also values, but they are not primitive. This makes them very special. Go ahead and log a few of them to the browser console:
console.log({});
console.log([]);
console.log(x => x * 2);
Notice how the browser console displays them differently from the primitive values. Some browsers might display an arrow before them, or do something special when you click them. If you have a few different browsers installed (e.g. Chrome and Firefox), compare how they visualize objects and functions.
Objects and functions are special because I can manipulate them from my code. For example, I can connect them to other values. This is rather vague — so we’ll refine this idea in a later module. For now, I can say that if primitive values are like distant stars, then objects and functions are more like rocks floating nearby my code. They’re close enough that I can manipulate them.
And that’s the second kind of values.
You might have questions. Good. If you ask a question, the JavaScript universe might answer it! Provided, of course, that you know how to ask.
Expressions
There are many questions JavaScript can’t answer. If you want to know whether it’s better to confess your true feelings to your best friend or to keep waiting until you both turn into skeletons, JavaScript won’t be of much help.
But there are some questions that JavaScript would be delighted to answer. These questions have a special name — they are called expressions.
If we “ask” the expression 2 + 2, JavaScript will “answer” with the value 4.
console.log(2 + 2); // 4
Expressions are questions that JavaScript can answer. JavaScript answers expressions in the only way it knows how — with values.
If the word “expression” confuses you, think of it as a piece of code that expresses a value. You might hear people say that 2 + 2 “results in” or “evaluates to” 4. These are all different ways to say the same thing.
We ask JavaScript 2 + 2, and it answers with 4. Expressions always result in a single value. Now we know enough about expressions to be dangerous!
I previously said that there are many types of JavaScript values: numbers, strings, objects, and so on. How do we know any particular value’s type?
This sounds like a question. Do we dare to ask it?
Checking a Type
At first, all values in the JavaScript cosmos might look the same — bright dots in the sky. But if you look closely, you’ll realize there are fewer than ten different types of values. Values of the same type behave in similar ways.
If we want to check a value’s type, we can ask it with the typeof operator. JavaScript will answer our question with one of the predetermined string
17/01/2021 Gmail - [Just JavaScript] 02. The JavaScript Universe values, such as "number", "string", or "object".
Below are a few examples you can try in the browser console:
console.log(typeof(2)); // "number"
console.log(typeof("hello")); // "string" console.log(typeof(undefined)); // "undefined"
Here, typeof(2) is an expression — and it results in the "number" value.
Strictly saying, using parens isn’t required with typeof. For example, typeof 2 would work just as fine as typeof(2). However, sometimes parens are required to avoid an ambiguity. One of the cases below would break if we omitted the parens after typeof. Try to guess which one it is:
console.log(typeof({})); // "object"
console.log(typeof([])); // "object"
console.log(typeof(x => x * 2)); // "function" You can verify your guess in the browser console.
Now take another look at the last three examples — this time with close attention to their results. Did you find any of these results surprising? Why?
Types of Values
As an aspiring astronomer, you might want to know about every type of value that can be observed in the JavaScript sky. After almost twenty five years of studying JavaScript, the scientists have only discovered nine such types:
Primitive Values
Undefined (undefined), used for unintentionally missing values. Null (null), used for intentionally missing values.
Booleans (true and false), used for logical operations.
Numbers (-100, 3.14, and others), used for math calculations. Strings ("hello", "abracadabra", and others), used for text. Symbols (uncommon), used to hide implementation details. BigInts (uncommon and new), used for math on big numbers.
Objects and Functions
Objects ({} and others), used to group related data and code. Functions (x => x * 2 and others), used to refer to code.
No Other Types
You might ask: “But what about other types I have used, like arrays?”
In JavaScript, there are no other fundamental value types other than the ones we have just enumerated. The rest are all objects! For example, even arrays, dates, and regular expressions fundamentally are objects in JavaScript:
console.log(typeof([])); // "object"
console.log(typeof(new Date())); // "object" console.log(typeof(/(hello|goodbye)/)); // "object"
“I see,” you might reply, “this is because everything is an object!” Alas, this is a popular urban legend, but it’s not true. Although code like "hi".toUpperCase() makes "hi" seem like an object, this is nothing but an illusion. JavaScript creates a wrapper object when you do this, and then immediately discards it.
It’s fine if this mechanism doesn’t quite click yet. For now, you only need to remember that primitive values, such as numbers and strings, are not objects.
Recap
Let’s recap what we know so far:
-
There are values, and then there’s everything else. We can think of values as different things “floating” in our JavaScript universe. They don’t exist inside our code, but we can refer to them from our code.
-
There are two categories of values: there are Primitive Values, and then there are Objects and Functions. In total, there are nine separate types. Each type serves a specific purpose, but some are rarely used.
-
Some values are lonely. For example, null is the only value of the Null type, and undefined is the only value of the Undefined type. As we will learn later, these two lonely values are quite the troublemakers!
-
We can ask questions with expressions. JavaScript will answer to us with values. For example, the 2 + 2 expression is answered with 4.
-
We can inspect the type of something by wrapping it in a typeof expression. For example, typeof(4) is the string value "number".
Exercises
Now it’s time to put what we learned to action.
Even if you already have a decent amount of experience with JavaScript don't skip the exercise questions! I personally learned some of these things only a few years ago.
Click here to answer these questions and provide feedback about this module. When you complete the exercises I will send the next module right away.
Next up we will explore the Primitive Values in more detail. We look at what these different primitive types like numbers and Null have in common, and learn a thing or two about what equality means in JavaScript.
We will also continue to refine our mental model. This module presents a crude sketch — an approximation. We will focus on different parts of the picture and fill them in with more details, like a progressive JPEG image.
These might seem like small steps, but we’re laying the foundation for
everything else to come. We’re building the JavaScript universe, together.
Javascript Mental Models by Dan Abramov 1
- Mental Models
3 messages
Dan Abramov
Read this code:
let a = 10;
let b = a;
a = 0;
What are the values of a and b after 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 attention to what’s
happening in your head, step by step. You might notice a monologue like this: let a = 10;
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 attention 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 setting 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” into which you can put stuff. Even if you don’t vividly imagine boxes anymore when you see a variable, they might still behave “boxy” 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
https://mail.google.com/mail/u/0?ik=45698ed0cc&view=pt&search=all&permthid=thread-f%3A1671730157188904350&simpl=ms… 2/6
17/01/2021 Gmail - [Just JavaScript] 01. Mental Models
These intuitions (like boxiness of variables) influence how we read code our whole lives. But sometimes, our mental models are wrong. Maybe a tutorial we read early on has sacrificed correctness for the ease of explaining. Maybe we incorrectly transferred an intuition about a particular language feature, like this, from another language we learned earlier. Maybe we inferred a mental model from some piece of code and never really verified if 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 help you find and fix bugs faster, understand other people’s code better, and feel confident in the code you write.
(By the way, a being 0 and b being 10 is the correct answer.)
Coding, Fast and Slow
“Thinking, Fast and Slow” by Daniel Kahneman is a widely popular non-fiction book. Its central thesis is that humans use two different “systems” when thinking.
Whenever we can, we rely on the “fast” system. We share this system with many animals, and that gives us amazing powers like walking without falling all the time. This “fast” system is good at pattern matching (necessary for survival!) and “gut reactions”. But it’s not good at planning.
Uniquely, thanks to the development of 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.
https://mail.google.com/mail/u/0?ik=45698ed0cc&view=pt&search=all&permthid=thread-f%3A1671730157188904350&simpl=ms… 3/6
17/01/2021 Gmail - [Just JavaScript] 01. Mental Models
Imagine that you’re in the middle of a lot of work, and you want to quickly identify what this function does. Take a quick look 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 though!) 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. But now that you know a bug exists, will you read the code differently? If you’ve been reading code in the “fast” mode, it’s likely you’ll switch to the
https://mail.google.com/mail/u/0?ik=45698ed0cc&view=pt&search=all&permthid=thread-f%3A1671730157188904350&simpl=ms… 4/6
17/01/2021 Gmail - [Just JavaScript] 01. Mental Models
more laborious “slow” mode to find it.
In the “fast” mode, we guess what the code does based on naming,
comments, and its overall structure. In the “slow” mode, we retrace what the
code does step by step.
That’s why having a correct mental model is so important. Simulating a
computer in our heads is hard enough — and this effort is wasted with wrong mental models.
Don’t worry if you can’t find the bug at all. This 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 see this bug plain as day.
In the next module, we'll start building mental models for some of the most
fundamental JavaScript concepts — values and variables.
Please click here to send feedback and complete a short survey about this
module.
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.