Primitive types

Primitive types are

  • Numbers
  • Strings
  • Booleans

And two special types:

  • null
  • undefined

Let’s see them in detail in the next sections.

Numbers

Internally, JavaScript has just one type for numbers: every number is a float.

A numeric literal is a number represented in the source code, amd depending on how it’s written, it can be an integer literal or a floating point literal.

Integers:

10
5354576767321
0xCC //hex

Floats:

3.14
.1234
5.2e4 //5.2 * 10^4

Strings

A string type is a sequence of characters. It’s defined in the source code as a string literal, which is enclosed in quotes or double quotes

'A string'
"Another string"

Strings can span across multiple lines by using the backslash

"A \
string"

A string can contain escape sequences that can be interpreted when the string is printed, like \n to create a new line. The backslash is also useful when you need to enter for example a quote in a string enclosed in quotes, to prevent the char to be interpreted as a closing quote:

'I\'m a developer'

Strings can be joined using the + operator:

"A " + "string"

Template strings

Introduced in ES2015, template strings are string literals that allow a more powerful way to define strings.

`a string`

You can perform string substitution, embedding the result of any JS expression:

`a string with ${something}`
`a string with ${something+somethingElse}`
`a string with ${obj.something()}`

You can have multiline strings easily:

`a string
with
${something}`

Booleans

JavaScript defines two reserved words for booleans: true and false. Many comparision operations == === < > (and so on) return either one or the other.

if, while statements and other control structures use booleans to determine the flow of the program.

They don’t just accept true or false, but also accept truthy and falsy values.

Falsy values, values interpreted as false, are

0
-0
NaN
undefined
null
'' //empty string

All the rest is considered a truthy value.

null

null is a special value that indicates the absence of a value.

It’s a common concept in other languages as well, can be known as nil or None in Python for example.

undefined

undefined indicates that a variable has not been initialized and the value is absent.

It’s commonly returned by functions with no return value. When a function accepts a parameter but that’s not set by the caller, it’s undefined.

To detect if a value is undefined, you use the construct:

typeof variable === 'undefined'

Object types

Anything that’s not a primitive type is an object type.

Functions, arrays and what we call objects are object types. They are special on their own, but they inherit many properties of objects, like having properties and also having methods that can act on those properties.