2. Data Types & Variables
Table of Contents:
Summary
Data types are categories of values in JavaScript. There are 5 primitive types (String, Number, Boolean, undefined, null) and 3 reference types (Object, Array, Function). Knowing the type of a value helps determines how you can use that value. Choosing the right type to represent your data is essential.
Operators are symbols (e.g.
+,>=,&&) that generate new data from existing values. Arithmetic, comparison, and logical operators allow you to perform calculations and make decisions.Type coercion is the process of converting a value from one data type to another, sometimes automatically. Values can be "truthy" or "falsy" depending on their content.
Variables are named containers for data. You can reference and reassign variables to store and update information in your program.
There are four ways to declare variables:
const(preferred for values that don't change),let(for values that do change),var(legacy, avoid using), and global variables (avoid using).
Scope refers to where a variable is declared. It impacts the "reachability" of the variable (where it can be referenced).
Hoisting allows some variables and functions to be referenced before they are declared, which can lead to confusing bugs. Prefer
constandletto avoid hoisting
Computation is All About Data
Every computational device, even the earliest device the abacus, is used to manipulate and generate data.

Our modern computers, while much more powerful, are still oriented around this singular goal: manipulating and generating data.
What has changed and evolved over time is what we do with those calculations and how quickly our devices can perform them. Here are some modern applications of how our computers make use of data:
Rendering images & video: Calculating pixel positions, color values, and frame rates turns raw math into Netflix streams and 3D games.
Navigation systems: Continuous GPS data (latitude/longitude as numbers) is transformed into live maps, directions, and traffic updates.
Social media: Posts are stored as text data, likes as counts, and relationships as graph data — powering your feed and recommendations.
Online shopping: Prices (numbers), product info (strings), and cart contents (arrays of objects) are combined to let you browse, compare, and buy.
Music & audio: Sound waves are stored as numerical data, then processed and streamed as songs, podcasts, and phone calls.
Healthcare & fitness apps: Heart rate, steps, and sleep cycles (all data points) are tracked and analyzed to monitor your health.
Artificial intelligence: Images, text, or speech are converted into numbers (vectors, matrices) that models process to recognize faces, generate text, or translate languages.
In this lesson, we'll learn about the different types of data, how our computers store data in variables, and then the many ways that we can compute new data.
Data Types
All values have a data type that determines what you can do with that value.
For example, you can use numbers to perform mathematical calculations and can use strings to construct messages. Knowing the different data types allows you to choose the best data type for your particular use case.
There are five main primitive data types: Number, String, Boolean, undefined, and null
String
"hello" or '@abc123'
Text (any sequence of characters)
Usernames, chat messages, product descriptions, search queries
Number
50 or 10.5 or -2
Numeric values
Scores in a game, count of likes on a post, timers
Boolean
true or false
Truth value
Login status, feature toggles (dark mode on/off), win/lose conditions
Undefined
undefined
A variable that has been declared but not yet given a value
“Not yet set” values
Null
null
Intentional absence of a value
Representing “no result”
There are also three reference data types: Objects, Arrays, and Functions.
Object
{ name: "Alex", age: 25 }
A collection of data relating to one "thing"
Storing user profile data, storing data about product (name, description, price, etc...)
Array
[ "apple", "banana", "cherry" ]
An ordered list of similar values
Storing lists (shopping cart items, game high scores, chat messages)
Function
function greet() { console.log("Hi!"); }
A reusable block of code
Performing actions, handling events, calculations
Operators
Now that we know the types of data, let's use our computers to generate data with operators!
An operator is a symbol that uses data values to generate a new piece of data, forming an expression:
Let's start by reviewing the basic categories of operators: arithmetic, comparison, and logical.
Challenge: Can you tell what each expression will produce?
Ternary Operator
The ternary operator boolExpression ? valA : valB produces one of two values based on the boolExpression value:
valAis produced if theboolExpressionevaluates totruevalBis produced if theboolExpressionevaluates tofalse
typeof Operator
The typeof operator returns the type of a given value as a string.
Resolution Order of Operations
Operators can be combined to form complex expressions. In these cases, understanding the order in which operators are evaluated — also called operator precedence — is crucial.
Let's look at this code snippet as an example, what is the value of result?:
Below is the order of precedence:
Function calls are evaluated first
Then arithmetic operators.
*,/,%are evaluated before+and-.Followed by comparison operators. Relational operators (
<,<=,>,>=) are evaluated before equality operators (===,!==,==,!=)Then logical operators. AND (
&&) has higher precedence than logical OR (||).Ternary operator (
x ? y :z) and assignment happens last (=)
Parentheses () can always be used to override the default order and make the evaluation order explicit.
Challenge: what values are produced by the code snippet below?
Type Coercion & Truthy vs. Falsy
We can "coerce" a value of one data type to become another data type using type casting functions:
In some cases, type coercion happens automatically, potentially without us knowing.
For example, what is the result of the expression below? What data type is produced? Do you think we should even be allowed to do something like this?
Variables
A Variable in JavaScript is a named container for data. By labeling our data, variables enable us to perform a series of computations in a program and "save" our progress along the way. Descriptive variable names dramatically improve the readability of our code.
Consider the two approaches below to produce the same result. The first does not use variables while the second does. What are the tradeoffs of each approach?
Approach 1: No Variables
Approach 2: Variables
Using Variables: Declare, Assign, Reference
There are three things we can do with variables:
Create a new variable ("declare the variable"). Use
letorconst.Give the variable a new value to hold ("assign the variable a value"). Only possible with
letvariables.Use the value held by the variable ("reference the variable")
We can even reference the current value of a variable to calculate the new value we assign to it:
Scope
Scope refers to where a variable is declared. The scope of the variable impacts the "reachability" of the variable (where it can be referenced).
For example, a variable declared in the scope of a function can only be referenced within that function. It is not reachable outside of the function.
Variables can be declared at the following levels of scope, listed from the least reachability to the most reachability:
Block-Scoped Variables — Variables declared within a "block statement"
{}(e.g.if,if else,else,for,while, etc...).Function-Scoped Variables — Variables and parameters declared within a function.
Module-Scoped Variables — Variables declared within a file and outside of any function.
Global-Scoped Variables — Variables provided by the runtime environment (Node, the Browser). These are things like the
globalandwindowobjects. Avoid adding data to these objects.
Scopes can contain other scopes. For example, a file can contain a function that has an if block statement inside. Variables declared in the "outer" scope can be referenced anywhere within the "inner" scopes, but not vice-versa.
When a variable that is out of scope is referenced, a ReferenceError is thrown.
The Four Ways To Declare Variables
There are 4 ways to declare a new variable, but only the first two of should be used:
constdeclares a block-scoped variable that cannot be reassigned. This should be your go-to variable declaration.letdeclares a re-assignable block-scoped variable. Use only when reassignment is necessary.vardeclares a re-assignable, hoisted, function-scoped variable. Do not usevar. Hoisting and function-scoped variables can cause unexpected behavior (read more below).Global-scoped variables are declared without a keyword. Do not use global variables.
Hoisting: Why We Don't Use var
varHoisting is a feature of JavaScript that allows certain variables/functions to be referenced before they are declared.
Variables declared with the
varkeyword and Functions declared with thefunctionkeyword are hoisted.Variables declared with
constorletand Arrow Functions are NOT hoisted.Variables declared with
varwill be given the valueundefineduntil their assignment statement is reached.Functions declared with
functionare fully invoke-able anywhere within their scope.
Last updated