Values and variables

JavaScript Types

JavaScript does have types: learn the primitive types like number, string, boolean, symbol, null and undefined, plus object types, and how typeof works.

Every value in JavaScript has a type. The language gives you a small set of primitive types and one catch-all object type for everything else.

Primitive types

Primitive types are:

Plus two special primitives:

  • null
  • undefined

Numbers

Internally, JavaScript stores every number as a float.

A numeric literal is a number written in source code. It can be an integer or a float.

Integers:

10
5354576767321
0xCC //hex

Floats:

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

Run typeof 42 in the console. You get 'number'.

Strings

A string is a sequence of characters. Write a string literal in single or double quotes:

'A string'
"Another string"

Split a string across lines with a backslash:

"A \
string"

Escape sequences work inside strings. \n adds a new line. Escape a quote when the string uses the same quote style:

'I\'m a developer'

Join strings with +:

"A " + "string"

Template literals

Template literals use backticks and landed in ES2015:

const a_string = `something`

Embed any expression:

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

Multiline strings need no escape:

`a string
with
${something}`

Booleans

JavaScript has two boolean literals: true and false.

Comparisons like ==, ===, <, and > return booleans. So do if and while conditions.

They also accept truthy and falsy values. Falsy values behave like false:

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

Everything else is truthy, including '0' and empty arrays.

null

null means “no value here on purpose”. Other languages call this nil or None in Python.

undefined

undefined means a variable exists but has no assigned value yet. Functions with no return also yield undefined. Missing parameters are undefined too.

Check for undefined with:

typeof variable === 'undefined'

Object types

Anything that is not a primitive is an object type. Objects have properties and methods.

Arrays and functions are objects under the hood.

How to find the type of a variable

Use typeof to get a string name for the type:

typeof 1 === 'number'
typeof '1' === 'string'
typeof {name: 'Flavio'} === 'object'
typeof [1, 2, 3] === 'object'
typeof true === 'boolean'
typeof undefined === 'undefined'
typeof (() => {}) === 'function'

JavaScript has no separate function type in the type system. typeof returns 'function' anyway. That is a long-standing convenience, not a separate category.

Lesson completed