Types and Values

Programs work by manipulating values. A value could be a number (e.g. 3.14), a string (e.g. "Hello"), and many more.

All values have a type. A type can be categorized as either primitive type or object type.

Primitive types

Primitive types include number, string, boolean, null, undefined, and Symbol (ES6).

With the exception of Symbol, they each have their own literal notation, which means you can write their values directly inside your scripts.

Properties of primitive values:

  • immutable their values cannot be changed (you cannot change a primitive value),
  • compared by value two primitive values are the same if their values are the same.

Numbers

This represents integers and floating-point numbers, as well as the special Infinity and NaN (Not a Number) values.

If you want, you can use _ (underscores) as digit separators: e.g. 360_000_000, 3.1415_9265, or 0xAABD_CC97_DD01.

Integers

1
-2

// Using HEXADECIMAL (x) notation
0xFF //=> 255
// Using BINARY (b) notation
0b101 //=> 5
// Using OCTAL (o) notation
0o377 //=> 255

// BigInt (ES2021), see the 'n' suffix
1000000000n
0b1101010001000n
0x123FF000000000000n

Floating-point numbers

0.5123
-0.1

// Using scientific notation
6.02e23 //=> 6.02 * 10^23
1.47e-32 //=> 1.47 * 10^(-32)

Infinity

Infinity (or -Infinity) is the result when overflow occurs, or when you try to divide a non-zero number with zero.

NaN

NaN (Not a Number) is the result when you try to calculate 0/0, Infinity/Infinity, the square root of a negative number, or when you try to do an arithmatic operation with values that can't be converted to numbers.

Strings

Strings represent texts. Javascript uses the UTF-16 encoding (so JavaScript strings are sequences of unsigned 16-bit values). Note that strings in JavaScript are immutable.

String literals

You can define strings using ' (single-quotes), " (double-quotes), or ` (backticks). See Escape character on how to escape special characters in the string.

// Using ' or " is a matter of preference
'I\'m a string'
"So do I"
// With `, your string can span multiple lines
`With me, you can span
multiple lines`

Template literals

When you define a string using `, you are creating a template literal. A template literal interprets anything inside it literally, including newlines.

You can insert a value inside a template literal using the ${...} syntax:

const name = 'Ferdinand';
const str = `Hello, ${name}!`;
console.log(str); //=> Hello, Ferdinand!

Booleans

Booleans represent true or false values.

true
false

null

Represents something defined but is "empty".

null

undefined

Represents something that is undefined.

undefined

Symbol

Symbols were introduced in ES6 "to serve as non-string property names" (Flanagan). There is no literal syntax for Symbol, so you will need to do Symbol() or Symbol('someString').

Note that each invocation of Symbol() (even with the same argument) will return a unique symbol value.

const obj = {};
const symbolA = Symbol('lorem-ipsum');
const symbolB = Symbol('lorem-ipsum');
obj[symbolA] = 1;
obj[symbolB] = 2;
console.log(obj[symbolA]); //=> 1
console.log(obj[symbolB]); //=> 2
console.log(symbolA === symbolB); //=> false

Object types

Anything that is not a primitive type is an object type. This includes Object, Array, Function, etc.

Object values are actually references to the physical object in the memory. When you re-assign an object value to a new variable, you are just copying the reference instead of the physical object's value.

Properties of object values:

  • mutable you can change their values (for example, you can change the properties of an object, or the elements of an array).
  • compared by reference Two object values are the same if they refer to the same object in the memory.
We will briefly discuss objects, arrays, and functions here. They will be explained in depth later.

Object

An object is an unordered collection of properties, each with a name and a value.

  • The property name could be a string or a Symbol
  • The property value could be any JavaScript value (including another object), or a getter and/or setter function.

The object literal

You can create an object using the {} notation.

const emptyObject = {};

const courseData = {
  name: 'Programming with JavaScript',
  description: 'Learn to code with',
  instructor: {
    firstName: 'John',
    lastName: 'Book',
    id: 12,
  },
};

console.log(emptyObject); //=> {}
console.log(courseData); //=> { name: ..., ... }

Using the new keyword

You can also create an object using the new keyword, followed by a constructor function.

const obj = new Object();
const arr = new Array();

Using the Object.create() function

Using Object.create() to create an object, you can control which prototype the object will inherit.

// The object will have no prototype
const obj1 = Object.create(null);
// Same as `{}` or `new Object()`
const obj2 = Object.create(Object.prototype);
// The object will have this object as prototype
const obj3 = Object.create({ a: 1, b: 2 });

// "Inherited properties" (from the prototype) are not
// "own properties", so these will all print '{}'
console.log(obj1); //=> {}
console.log(obj2); //=> {}
console.log(obj3); //=> {}

// But the "inherited properties" are actually there
console.log(obj3.a, obj3.b); //=> 1 2

Array

An array is an ordered list of values.

  • Each value is called an element, and its position in the array is called its index.
  • Index goes from 0 (the first element) up to 232 2 (4,294,967,294).
  • Arrays have a length property.

The array literal

You can create an array using the [] notation.

const emptyArray = [];
const elements = ['fire', 'water', 'metal', 'wood', 'earth'];
const mixedArray = [1, 2, [2, 'something'], { x: 7 }];

Using new Array()

You can also create an array using the new Array() constructor. It has different behaviors depending on the number of arguments you give.

// Without argument: the same as `[]`
const arr1 = new Array();
console.log(arr1);

// 1 argument: length of array
const arr2 = new Array(5);
console.log(arr2);
console.log(arr2.length); //=> 5

// 2+ arguments: elements of the array
const arr3 = new Array(1, 2, 3);
console.log(arr3); //=> [1, 2, 3]

Function

Functions are JavaScript codes that you declare once and can be called (invoked) multiple times. Note that the functions won't actually be run until you call them.

  • When you declare a function, you can specify their parameters, which behave like local variables of the function whose value will be decided when you call the function.
  • When you call a function, you provide the values (arguments) for the parameters.
  • You may use the return keyword inside a function to return a value (exit the function with the given value).

Declaring a function with the function keyword

You can declare a function with the function keyword. A function declared with the function keyword has their own this variable.

  • You may provide the name of the function after the function keyword, before the open paranthesis
  • You may provide the parameters between the ( and ), separated by ,
// Function definition with name and parameters
function multiply(a, b) {
  return a * b;
}

// Barebone function definition
// (We assign it to a variable so you can call it later)
const printHello = function () {
  console.log('Hello world!');
};

Declaring a function with the arrow function notation

You can create a "lambda" (anonymous) function with the arrow function notation (=>). Functions declared with the arrow function notation does NOT have its own this variable.

// With parameters
const multiply = (a, b) => {
  return a * b;
};

// Without parameters
const printHello = () => {
  console.log('Hello world!');
};

If the arrow function only returns a single expression, you can simply write the return expression after the =>, without the curly braces.

// Equivalent to the `multiply` function above
const multiply = (a, b) => a * b;

// If you want to return an object, surround it with ()
const getObj = () => ({ a: 1, b: 2 });

Calling a function

There are multiple ways to call a function in JavaScript.

The most common way is to specify the function's name (or an expression that evaluates to the function's reference) and append it with (), potentially specifying the arguments between the ( and ).

// Example with named function
function multiply(a, b) {
  return a * b;
}
const result = multiply(5, 6);
console.log(result); //=> 30

// Example with unnamed function
const printHello = () => {
  console.log('Hello world!');
}
printHello(); //=> Hello world!

References

  • JavaScript: The Definitive Guide, 7th Edition (David Flanagan)Chapter 3. Types, Values, and Variables
  • JavaScript: The Definitive Guide, 7th Edition (David Flanagan)Chapter 6. Objects
  • JavaScript: The Definitive Guide, 7th Edition (David Flanagan)Chapter 7. Arrays
  • JavaScript: The Definitive Guide, 7th Edition (David Flanagan)Chapter 8. Functions