Basics
If you are new to programming, there is a beginner's guide to help align your priorities and expectations.
If you already know JavaScript, the new information starts at the introduction to types. The most efficient way to learn is by reading carefully, clicking the button when you see it, modifying the code examples, and clicking the button again.
The console
The console.log
function displays a value.
A value is a unit of information, like the single number 42
. Click the button to see what this program does.
A function is an action that your computer knows how to perform. You can instruct the computer to perform any known function with a function call statement. Notice the parentheses ((
and )
) around the value, and the comma between values if there is more than one.
console.log
multiple valuesTry experimenting with the program below, which tells the computer to display some numbers and do some simple math.
Notice that the name of a function must match exactly, otherwise you will encounter a compilation error.
Strings
A string
is a sequence of characters.
It can be a word like "Hello"
, a number like "42"
, or an entire book. Strings are enclosed in quotation marks - either "
or '
, as long as it is consistent.
Every string has a set of known actions it can perform on its own characters. The simplest of these actions, like converting to upper/lower case, do not require any input.
Notice the similarity and differences between this function call and console.log
above. Even though the function does not expect any input, we must still include an open and close parentheses (()
) after the function name to call it.
To create a string that contains multiple lines of text, use the backtick `
operator.
You can join strings to other values with the +
operator.
It is often important to include spaces within a string when concatenating them (i.e. joining them in order).
When console.log
receives multiple inputs, it will display them with a single space separator.
When using an operator like +
, your computer follows standard left-to-right order of operations to produce the result,
so you may also want to use parentheses ((
and )
).
Variables
A variable is a named container for a value.
There are three ways to define a variable - var
, let
, and const
. The const
keyword is used for constant values that will not change.
Changing the value of a const
will produce an error.
TypeScript programs (and most modern JavaScript programs) tend to favor using let
and const
over var
, due
to various unintended behaviors that var
can cause. For example, var
allows a variable to be declared more than once.
Attempting to use let
to redeclare a variable of the same name will produce an error.
Questions
Types
Similar to how you can create a container for a value with let
or const
, TypeScript allows you to create a container for a data type with the type
keyword.
The name greeting
refers to an actual unit of information whose data type is string
. The name Salutation
refers to the data type string
, and only exists within the TypeScript compiler. When TypeScript compiles the program, it will only emit one line of code.
If you attempt to use a type as a value, the TypeScript compiler will produce an error.
You can even use the same name for a variable and for a type, although this is strongly recommended against for readability reasons.
To summarize this important distinction between data and types:
- Data is the actual information that exists - the 0's and 1's that your program manipulates when it runs.
- Types are metadata used by TypeScript to describe the shape or contract of data. They exist for the purpose of catching errors before your program runs, by enforcing certain rules during the compilation process.
Numbers
JavaScript stores numbers as floating point values.
This can create issues when dealing with decimal numbers, since the internal representation of the number can become slightly imprecise. Consider the classic example below, where you would expect the output to be exactly 0.3
.
You may also encounter floating point imprecision when subtracting, multiplying, and dividing decimal numbers.
This is the expected behavior by any system that implements the IEEE 754 standard for representing numbers in floating point.
Converting numbers to strings
To convert a number to a string with a fixed number of decimal places, use toFixed
.
The toPrecision
function returns a string with the specified number of significant digits, and toExponential
returns a string
in exponential notation with the given decimal precision.
You can also use toString
to produce a string representation of the number. The first argument of toString
is the
base to output in (default is base 10).
Infinity
and NaN
JavaScript has special values to represent infinity (Infinity
) and "not a number" (NaN
).
A common situation where NaN
arises in TypeScript programs is during the conversion of a string
value to number
.
Booleans
A boolean value is either true
or false
.
The most common way you will encounter a boolean is when it is produced by comparison of two other values.
Comparing for equality
There are two operators for comparing whether two values are equal in JavaScript: ==
and ===
.
The double equal sign is the loose equality operator, which checks if two values are equal after converting them to a common type.
The triple equal (===
) is the strict equality operator, which checks that two values are equal and of the same type without performing
any type conversions. If the values are different types, the comparison will return false
.
Comparing for inequality
The inverse to strict/loose equality is strict and loose inequality - !=
and !==
.
And operator
In the example below, the and operator (&&
) produces true
if both values are true
.
Unlike other programming languages, TypeScript allows you to use the &&
operator with any values, not just booleans. If both values are equivalent to true
, the value on the right is produced by the expression.
Certain values in JavaScript are equivalent to false
, like the number 0
or the empty string ""
(a string with no characters). These values are often referred to as falsy, while all other values are referred to as truthy. Try modifying the program below to discover which values are truthy and which ones are falsy.
Or operator
In the example below, the or operator (||
) produces true
if either boolean is true
.
Not operator
Ternary operator
A ternary expression produces one of two values based on whether a boolean is true
or false
.
If the boolean value is true
, the value left of the colon (:
) is produced. If the value is false
, the value right of the
colon is the result of the ternary expression.
A common programming pattern in JavaScript is to use boolean operators when conditionally operating on values.
A boolean value is produced by comparison operators like <
(less than) and >
(greater than).
Type annotations
One of the most commonly used features of TypeScript is its type annotations, where variables are annotated with the data type of the information they contain.
const pi: number = 3.1415926535
let found: boolean = false
By adding type annotations, TypeScript can use type inference to detect a wide variety of situations where a valid JavaScript program would encounter runtime errors.
Notice that even without type annotations, TypeScript will use type inference to determine the data types of variables and functions.
There is also a special type any
which can be applied to a variable whose data type is unknown. This means TypeScript
will be unable to detect an error in the same program as above, but the program will produce a runtime error when it is executed.
TypeScript helps you prevent runtime errors by exposing a wide range of potential issues as compilation errors, which can be addressed during the development process rather than as a bug fix later on.
Comments
It is standard programming practice to leave human-readable comments.
This helps other programmers understand what you've written. A comment either starts with //
and continues to the end of the line, or encloses all the text between the special character sequence /*
and */
.
Notice there is one ray of the sun in the image above which is not print out, and it appears in a different color when we see it as code. This is because the backward slash (\
) is an escape character, which allows us to represent certain special characters like the new line character (\n
).
Syntax
A programming language's syntax is similar to the grammatical structure of a spoken language. In English, words are expected to be in a certain order ("I like apples", not "Apples I like"). Certain words like "I" are expected to be capitalized a certain way, and sentences are expected to end with a period (.
).
In TypeScript, the semicolon (;
) is an explicit indicator for the end of an instruction.
Notice the third line in the program above doesn't have a semicolon. In most situations, a line break will be interpreted as the end of an instruction - this is called Automatic Semicolon Insertion (ASI).
The examples on this site tend to not use semicolons for the sake of clarity and readability. However, there are several situations where a semicolon is required for correctness, such as the program below.
The expression 42(1 + 1)...
is being interpreted as a function call of a nonexistent function named 42
. This is because it is perfectly valid to write a console.log
instruction like this:
In the vast majority of TypeScript programs, you will find semicolons at the end of every line. Most professional codebases and big companies require them. At the end of the day, semicolon usage is a matter of stylistic preference - what is most important to understand is that there are situations where a semicolon is absolutely necessary.
JavaScript Object Notation
JSON is a widely used format for exchanging data that is used in JavaScript programs.
When a program stores structured data or requests information from a web server, the response will often be formatted in JSON.
The JSON.parse
function allows you to decode a JSON-formatted string into JavaScript values like string
, number
, and boolean
,
while the JSON.stringify
function converts a JavaScript value into a JSON-formatted string.
Since TypeScript cannot infer the actual data types that will be generated by parsing a JSON string, the result of JSON.parse
has the type any
.
If you are sure about the data type contained in a JSON string, you can use the as
keyword to apply a type to the result.
If your assumption is incorrect, your program will encounter the same runtime error that the same JavaScript program would encounter.
As you encounter other data types of TypeScript, this cursory introduction to JSON.parse
and JSON.stringify
will be expanded to include details
on how those data types should be parsed and stringified.
Null and undefined
There are two values that represent the idea of a "nonexistent value" - null
and undefined
. While they can (for the most part) be used interchangeably, there are notable differences between them.
There are many situations where you want null
or undefined
values to evaluate to exactly false
, and all other values to evaluate to true
. In such situations, you can use the not operator (!
) twice to effectively "double invert" a value into a boolean.
Checking a data type
Programs often deal with information where some data types are unknown. For example, with JSON.parse
, the value produced from the transformation depends on the input string which usually comes from an external source.
The typeof
operator produces a string that indicates a value's data type.
Notice that typeof undefined
produces the string "undefined"
, but typeof null
produces the string "object"
. This is actually the expected behavior!