Discover Functional JavaScript was named one of thebest new Functional Programming ebooks by BookAuthority!

JavaScript has primitives, objects and functions. All of them are values. All are treated as objects, even primitives.

Primitives

Number, boolean, string, undefined and null are primitives.

Number

There is only one number type in JavaScript, the 64-bit binary floating point type. Decimal numbers’ arithmetic is inexact.

As you may already know, 0.1 + 0.2 does not make 0.3 . But with integers, the arithmetic is exact, so 1+2 === 3 .

Numbers inherit methods from the Number.prototype object. Methods can be called on numbers:

(123).toString();  //"123"(1.23).toFixed(1); //"1.2"

There are functions for converting strings to numbers : Number.parseInt(), Number.parseFloat() and Number():

Number.parseInt("1")       //1Number.parseInt("text")    //NaNNumber.parseFloat("1.234") //1.234Number("1")                //1Number("1.234")            //1.234

Invalid arithmetic operations or invalid conversions will not throw an exception, but will result in the NaN “Not-a-Number” value. Number.isNaN() can detect NaN .

The + operator can add or concatenate.

1 + 1      //2"1" + "1"  //"11"1 + "1"    //"11"

String

A string stores a series of Unicode characters. The text can be inside double quotes "" or single quotes ''.

Strings inherit methods from String.prototype. They have methods like : substring(), indexOf() and concat() .

"text".substring(1,3) //"ex""text".indexOf('x')   //2"text".concat(" end") //"text end"

Strings, like all primitives, are immutable. For example concat() doesn’t modify the existing string but creates a new one.

Boolean

A boolean has two values : true and false .
The language has truthy and falsy values.
false, null, undefined, ''(empty string), 0 and NaN are falsy. All other values, including all objects, are truthy.

The truthy value is evaluated to true when executed in a boolean context. Falsy value is evaluated to false. Take a look at the next example displaying the false branch.

let text = '';if(text) {  console.log("This is true");} else {  console.log("This is false");}

The equality operator is ===. The not equal operator is !== .

Variables

Variables can be defined using var, let and const.

var declares and optionally initializes a variable. Variables declared with var have a function scope. They are treated as declared at the top of the function. This is called variable hoisting.

The let declaration has a block scope.

The value of a variable that is not initialize is undefined .

A variable declared with const cannot be reassigned. Its value, however, can still be mutable. const freezes the variable, Object.freeze() freezes the object. The const declaration has a block scope.

Objects

An object is a dynamic collection of properties.

The property key is a unique string. When a non string is used as the property key, it will be converted to a string. The property value can be a primitive, object, or function.

The simplest way to create an object is to use an object literal:

let obj = {  message : "A message",  doSomething : function() {}}

There are two ways to access properties: dot notation and bracket notation. We can read, add, edit and remove an object’s properties at any time.

  • get: object.name, object[expression]
  • set: object.name = value, object[expression] = value
  • delete: delete object.name, delete object[expression]
let obj = {}; //create empty objectobj.message = "A message"; //add propertyobj.message = "A new message"; //edit propertydelete obj.message; //delete property

Objects can be used as maps. A simple map can be created using Object.create(null) :

let french = Object.create(null);french["yes"] = "oui";french["no"]  = "non";french["yes"];//"oui"

All object’s properties are public. Object.keys() can be used to iterate over all properties.

function logProperty(name){  console.log(name); //property name  console.log(obj[name]); //property value}
Object.keys(obj).forEach(logProperty);

Object.assign() copies all properties from one object to another. An object can be cloned by copying all its properties to an empty object:

let book = { title: "The good parts" };let clone = Object.assign({}, book);

An immutable object is an object that once created cannot be changed. If you want to make the object immutable, use Object.freeze() .

Primitives vs Objects

Primitives (except null and undefined) are treated like objects, in the sense that they have methods but they are not objects.

Numbers, strings, and booleans have object equivalent wrappers. These are the Number, String, and Boolean functions.

In order to allow access to properties on primitives, JavaScript creates an wrapper object and then destroys it. The process of creating and destroying wrapper objects is optimized by the JavaScript engine.

Primitives are immutable, and objects are mutable.

Array

Arrays are indexed collections of values. Each value is an element. Elements are ordered and accessed by their index number.

JavaScript has array-like objects. Arrays are implemented using objects. Indexes are converted to strings and used as names for retrieving values.

A simple array like let arr = ['A', 'B', 'C'] is emulated using an object like the one below:

{  '0': 'A',  '1': 'B',  '2': 'C'}

Discover Functional JavaScript was named one of the best new Functional Programming ebooks by BookAuthority!

For more on applying functional techniques to React take a look at Functional React.

Learn how to apply the Principles of Design Patterns.

You can find me on Medium and Twitter.