Using classes - JavaScript

Using classes
=============

* « Previous
* Next »

JavaScript is a prototype-based language — an object's behaviors are specified by its own properties and its prototype's properties. However, with the addition of classes, the creation of hierarchies of objects and the inheritance of properties and their values are much more in line with other object-oriented languages such as Java. In this section, we will demonstrate how objects can be created from classes.

In many other languages, *classes*, or constructors, are clearly distinguished from *objects*, or instances. In JavaScript, classes are mainly an abstraction over the existing prototypical inheritance mechanism — all patterns are convertible to prototype-based inheritance. Classes themselves are normal JavaScript values as well, and have their own prototype chains. In fact, most plain JavaScript functions can be used as constructors — you use the `new` operator with a constructor function to create a new object.

We will be playing with the well-abstracted class model in this tutorial, and discuss what semantics classes offer. If you want to dive deep into the underlying prototype system, you can read the Inheritance and the prototype chain guide.

This chapter assumes that you are already somewhat familiar with JavaScript and that you have used ordinary objects.

Overview of classes
-------------------

If you have some hands-on experience with JavaScript, or have followed along with the guide, you probably have already used classes, even if you haven't created one. For example, this may seem familiar to you:

```js
const bigDay = new Date(2019, 6, 19);
console.log(bigDay.toLocaleDateString());
if (bigDay.getTime() < Date.now()) {
  console.log("Once upon a time...");
}
```

On the first line, we created an instance of the class `Date`, and called it `bigDay`. On the second line, we called a method `toLocaleDateString()` on the `bigDay` instance, which returns a string. Then, we compared two numbers: one returned from the `getTime()` method, the other directly called from the `Date` class *itself*, as `Date.now()`.

`Date` is a built-in class of JavaScript. From this example, we can get some basic ideas of what classes do:

* Classes create objects through the `new` operator.
* Each object has some properties (data or method) added by the class.
* The class stores some properties (data or method) itself, which are usually used to interact with instances.

These correspond to the three key features of classes:

* Constructor;
* Instance methods and instance fields;
* Static methods and static fields.
Declaring a class
-----------------

Classes are usually created with *class declarations*.

```js
class MyClass {
  // class body...
}
```

Within a class body, there are a range of features available.

```js
class MyClass {
  // Constructor
  constructor() {
    // Constructor body
  }
  // Instance field
  myField = "foo";
  // Instance method
  myMethod() {
    // myMethod body
  }
  // Static field
  static myStaticField = "bar";
  // Static method
  static myStaticMethod() {
    // myStaticMethod body
  }
  // Static block
  static {
    // Static initialization code
  }
  // Fields, methods, static fields, and static methods all have
  // "private" forms
  #myPrivateField = "bar";
}
```

If you came from a pre-ES6 world, you may be more familiar with using functions as constructors. The pattern above would roughly translate to the following with function constructors:

```js
function MyClass() {
  this.myField = "foo";
  // Constructor body
}
MyClass.myStaticField = "bar";
MyClass.myStaticMethod = function () {
  // myStaticMethod body
};
MyClass.prototype.myMethod = function () {
  // myMethod body
};

(function () {
  // Static initialization code
})();
```

**Note:** Private fields and methods are new features in classes with no trivial equivalent in function constructors.

### Constructing a class

After a class has been declared, you can create instances of it using the `new` operator.

```js
const myInstance = new MyClass();
console.log(myInstance.myField); // 'foo'
myInstance.myMethod();
```

Typical function constructors can both be constructed with `new` and called without `new`. However, attempting to "call" a class without `new` will result in an error.

```js
const myInstance = MyClass(); // TypeError: Class constructor MyClass cannot be invoked without 'new'
```

### Class declaration hoisting

Unlike function declarations, class declarations are not hoisted (or, in some interpretations, hoisted but with the temporal dead zone restriction), which means you cannot use a class before it is declared.

```js
new MyClass(); // ReferenceError: Cannot access 'MyClass' before initialization

class MyClass {}
```

This behavior is similar to variables declared with `let` and `const`.

### Class expressions

Similar to functions, class declarations also have their expression counterparts.

```js
const MyClass = class {
  // Class body...
};
```

Class expressions can have names as well. The expression's name is only visible to the class's body.

```js
const MyClass = class MyClassLongerName {
  // Class body. Here MyClass and MyClassLongerName point to the same class.
};
new MyClassLongerName(); // ReferenceError: MyClassLongerName is not defined
```

Constructor
-----------

Perhaps the most important job of a class is to act as a "factory" for objects. For example, when we use the `Date` constructor, we expect it to give a new object which represents the date data we passed in — which we can then manipulate with other methods the instance exposes. In classes, the instance creation is done by the constructor.

As an example, we would create a class called `Color`, which represents a specific color. Users create colors through passing in an RGB triplet.

```js
class Color {
  constructor(r, g, b) {
    // Assign the RGB values as a property of `this`.
    this.values = [r, g, b];
  }
}
```

Open your browser's devtools, paste the above code into the console, and then create an instance:

```js
const red = new Color(255, 0, 0);
console.log(red);
```

You should see some output like this:
```

Object { values: (3) […] }
  values: Array(3) [ 255, 0, 0 ]
```

You have successfully created a `Color` instance, and the instance has a `values` property, which is an array of the RGB values you passed in. That is pretty much equivalent to the following:

```js
function createColor(r, g, b) {
  return {
    values: [r, g, b],
  };
}
```

The constructor's syntax is exactly the same as a normal function — which means you can use other syntaxes, like rest parameters:

```js
class Color {
  constructor(...values) {
    this.values = values;
  }
}

const red = new Color(255, 0, 0);
// Creates an instance with the same shape as above.
```

Each time you call `new`, a different instance is created.

```js
const red = new Color(255, 0, 0);
const anotherRed = new Color(255, 0, 0);
console.log(red === anotherRed); // false
```

Within a class constructor, the value of `this` points to the newly created instance. You can assign properties to it, or read existing properties (especially methods — which we will cover next).

The `this` value will be automatically returned as the result of `new`. You are advised to not return any value from the constructor — because if you return a non-primitive value, it will become the value of the `new` expression, and the value of `this` is dropped. (You can read more about what `new` does in its description.)

```js
class MyClass {
  constructor() {
    this.myField = "foo";
    return {};
  }
}

console.log(new MyClass().myField); // undefined
```

Instance methods
----------------

If a class only has a constructor, it is not much different from a `createX` factory function which just creates plain objects. However, the power of classes is that they can be used as "templates" which automatically assign methods to instances.

For example, for `Date` instances, you can use a range of methods to get different information from a single date value, such as the year, month, day of the week, etc. You can also set those values through the `setX` counterparts like `setFullYear`.

For our own `Color` class, we can add a method called `getRed` which returns the red value of the color.

```js
class Color {
  constructor(r, g, b) {
    this.values = [r, g, b];
  }
  getRed() {
    return this.values[0];
  }
}

const red = new Color(255, 0, 0);
console.log(red.getRed()); // 255
```

Without methods, you may be tempted to define the function within the constructor:

```js
class Color {
  constructor(r, g, b) {
    this.values = [r, g, b];
    this.getRed = function () {
      return this.values[0];
    };
  }
}
```

This also works. However, a problem is that this creates a new function every time a `Color` instance is created, even when they all do the same thing!

```js
console.log(new Color().getRed === new Color().getRed); // false
```

In contrast, if you use a method, it will be shared between all instances. A function can be shared between all instances, but still have its behavior differ when different instances call it, because the value of `this` is different. If you are curious *where* this method is stored in — it's defined on the prototype of all instances, or `Color.prototype`, which is explained in more detail in Inheritance and the prototype chain.

Similarly, we can create a new method called `setRed`, which sets the red value of the color.

```js
class Color {
  constructor(r, g, b) {
    this.values = [r, g, b];
  }
  getRed() {
    return this.values[0];
  }
  setRed(value) {
    this.values[0] = value;
  }
}

const red = new Color(255, 0, 0);
red.setRed(0);
console.log(red.getRed()); // 0; of course, it should be called "black" at this stage!
```

Private fields
--------------

You might be wondering: why do we want to go to the trouble of using `getRed` and `setRed` methods, when we can directly access the `values` array on the instance?

```js
class Color {
  constructor(r, g, b) {
    this.values = [r, g, b];
  }
}

const red = new Color(255, 0, 0);
red.values[0] = 0;
console.log(red.values[0]); // 0
```

There is a philosophy in object-oriented programming called "encapsulation". This means you should not access the underlying implementation of an object, but instead use well-abstracted methods to interact with it. For example, if we suddenly decided to represent colors as HSL instead:

```js
class Color {
  constructor(r, g, b) {
    // values is now an HSL array!
    this.values = rgbToHSL([r, g, b]);
  }
  getRed() {
    return this.values[0];
  }
  setRed(value) {
    this.values[0] = value;
  }
}

const red = new Color(255, 0, 0);
console.log(red.values[0]); // 0; It's not 255 anymore, because the H value for pure red is 0
```

The user assumption that `values` means the RGB value suddenly collapses, and it may cause their logic to break. So, if you are an implementor of a class, you would want to hide the internal data structure of your instance from your user, both to keep the API clean and to prevent the user's code from breaking when you do some "harmless refactors". In classes, this is done through *private fields*.

A private field is an identifier prefixed with `#` (the hash symbol). The hash is an integral part of the field's name, which means a private property can never have name clash with a public property. In order to refer to a private field anywhere in the class, you must *declare* it in the class body (you can't create a private property on the fly). Apart from this, a private field is pretty much equivalent to a normal property.

```js
class Color {
  // Declare: every Color instance has a private field called #values.
  #values;
  constructor(r, g, b) {
    this.#values = [r, g, b];
  }
  getRed() {
    return this.#values[0];
  }
  setRed(value) {
    this.#values[0] = value;
  }
}

const red = new Color(255, 0, 0);
console.log(red.getRed()); // 255
```

Accessing private fields outside the class is an early syntax error. The language can guard against this because `#privateField` is a special syntax, so it can do some static analysis and find all usage of private fields before even evaluating the code.

```js
console.log(red.#values); // SyntaxError: Private field '#values' must be declared in an enclosing class
```

**Note:** Code run in the Chrome console can access private properties outside the class. This is a DevTools-only relaxation of the JavaScript syntax restriction.

Private fields in JavaScript are *hard private*: if the class does not implement methods that expose these private fields, there's absolutely no mechanism to retrieve them from outside the class. This means you are safe to do any refactors to your class's private fields, as long as the behavior of exposed methods stay the same.

After we've made the `values` field private, we can add some more logic in the `getRed` and `setRed` methods, instead of making them simple pass-through methods. For example, we can add a check in `setRed` to see if it's a valid R value:

```js
class Color {
  #values;
  constructor(r, g, b) {
    this.#values = [r, g, b];
  }
  getRed() {
    return this.#values[0];
  }
  setRed(value) {
    if (value < 0 || value > 255) {
      throw new RangeError("Invalid R value");
    }
    this.#values[0] = value;
  }
}

const red = new Color(255, 0, 0);
red.setRed(1000); // RangeError: Invalid R value
```

If we leave the `values` property exposed, our users can easily circumvent that check by assigning to `values[0]` directly, and create invalid colors. But with a well-encapsulated API, we can make our code more robust and prevent logic errors downstream.

A class method can read the private fields of other instances, as long as they belong to the same class.

```js
class Color {
  #values;
  constructor(r, g, b) {
    this.#values = [r, g, b];
  }
  redDifference(anotherColor) {
    // #values doesn't necessarily need to be accessed from this:
    // you can access private fields of other instances belonging
    // to the same class.
    return this.#values[0] - anotherColor.#values[0];
  }
}

const red = new Color(255, 0, 0);
const crimson = new Color(220, 20, 60);
red.redDifference(crimson); // 35
```

However, if `anotherColor` is not a Color instance, `#values` won't exist. (Even if another class has an identically named `#values` private field, it's not referring to the same thing and cannot be accessed here.) Accessing a nonexistent private property throws an error instead of returning `undefined` like normal properties do. If you don't know if a private field exists on an object and you wish to access it without using `try`/`catch` to handle the error, you can use the `in` operator.

```js
class Color {
  #values;
  constructor(r, g, b) {
    this.#values = [r, g, b];
  }
  redDifference(anotherColor) {
    if (!(#values in anotherColor)) {
      throw new TypeError("Color instance expected");
    }
    return this.#values[0] - anotherColor.#values[0];
  }
}
```

**Note:** Keep in mind that the `#` is a special identifier syntax, and you can't use the field name as if it's a string. `"#values" in anotherColor` would look for a property name literally called `"#values"`, instead of a private field.

There are some limitations in using private properties: the same name can't be declared twice in a single class, and they can't be deleted. Both lead to early syntax errors.

```js
class BadIdeas {
  #firstName;
  #firstName; // syntax error occurs here
  #lastName;
  constructor() {
    delete this.#lastName; // also a syntax error
  }
}
```

Methods, getters, and setters can be private as well. They're useful when you have something complex that the class needs to do internally but no other part of the code should be allowed to call.

For example, imagine creating HTML custom elements that should do something somewhat complicated when clicked/tapped/otherwise activated. Furthermore, the somewhat complicated things that happen when the element is clicked should be restricted to this class, because no other part of the JavaScript will (or should) ever access it.

```js
class Counter extends HTMLElement {
  #xValue = 0;
  constructor() {
    super();
    this.onclick = this.#clicked.bind(this);
  }
  get #x() {
    return this.#xValue;
  }
  set #x(value) {
    this.#xValue = value;
    window.requestAnimationFrame(this.#render.bind(this));
  }
  #clicked() {
    this.#x++;
  }
  #render() {
    this.textContent = this.#x.toString();
  }
  connectedCallback() {
    this.#render();
  }
}

customElements.define("num-counter", Counter);
```

In this case, pretty much every field and method is private to the class. Thus, it presents an interface to the rest of the code that's essentially just like a built-in HTML element. No other part of the program has the power to affect any of the internals of `Counter`.

Accessor fields
---------------

`color.getRed()` and `color.setRed()` allow us to read and write to the red value of a color. If you come from languages like Java, you will be very familiar with this pattern. However, using methods to simply access a property is still somewhat unergonomic in JavaScript. *Accessor fields* allow us to manipulate something as if its an "actual property".

```js
class Color {
  constructor(r, g, b) {
    this.values = [r, g, b];
  }
  get red() {
    return this.values[0];
  }
  set red(value) {
    this.values[0] = value;
  }
}

const red = new Color(255, 0, 0);
red.red = 0;
console.log(red.red); // 0
```

It looks as if the object has a property called `red` — but actually, no such property exists on the instance! There are only two methods, but they are prefixed with `get` and `set`, which allows them to be manipulated as if they were properties.

If a field only has a getter but no setter, it will be effectively read-only.

```js
class Color {
  constructor(r, g, b) {
    this.values = [r, g, b];
  }
  get red() {
    return this.values[0];
  }
}

const red = new Color(255, 0, 0);
red.red = 0;
console.log(red.red); // 255
```

In strict mode, the `red.red = 0` line will throw a type error: "Cannot set property red of #<Color> which has only a getter". In non-strict mode, the assignment is silently ignored.

Public fields
-------------

Private fields also have their public counterparts, which allow every instance to have a property. Fields are usually designed to be independent of the constructor's parameters.

```js
class MyClass {
  luckyNumber = Math.random();
}
console.log(new MyClass().luckyNumber); // 0.5
console.log(new MyClass().luckyNumber); // 0.3
```

Public fields are almost equivalent to assigning a property to `this`. For example, the above example can also be converted to:

```js
class MyClass {
  constructor() {
    this.luckyNumber = Math.random();
  }
}
```

Static properties
-----------------

With the `Date` example, we have also encountered the `Date.now()` method, which returns the current date. This method does not belong to any date instance — it belongs to the class itself. However, it's put on the `Date` class instead of being exposed as a global `DateNow()` function, because it's mostly useful when dealing with date instances.

**Note:** Prefixing utility methods with what they deal with is called "namespacing" and is considered a good practice. For example, in addition to the older, unprefixed `parseInt()` method, JavaScript also later added the prefixed `Number.parseInt()` method to indicate that it's for dealing with numbers.

*Static properties* are a group of class features that are defined on the class itself, rather than on individual instances of the class. These features include:

* Static methods
* Static fields
* Static getters and setters

Everything also has private counterparts. For example, for our `Color` class, we can create a static method that checks whether a given triplet is a valid RGB value:

```js
class Color {
  static isValid(r, g, b) {
    return r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255;
  }
}

Color.isValid(255, 0, 0); // true
Color.isValid(1000, 0, 0); // false
```

Static properties are very similar to their instance counterparts, except that:

* They are all prefixed with `static`, and
* They are not accessible from instances.

```js
console.log(new Color(0, 0, 0).isValid); // undefined
```

There is also a special construct called a *static initialization block*, which is a block of code that runs when the class is first loaded.

```js
class MyClass {
  static {
    MyClass.myStaticProperty = "foo";
  }
}

console.log(MyClass.myStaticProperty); // 'foo'
```

Static initialization blocks are almost equivalent to immediately executing some code after a class has been declared. The only difference is that they have access to static private properties.

Extends and inheritance
-----------------------

A key feature that classes bring about (in addition to ergonomic encapsulation with private fields) is *inheritance*, which means one object can "borrow" a large part of another object's behaviors, while overriding or enhancing certain parts with its own logic.

For example, suppose our `Color` class now needs to support transparency. We may be tempted to add a new field that indicates its transparency:

```js
class Color {
  #values;
  constructor(r, g, b, a = 1) {
    this.#values = [r, g, b, a];
  }
  get alpha() {
    return this.#values[3];
  }
  set alpha(value) {
    if (value < 0 || value > 1) {
      throw new RangeError("Alpha value must be between 0 and 1");
    }
    this.#values[3] = value;
  }
}
```

However, this means every instance — even the vast majority which aren't transparent (those with an alpha value of 1) — will have to have the extra alpha value, which is not very elegant. Plus, if the features keep growing, our `Color` class will become very bloated and hard to maintain.

Instead, in object-oriented programming, we would create a *derived class*. The derived class has access to all public properties of the parent class. In JavaScript, derived classes are declared with an `extends` clause, which indicates the class it extends from.

```js
class ColorWithAlpha extends Color {
  #alpha;
  constructor(r, g, b, a) {
    super(r, g, b);
    this.#alpha = a;
  }
  get alpha() {
    return this.#alpha;
  }
  set alpha(value) {
    if (value < 0 || value > 1) {
      throw new RangeError("Alpha value must be between 0 and 1");
    }
    this.#alpha = value;
  }
}
```

There are a few things that have immediately come to attention. First is that in the constructor, we are calling `super(r, g, b)`. It is a language requirement to call `super()` before accessing `this`. The `super()` call calls the parent class's constructor to initialize `this` — here it's roughly equivalent to `this = new Color(r, g, b)`. You can have code before `super()`, but you cannot access `this` before `super()` — the language prevents you from accessing the uninitialized `this`.

After the parent class is done with modifying `this`, the derived class can do its own logic. Here we added a private field called `#alpha`, and also provided a pair of getter/setters to interact with them.

A derived class inherits all methods from its parent. For example, although `ColorWithAlpha` doesn't declare a `get red()` accessor itself, you can still access `red` because this behavior is specified by the parent class:

```js
const color = new ColorWithAlpha(255, 0, 0, 0.5);
console.log(color.red); // 255
```

Derived classes can also override methods from the parent class. For example, all classes implicitly inherit the `Object` class, which defines some basic methods like `toString()`. However, the base `toString()` method is notoriously useless, because it prints `[object Object]` in most cases:

```js
console.log(red.toString()); // [object Object]
```

Instead, our class can override it to print the color's RGB values:

```js
class Color {
  #values;
  // …
  toString() {
    return this.#values.join(", ");
  }
}

console.log(new Color(255, 0, 0).toString()); // '255, 0, 0'
```

Within derived classes, you can access the parent class's methods by using `super`. This allows you to build enhancement methods and avoid code duplication.

```js
class ColorWithAlpha extends Color {
  #alpha;
  // …
  toString() {
    // Call the parent class's toString() and build on the return value
    return `${super.toString()}, ${this.#alpha}`;
  }
}

console.log(new ColorWithAlpha(255, 0, 0, 0.5).toString()); // '255, 0, 0, 0.5'
```

When you use `extends`, the static methods inherit from each other as well, so you can also override or enhance them.

```js
class ColorWithAlpha extends Color {
  // ...
  static isValid(r, g, b, a) {
    // Call the parent class's isValid() and build on the return value
    return super.isValid(r, g, b) && a >= 0 && a <= 1;
  }
}

console.log(ColorWithAlpha.isValid(255, 0, 0, -1)); // false
```

Derived classes don't have access to the parent class's private fields — this is another key aspect to JavaScript private fields being "hard private". Private fields are scoped to the class body itself and do not grant access to *any* outside code.

```js
class ColorWithAlpha extends Color {
  log() {
    console.log(this.#values); // SyntaxError: Private field '#values' must be declared in an enclosing class
  }
}
```

A class can only extend from one class. This prevents problems in multiple inheritance like the diamond problem. However, due to the dynamic nature of JavaScript, it's still possible to achieve the effect of multiple inheritance through class composition and mixins.

Instances of derived classes are also instances of the base class.

```js
const color = new ColorWithAlpha(255, 0, 0, 0.5);
console.log(color instanceof Color); // true
console.log(color instanceof ColorWithAlpha); // true
```

Why classes?
------------

The guide has been pragmatic so far: we are focusing on *how* classes can be used, but there's one question unanswered: *why* would one use a class? The answer is: it depends.

Classes introduce a *paradigm*, or a way to organize your code. Classes are the foundations of object-oriented programming, which is built on concepts like inheritance and polymorphism (especially *subtype polymorphism*). However, many people are philosophically against certain OOP practices and don't use classes as a result.

For example, one thing that makes `Date` objects infamous is that they're *mutable*.

```js
function incrementDay(date) {
  return date.setDate(date.getDate() + 1);
}
const date = new Date(); // 2019-06-19
const newDay = incrementDay(date);
console.log(newDay); // 2019-06-20
// The old date is modified as well!?
console.log(date); // 2019-06-20
```

Mutability and internal state are important aspects of object-oriented programming, but often make code hard to reason with — because any seemingly innocent operation may have unexpected side effects and change the behavior in other parts of the program.

In order to reuse code, we usually resort to extending classes, which can create big hierarchies of inheritance patterns.

![A typical OOP inheritance tree, with five classes and three levels](/en-US/docs/Web/JavaScript/Guide/Using_classes/figure8.1.png)

However, it is often hard to describe inheritance cleanly when one class can only extend one other class. Often, we want the behavior of multiple classes. In Java, this is done through interfaces; in JavaScript, it can be done through mixins. But at the end of the day, it's still not very convenient.

On the brighter side, classes are a very powerful way to organize our code on a higher level. For example, without the `Color` class, we may need to create a dozen of utility functions:

```js
function isRed(color) {
  return color.red === 255;
}
function isValidColor(color) {
  return (
    color.red >= 0 &&
    color.red <= 255 &&
    color.green >= 0 &&
    color.green <= 255 &&
    color.blue >= 0 &&
    color.blue <= 255
  );
}
// ...
```

But with classes, we can congregate them all under the `Color` namespace, which improves readability. In addition, the introduction of private fields allows us to hide certain data from downstream users, creating a clean API.

In general, you should consider using classes when you want to create objects that store their own internal data and expose a lot of behavior. Take built-in JavaScript classes as examples:

* The `Map` and `Set` classes store a collection of elements and allow you to access them by key using `get()`, `set()`, `has()`, etc.
* The `Date` class stores a date as a Unix timestamp (a number) and allows you to format, update, and read individual date components.
* The `Error` class stores information about a particular exception, including the error message, stack trace, cause, etc. It's one of the few classes that come with a rich inheritance structure: there are multiple built-in classes like `TypeError` and `ReferenceError` that extend `Error`. In the case of errors, this inheritance allows refining the semantics of errors: each error class represents a specific type of error, which can be easily checked with `instanceof`.

JavaScript offers the mechanism to organize your code in a canonical object-oriented way, but whether and how to use it is entirely up to the programmer's discretion.

* « Previous
* Next »


Functions - JavaScript

Functions
=========

* « Previous
* Next »

Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output. To use a function, you must define it somewhere in the scope from which you wish to call it.

See also the exhaustive reference chapter about JavaScript functions to get to know the details.

Defining functions
------------------

### Function declarations

A **function definition** (also called a **function declaration**, or **function statement**) consists of the `function` keyword, followed by:

* The name of the function.
* A list of parameters to the function, enclosed in parentheses and separated by commas.
* The JavaScript statements that define the function, enclosed in curly braces, `{ /* … */ }`.

For example, the following code defines a simple function named `square`:

```js
function square(number) {
  return number \* number;
}
```

The function `square` takes one parameter, called `number`. The function consists of one statement that says to return the parameter of the function (that is, `number`) multiplied by itself. The `return` statement specifies the value returned by the function, which is `number * number`.

Parameters are essentially passed to functions **by value** — so if the code within the body of a function assigns a completely new value to a parameter that was passed to the function, **the change is not reflected globally or in the code which called that function**.

When you pass an object as a parameter, if the function changes the object's properties, that change is visible outside the function, as shown in the following example:

```js
function myFunc(theObject) {
  theObject.make = "Toyota";
}

const mycar = {
  make: "Honda",
  model: "Accord",
  year: 1998,
};

console.log(mycar.make); // "Honda"
myFunc(mycar);
console.log(mycar.make); // "Toyota"
```

When you pass an array as a parameter, if the function changes any of the array's values, that change is visible outside the function, as shown in the following example:

```js
function myFunc(theArr) {
  theArr[0] = 30;
}

const arr = [45];

console.log(arr[0]); // 45
myFunc(arr);
console.log(arr[0]); // 30
```

### Function expressions

While the function declaration above is syntactically a statement, functions can also be created by a function expression.

Such a function can be **anonymous**; it does not have to have a name. For example, the function `square` could have been defined as:

```js
const square = function (number) {
  return number \* number;
};

console.log(square(4)); // 16
```

However, a name *can* be provided with a function expression. Providing a name allows the function to refer to itself, and also makes it easier to identify the function in a debugger's stack traces:

```js
const factorial = function fac(n) {
  return n < 2 ? 1 : n \* fac(n - 1);
};

console.log(factorial(3)); // 6
```

Function expressions are convenient when passing a function as an argument to another function. The following example shows a `map` function that should receive a function as first argument and an array as second argument:

```js
function map(f, a) {
  const result = new Array(a.length);
  for (let i = 0; i < a.length; i++) {
    result[i] = f(a[i]);
  }
  return result;
}
```

In the following code, the function receives a function defined by a function expression and executes it for every element of the array received as a second argument:

```js
function map(f, a) {
  const result = new Array(a.length);
  for (let i = 0; i < a.length; i++) {
    result[i] = f(a[i]);
  }
  return result;
}

const cube = function (x) {
  return x \* x \* x;
};

const numbers = [0, 1, 2, 5, 10];
console.log(map(cube, numbers)); // [0, 1, 8, 125, 1000]
```

In JavaScript, a function can be defined based on a condition. For example, the following function definition defines `myFunc` only if `num` equals `0`:

```js
let myFunc;
if (num === 0) {
  myFunc = function (theObject) {
    theObject.make = "Toyota";
  };
}
```

In addition to defining functions as described here, you can also use the `Function` constructor to create functions from a string at runtime, much like `eval()`.

A **method** is a function that is a property of an object. Read more about objects and methods in Working with objects.

Calling functions
-----------------

*Defining* a function does not *execute* it. Defining it names the function and specifies what to do when the function is called.

**Calling** the function actually performs the specified actions with the indicated parameters. For example, if you define the function `square`, you could call it as follows:

```js
square(5);
```

The preceding statement calls the function with an argument of `5`. The function executes its statements and returns the value `25`.

Functions must be *in scope* when they are called, but the function declaration can be hoisted (appear below the call in the code). The scope of a function declaration is the function in which it is declared (or the entire program, if it is declared at the top level).

The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function. The `showProps()` function (defined in Working with objects) is an example of a function that takes an object as an argument.

A function can call itself. For example, here is a function that computes factorials recursively:

```js
function factorial(n) {
  if (n === 0 || n === 1) {
    return 1;
  } else {
    return n \* factorial(n - 1);
  }
}
```

You could then compute the factorials of `1` through `5` as follows:

```js
console.log(factorial(1)); // 1
console.log(factorial(2)); // 2
console.log(factorial(3)); // 6
console.log(factorial(4)); // 24
console.log(factorial(5)); // 120
```

There are other ways to call functions. There are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime.

It turns out that *functions are themselves objects* — and in turn, these objects have methods. (See the `Function` object.) The `call()` and `apply()` methods can be used to achieve this goal.

### Function hoisting

Consider the example below:

```js
console.log(square(5)); // 25

function square(n) {
  return n \* n;
}
```

This code runs without any error, despite the `square()` function being called before it's declared. This is because the JavaScript interpreter hoists the entire function declaration to the top of the current scope, so the code above is equivalent to:

```js
// All function declarations are effectively at the top of the scope
function square(n) {
  return n \* n;
}

console.log(square(5)); // 25
```

Function hoisting only works with function *declarations* — not with function *expressions*. The following code will not work:

```js
console.log(square(5)); // ReferenceError: Cannot access 'square' before initialization
const square = function (n) {
  return n \* n;
};
```

Function scope
--------------

Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside the scope in which it is defined.

In other words, a function defined in the global scope can access all variables defined in the global scope. A function defined inside another function can also access all variables defined in its parent function, and any other variables to which the parent function has access.

```js
// The following variables are defined in the global scope
const num1 = 20;
const num2 = 3;
const name = "Chamakh";

// This function is defined in the global scope
function multiply() {
  return num1 \* num2;
}

console.log(multiply()); // 60

// A nested function example
function getScore() {
  const num1 = 2;
  const num2 = 3;

  function add() {
    return `${name} scored ${num1 + num2}`;
  }

  return add();
}

console.log(getScore()); // "Chamakh scored 5"
```

Scope and the function stack
----------------------------

### Recursion

A function can refer to and call itself. There are three ways for a function to refer to itself:

1. The function's name
2. `arguments.callee`
3. An in-scope variable that refers to the function

For example, consider the following function definition:

```js
const foo = function bar() {
  // statements go here
};
```

Within the function body, the following are all equivalent:

1. `bar()`
2. `arguments.callee()`
3. `foo()`

A function that calls itself is called a *recursive function*. In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case).

For example, consider the following loop:

```js
let x = 0;
// "x < 10" is the loop condition
while (x < 10) {
  // do stuff
  x++;
}
```

It can be converted into a recursive function declaration, followed by a call to that function:

```js
function loop(x) {
  // "x >= 10" is the exit condition (equivalent to "!(x < 10)")
  if (x >= 10) {
    return;
  }
  // do stuff
  loop(x + 1); // the recursive call
}
loop(0);
```

However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (such as the DOM) is easier via recursion:

```js
function walkTree(node) {
  if (node === null) {
    return;
  }
  // do something with node
  for (let i = 0; i < node.childNodes.length; i++) {
    walkTree(node.childNodes[i]);
  }
}
```

Compared to the function `loop`, each recursive call itself makes many recursive calls here.

It is possible to convert any recursive algorithm to a non-recursive one, but the logic is often much more complex, and doing so requires the use of a stack.

In fact, recursion itself uses a stack: the function stack. The stack-like behavior can be seen in the following example:

```js
function foo(i) {
  if (i < 0) {
    return;
  }
  console.log(`begin: ${i}`);
  foo(i - 1);
  console.log(`end: ${i}`);
}
foo(3);

// Logs:
// begin: 3
// begin: 2
// begin: 1
// begin: 0
// end: 0
// end: 1
// end: 2
// end: 3
```

### Nested functions and closures

You may nest a function within another function. The nested (inner) function is private to its containing (outer) function.

It also forms a *closure*. A closure is an expression (most commonly, a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.

To summarize:

* The inner function can be accessed only from statements in the outer function.
* The inner function forms a closure: the inner function can use the arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function.

The following example shows nested functions:

```js
function addSquares(a, b) {
  function square(x) {
    return x \* x;
  }
  return square(a) + square(b);
}

console.log(addSquares(2, 3)); // 13
console.log(addSquares(3, 4)); // 25
console.log(addSquares(4, 5)); // 41
```

Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function:

```js
function outside(x) {
  function inside(y) {
    return x + y;
  }
  return inside;
}

const fnInside = outside(3); // Think of it like: give me a function that adds 3 to whatever you give it
console.log(fnInside(5)); // 8
console.log(outside(3)(5)); // 8
```

### Preservation of variables

Notice how `x` is preserved when `inside` is returned. A closure must preserve the arguments and variables in all scopes it references. Since each call provides potentially different arguments, a new closure is created for each call to `outside`. The memory can be freed only when the returned `inside` is no longer accessible.

This is not different from storing references in other objects, but is often less obvious because one does not set the references directly and cannot inspect them.

### Multiply-nested functions

Functions can be multiply-nested. For example:

* A function (`A`) contains a function (`B`), which itself contains a function (`C`).
* Both functions `B` and `C` form closures here. So, `B` can access `A`, and `C` can access `B`.
* In addition, since `C` can access `B` which can access `A`, `C` can also access `A`.

Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called *scope chaining*. (The reason it is called "chaining" is explained later.)

Consider the following example:

```js
function A(x) {
  function B(y) {
    function C(z) {
      console.log(x + y + z);
    }
    C(3);
  }
  B(2);
}
A(1); // Logs 6 (which is 1 + 2 + 3)
```

In this example, `C` accesses `B`'s `y` and `A`'s `x`.

This can be done because:

1. `B` forms a closure including `A` (i.e., `B` can access `A`'s arguments and variables).
2. `C` forms a closure including `B`.
3. Because `C`'s closure includes `B` and `B`'s closure includes `A`, then `C`'s closure also includes `A`. This means `C` can access *both* `B` *and* `A`'s arguments and variables. In other words, `C` *chains* the scopes of `B` and `A`, *in that order*.

The reverse, however, is not true. `A` cannot access `C`, because `A` cannot access any argument or variable of `B`, which `C` is a variable of. Thus, `C` remains private to only `B`.

### Name conflicts

When two arguments or variables in the scopes of a closure have the same name, there is a *name conflict*. More nested scopes take precedence. So, the innermost scope takes the highest precedence, while the outermost scope takes the lowest. This is the scope chain. The first on the chain is the innermost scope, and the last is the outermost scope. Consider the following:

```js
function outside() {
  const x = 5;
  function inside(x) {
    return x \* 2;
  }
  return inside;
}

console.log(outside()(10)); // 20 (instead of 10)
```

The name conflict happens at the statement `return x * 2` and is between `inside`'s parameter `x` and `outside`'s variable `x`. The scope chain here is {`inside`, `outside`, global object}. Therefore, `inside`'s `x` takes precedences over `outside`'s `x`, and `20` (`inside`'s `x`) is returned instead of `10` (`outside`'s `x`).

Closures
--------

Closures are one of the most powerful features of JavaScript. JavaScript allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to).

However, the outer function does *not* have access to the variables and functions defined inside the inner function. This provides a sort of encapsulation for the variables of the inner function.

Also, since the inner function has access to the scope of the outer function, the variables and functions defined in the outer function will live longer than the duration of the outer function execution, if the inner function manages to survive beyond the life of the outer function. A closure is created when the inner function is somehow made available to any scope outside the outer function.

```js
// The outer function defines a variable called "name"
const pet = function (name) {
  const getName = function () {
    // The inner function has access to the "name" variable of the outer function
    return name;
  };
  return getName; // Return the inner function, thereby exposing it to outer scopes
};
const myPet = pet("Vivie");

console.log(myPet()); // "Vivie"
```

It can be much more complex than the code above. An object containing methods for manipulating the inner variables of the outer function can be returned.

```js
const createPet = function (name) {
  let sex;

  const pet = {
    // setName(newName) is equivalent to setName: function (newName)
    // in this context
    setName(newName) {
      name = newName;
    },

    getName() {
      return name;
    },

    getSex() {
      return sex;
    },

    setSex(newSex) {
      if (
        typeof newSex === "string" &&
        (newSex.toLowerCase() === "male" || newSex.toLowerCase() === "female")
      ) {
        sex = newSex;
      }
    },
  };

  return pet;
};

const pet = createPet("Vivie");
console.log(pet.getName()); // Vivie

pet.setName("Oliver");
pet.setSex("male");
console.log(pet.getSex()); // male
console.log(pet.getName()); // Oliver
```

In the code above, the `name` variable of the outer function is accessible to the inner functions, and there is no other way to access the inner variables except through the inner functions. The inner variables of the inner functions act as safe stores for the outer arguments and variables. They hold "persistent" and "encapsulated" data for the inner functions to work with. The functions do not even have to be assigned to a variable, or have a name.

```js
const getCode = (function () {
  const apiCode = "0]Eal(eh&2"; // A code we do not want outsiders to be able to modify…

  return function () {
    return apiCode;
  };
})();

console.log(getCode()); // "0]Eal(eh&2"
```

**Note:** There are a number of pitfalls to watch out for when using closures!

If an enclosed function defines a variable with the same name as a variable in the outer scope, then there is no way to refer to the variable in the outer scope again. (The inner scope variable "overrides" the outer one, until the program exits the inner scope. It can be thought of as a name conflict.)

```js
const createPet = function (name) {
  // The outer function defines a variable called "name".
  return {
    setName(name) {
      // The enclosed function also defines a variable called "name".
      name = name; // How do we access the "name" defined by the outer function?
    },
  };
};
```

Using the arguments object
--------------------------

The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows:

```js
arguments[i];
```

where `i` is the ordinal number of the argument, starting at `0`. So, the first argument passed to a function would be `arguments[0]`. The total number of arguments is indicated by `arguments.length`.

Using the `arguments` object, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don't know in advance how many arguments will be passed to the function. You can use `arguments.length` to determine the number of arguments actually passed to the function, and then access each argument using the `arguments` object.

For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:

```js
function myConcat(separator) {
  let result = ""; // initialize list
  // iterate through arguments
  for (let i = 1; i < arguments.length; i++) {
    result += arguments[i] + separator;
  }
  return result;
}
```

You can pass any number of arguments to this function, and it concatenates each argument into a string "list":

```js
console.log(myConcat(", ", "red", "orange", "blue"));
// "red, orange, blue, "

console.log(myConcat("; ", "elephant", "giraffe", "lion", "cheetah"));
// "elephant; giraffe; lion; cheetah; "

console.log(myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley"));
// "sage. basil. oregano. pepper. parsley. "
```

**Note:** The `arguments` variable is "array-like", but not an array. It is array-like in that it has a numbered index and a `length` property. However, it does *not* possess all of the array-manipulation methods.

See the `Function` object in the JavaScript reference for more information.

Function parameters
-------------------

There are two special kinds of parameter syntax: *default parameters* and *rest parameters*.

### Default parameters

In JavaScript, parameters of functions default to `undefined`. However, in some situations it might be useful to set a different default value. This is exactly what default parameters do.

In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are `undefined`.

In the following example, if no value is provided for `b`, its value would be `undefined` when evaluating `a*b`, and a call to `multiply` would normally have returned `NaN`. However, this is prevented by the second line in this example:

```js
function multiply(a, b) {
  b = typeof b !== "undefined" ? b : 1;
  return a \* b;
}

console.log(multiply(5)); // 5
```

With *default parameters*, a manual check in the function body is no longer necessary. You can put `1` as the default value for `b` in the function head:

```js
function multiply(a, b = 1) {
  return a \* b;
}

console.log(multiply(5)); // 5
```

For more details, see default parameters in the reference.

### Rest parameters

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

In the following example, the function `multiply` uses *rest parameters* to collect arguments from the second one to the end. The function then multiplies these by the first argument.

```js
function multiply(multiplier, ...theArgs) {
  return theArgs.map((x) => multiplier \* x);
}

const arr = multiply(2, 1, 2, 3);
console.log(arr); // [2, 4, 6]
```

Arrow functions
---------------

An arrow function expression (also called a *fat arrow* to distinguish from a hypothetical `->` syntax in future JavaScript) has a shorter syntax compared to function expressions and does not have its own `this`, `arguments`, `super`, or `new.target`. Arrow functions are always anonymous.

Two factors influenced the introduction of arrow functions: *shorter functions* and *non-binding* of `this`.

### Shorter functions

In some functional patterns, shorter functions are welcome. Compare:

```js
const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];

const a2 = a.map(function (s) {
  return s.length;
});

console.log(a2); // [8, 6, 7, 9]

const a3 = a.map((s) => s.length);

console.log(a3); // [8, 6, 7, 9]
```

### No separate this

Until arrow functions, every new function defined its own `this` value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming.

```js
function Person() {
  // The Person() constructor defines `this` as itself.
  this.age = 0;

  setInterval(function growUp() {
    // In nonstrict mode, the growUp() function defines `this`
    // as the global object, which is different from the `this`
    // defined by the Person() constructor.
    this.age++;
  }, 1000);
}

const p = new Person();
```

In ECMAScript 3/5, this issue was fixed by assigning the value in `this` to a variable that could be closed over.

```js
function Person() {
  // Some choose `that` instead of `self`.
  // Choose one and be consistent.
  const self = this;
  self.age = 0;

  setInterval(function growUp() {
    // The callback refers to the `self` variable of which
    // the value is the expected object.
    self.age++;
  }, 1000);
}
```

Alternatively, a bound function could be created so that the proper `this` value would be passed to the `growUp()` function.

An arrow function does not have its own `this`; the `this` value of the enclosing execution context is used. Thus, in the following code, the `this` within the function that is passed to `setInterval` has the same value as `this` in the enclosing function:

```js
function Person() {
  this.age = 0;

  setInterval(() => {
    this.age++; // `this` properly refers to the person object
  }, 1000);
}

const p = new Person();
```

* « Previous
* Next »


Text formatting - JavaScript

Text formatting
===============

* « Previous
* Next »

This chapter introduces how to work with strings and text in JavaScript.

Strings
-------

JavaScript's String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values (UTF-16 code units). Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on. The length of a String is the number of elements in it. You can create strings using string literals or string objects.

### String literals

You can create simple strings using either single or double quotes:

```js
'foo'
"bar"
```

More advanced strings can be created using escape sequences:

#### Hexadecimal escape sequences

The number after \x is interpreted as a hexadecimal number.

```js
"\xA9" // "©"
```

#### Unicode escape sequences

The Unicode escape sequences require at least four hexadecimal digits following `\u`.

```js
"\u00A9" // "©"
```

#### Unicode code point escapes

With Unicode code point escapes, any character can be escaped using hexadecimal numbers so that it is possible to use Unicode code points up to `0x10FFFF`. With simple Unicode escapes it is often necessary to write the surrogate halves separately to achieve the same result.

See also `String.fromCodePoint()` or `String.prototype.codePointAt()`.

```js
"\u{2F804}"

// the same with simple Unicode escapes
"\uD87E\uDC04"
```

### String objects

The `String` object is a wrapper around the string primitive data type.

```js
const foo = new String("foo"); // Creates a String object
console.log(foo); // [String: 'foo']
typeof foo; // 'object'
```

You can call any of the methods of the `String` object on a string literal value—JavaScript automatically converts the string literal to a temporary `String` object, calls the method, then discards the temporary `String` object. You can also use the `length` property with a string literal.

You should use string literals unless you specifically need to use a `String` object, because `String` objects can have counterintuitive behavior. For example:

```js
const firstString = "2 + 2"; // Creates a string literal value
const secondString = new String("2 + 2"); // Creates a String object
eval(firstString); // Returns the number 4
eval(secondString); // Returns a String object containing "2 + 2"
```

A `String` object has one property, `length`, that indicates the number of UTF-16 code units in the string. For example, the following code assigns `helloLength` the value 13, because "Hello, World!" has 13 characters, each represented by one UTF-16 code unit. You can access each code unit using an array bracket style. You can't change individual characters because strings are immutable array-like objects:

```js
const hello = "Hello, World!";
const helloLength = hello.length;
hello[0] = "L"; // This has no effect, because strings are immutable
hello[0]; // This returns "H"
```

Characters whose Unicode scalar values are greater than U+FFFF (such as some rare Chinese/Japanese/Korean/Vietnamese characters and some emoji) are stored in UTF-16 with two surrogate code units each. For example, a string containing the single character U+1F600 "Emoji grinning face" will have length 2. Accessing the individual code units in such a string using square brackets may have undesirable consequences such as the formation of strings with unmatched surrogate code units, in violation of the Unicode standard. (Examples should be added to this page after MDN bug 857438 is fixed.) See also `String.fromCodePoint()` or `String.prototype.codePointAt()`.

A `String` object has a variety of methods: for example those that return a variation on the string itself, such as `substring` and `toUpperCase`.

The following table summarizes the methods of `String` objects.

#### Methods of `String`

| Method | Description |
| --- | --- |
| `charAt()`, `charCodeAt()`,
 `codePointAt()` |
 Return the character or character code at the specified position in
 string.
  |
| `indexOf()`,
 `lastIndexOf()` |
 Return the position of specified substring in the string or last
 position of specified substring, respectively.
  |
| `startsWith()`,
 `endsWith()`,
 `includes()` |
 Returns whether or not the string starts, ends or contains a specified
 string.
  |
| `concat()` | Combines the text of two strings and returns a new string. |
| `split()` |
 Splits a `String` object into an array of strings by
 separating the string into substrings.
  |
| `slice()` | Extracts a section of a string and returns a new string. |
| `substring()`,
 `substr()` |
 Return the specified subset of the string, either by specifying the
 start and end indexes or the start index and a length.
  |
| `match()`, `matchAll()`,
 `replace()`, `replaceAll()`,
 `search()` | Work with regular expressions. |
| `toLowerCase()`,
 `toUpperCase()` | Return the string in all lowercase or all uppercase, respectively. |
| `normalize()` | Returns the Unicode Normalization Form of the calling string value. |
| `repeat()` |
 Returns a string consisting of the elements of the object repeated the
 given times.
  |
| `trim()` | Trims whitespace from the beginning and end of the string. |

### Multi-line template literals

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

Template literals are enclosed by backtick (grave accent) characters (```) instead of double or single quotes. Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (`${expression}`).

#### Multi-lines

Any new line characters inserted in the source are part of the template literal. Using normal strings, you would have to use the following syntax in order to get multi-line strings:

```js
console.log(
  "string text line 1\n\
string text line 2",
);
// "string text line 1
// string text line 2"
```

To get the same effect with multi-line strings, you can now write:

```js
console.log(`string text line 1
string text line 2`);
// "string text line 1
// string text line 2"
```

#### Embedded expressions

In order to embed expressions within normal strings, you would use the following syntax:

```js
const five = 5;
const ten = 10;
console.log(
  "Fifteen is " + (five + ten) + " and not " + (2 \* five + ten) + ".",
);
// "Fifteen is 15 and not 20."
```

Now, with template literals, you are able to make use of the syntactic sugar making substitutions like this more readable:

```js
const five = 5;
const ten = 10;
console.log(`Fifteen is ${five + ten} and not ${2 \* five + ten}.`);
// "Fifteen is 15 and not 20."
```

For more information, read about Template literals in the JavaScript reference.

Internationalization
--------------------

The `Intl` object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. The constructors for `Intl.Collator`, `Intl.NumberFormat`, and `Intl.DateTimeFormat` objects are properties of the `Intl` object.

### Date and time formatting

The `Intl.DateTimeFormat` object is useful for formatting date and time. The following formats a date for English as used in the United States. (The result is different in another time zone.)

```js
// July 17, 2014 00:00:00 UTC:
const july172014 = new Date("2014-07-17");

const options = {
  year: "2-digit",
  month: "2-digit",
  day: "2-digit",
  hour: "2-digit",
  minute: "2-digit",
  timeZoneName: "short",
};
const americanDateTime = new Intl.DateTimeFormat("en-US", options).format;

// Local timezone vary depending on your settings
// In CEST, logs: 07/17/14, 02:00 AM GMT+2
// In PDT, logs: 07/16/14, 05:00 PM GMT-7
console.log(americanDateTime(july172014));
```

### Number formatting

The `Intl.NumberFormat` object is useful for formatting numbers, for example currencies.

```js
const gasPrice = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  minimumFractionDigits: 3,
});

console.log(gasPrice.format(5.259)); // $5.259

const hanDecimalRMBInChina = new Intl.NumberFormat("zh-CN-u-nu-hanidec", {
  style: "currency",
  currency: "CNY",
});

console.log(hanDecimalRMBInChina.format(1314.25)); // ￥ 一,三一四.二五
```

### Collation

The `Intl.Collator` object is useful for comparing and sorting strings.

For example, there are actually two different sort orders in German, *phonebook* and *dictionary*. Phonebook sort emphasizes sound, and it's as if "ä", "ö", and so on were expanded to "ae", "oe", and so on prior to sorting.

```js
const names = ["Hochberg", "Hönigswald", "Holzman"];

const germanPhonebook = new Intl.Collator("de-DE-u-co-phonebk");

// as if sorting ["Hochberg", "Hoenigswald", "Holzman"]:
console.log(names.sort(germanPhonebook.compare).join(", "));
// "Hochberg, Hönigswald, Holzman"
```

Some German words conjugate with extra umlauts, so in dictionaries it's sensible to order ignoring umlauts (except when ordering words differing *only* by umlauts: *schon* before *schön*).

```js
const germanDictionary = new Intl.Collator("de-DE-u-co-dict");

// as if sorting ["Hochberg", "Honigswald", "Holzman"]:
console.log(names.sort(germanDictionary.compare).join(", "));
// "Hochberg, Holzman, Hönigswald"
```

For more information about the `Intl` API, see also Introducing the JavaScript Internationalization API.

* « Previous
* Next »


Expressions and operators - JavaScript

Expressions and operators
=========================

* « Previous
* Next »

This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.

At a high level, an *expression* is a valid unit of code that resolves to a value. There are two types of expressions: those that have side effects (such as assigning values) and those that purely *evaluate*.

The expression `x = 7` is an example of the first type. This expression uses the `=` *operator* to assign the value seven to the variable `x`. The expression itself evaluates to `7`.

The expression `3 + 4` is an example of the second type. This expression uses the `+` operator to add `3` and `4` together and produces a value, `7`. However, if it's not eventually part of a bigger construct (for example, a variable declaration like `const z = 3 + 4`), its result will be immediately discarded — this is usually a programmer mistake because the evaluation doesn't produce any effects.

As the examples above also illustrate, all complex expressions are joined by *operators*, such as `=` and `+`. In this section, we will introduce the following operators:

* Assignment operators
* Comparison operators
* Arithmetic operators
* Bitwise operators
* Logical operators
* BigInt operators
* String operators
* Conditional (ternary) operator
* Comma operator
* Unary operators
* Relational operators

These operators join operands either formed by higher-precedence operators or one of the basic expressions. A complete and detailed list of operators and expressions is also available in the reference.

The *precedence* of operators determines the order they are applied when evaluating an expression. For example:

```js
const x = 1 + 2 \* 3;
const y = 2 \* 3 + 1;
```

Despite `*` and `+` coming in different orders, both expressions would result in `7` because `*` has precedence over `+`, so the `*`-joined expression will always be evaluated first. You can override operator precedence by using parentheses (which creates a grouped expression — the basic expression). To see a complete table of operator precedence as well as various caveats, see the Operator Precedence Reference page.

 JavaScript has both *binary* and *unary* operators, and one special ternary operator, the conditional operator.
 A binary operator requires two operands, one before the operator and one after the operator:
```

operand1 operator operand2
```

For example, `3 + 4` or `x * y`. This form is called an *infix* binary operator, because the operator is placed between two operands. All binary operators in JavaScript are infix.

A unary operator requires a single operand, either before or after the operator:
```

operator operand
operand operator
```

For example, `x++` or `++x`. The `operator operand` form is called a *prefix* unary operator, and the `operand operator` form is called a *postfix* unary operator. `++` and `--` are the only postfix operators in JavaScript — all other operators, like `!`, `typeof`, etc. are prefix.

Assignment operators
--------------------

 An assignment operator assigns a value to its left operand based on the value of its right operand.
 The simple assignment operator is equal (`=`), which assigns the value of its right operand to its left operand.
 That is, `x = f()` is an assignment expression that assigns the value of `f()` to `x`.

There are also compound assignment operators that are shorthand for the operations listed in the following table:

| Name | Shorthand operator | Meaning |
| --- | --- | --- |
| Assignment | `x = f()` | `x = f()` |
| Addition assignment | `x += f()` | `x = x + f()` |
| Subtraction assignment | `x -= f()` | `x = x - f()` |
| Multiplication assignment | `x *= f()` | `x = x * f()` |
| Division assignment | `x /= f()` | `x = x / f()` |
| Remainder assignment | `x %= f()` | `x = x % f()` |
| Exponentiation assignment | `x **= f()` | `x = x ** f()` |
| Left shift assignment | `x <<= f()` | `x = x << f()` |
| Right shift assignment | `x >>= f()` | `x = x >> f()` |
| Unsigned right shift assignment | `x >>>= f()` | `x = x >>> f()` |
| Bitwise AND assignment | `x &= f()` | `x = x & f()` |
| Bitwise XOR assignment | `x ^= f()` | `x = x ^ f()` |
| Bitwise OR assignment | `x |= f()` | `x = x | f()` |
| Logical AND assignment | `x &&= f()` | `x && (x = f())` |
| Logical OR assignment | `x ||= f()` | `x || (x = f())` |
| Nullish coalescing assignment | `x ??= f()` | `x ?? (x = f())` |

### Assigning to properties

 If an expression evaluates to an object, then the left-hand side of an assignment expression may make assignments to properties of that expression.
 For example:

```js
const obj = {};

obj.x = 3;
console.log(obj.x); // Prints 3.
console.log(obj); // Prints { x: 3 }.

const key = "y";
obj[key] = 5;
console.log(obj[key]); // Prints 5.
console.log(obj); // Prints { x: 3, y: 5 }.
```

For more information about objects, read Working with Objects.

If an expression does not evaluate to an object, then assignments to properties of that expression do not assign:

```js
const val = 0;
val.x = 3;

console.log(val.x); // Prints undefined.
console.log(val); // Prints 0.
```

In strict mode, the code above throws, because one cannot assign properties to primitives.

It is an error to assign values to unmodifiable properties or to properties of an expression without properties (`null` or `undefined`).

### Destructuring

 For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and
 object literals.

Without destructuring, it takes multiple statements to extract values from arrays and objects:

```js
const foo = ["one", "two", "three"];

const one = foo[0];
const two = foo[1];
const three = foo[2];
```

With destructuring, you can extract multiple values into distinct variables using a single statement:

```js
const [one, two, three] = foo;
```

### Evaluation and nesting

In general, assignments are used within a variable declaration (i.e., with `const`, `let`, or `var`) or as standalone statements).

```js
// Declares a variable x and initializes it to the result of f().
// The result of the x = f() assignment expression is discarded.
let x = f();

x = g(); // Reassigns the variable x to the result of g().
```

 However, like other expressions, assignment expressions like `x = f()` evaluate into a result value.
 Although this result value is usually not used, it can then be used by another expression.

 Chaining assignments or nesting assignments in other expressions can result in surprising behavior.
 For this reason, some JavaScript style guides discourage chaining or nesting assignments.
 Nevertheless, assignment chaining and nesting may occur sometimes, so it is important to be able to understand how they work.

 By chaining or nesting an assignment expression, its result can itself be assigned to another variable.
 It can be logged, it can be put inside an array literal or function call, and so on.

```js
let x;
const y = (x = f()); // Or equivalently: const y = x = f();
console.log(y); // Logs the return value of the assignment x = f().

console.log(x = f()); // Logs the return value directly.

// An assignment expression can be nested in any place
// where expressions are generally allowed,
// such as array literals' elements or as function calls' arguments.
console.log([0, x = f(), 0]);
console.log(f(0, x = f(), 0));
```

 The evaluation result matches the expression to the right of the `=` sign in the
 "Meaning" column of the table above. That means that `x = f()` evaluates into
 whatever `f()`'s result is, `x += f()` evaluates into the resulting sum `x + f()`,
 `x **= f()` evaluates into the resulting power `x ** y`, and so on.

 In the case of logical assignments, `x &&= f()`,
 `x ||= f()`, and `x ??= f()`, the return value is that of the
 logical operation without the assignment, so `x && f()`,
 `x || f()`, and `x ?? f()`, respectively.

 When chaining these expressions without parentheses or other grouping operators
 like array literals, the assignment expressions are **grouped right to left**
 (they are right-associative), but they are **evaluated left to right**.

 Note that, for all assignment operators other than `=` itself,
 the resulting values are always based on the operands' values *before*
 the operation.

 For example, assume that the following functions `f` and `g`
 and the variables `x` and `y` have been declared:

```js
function f() {
  console.log("F!");
  return 2;
}
function g() {
  console.log("G!");
  return 3;
}
let x, y;
```

Consider these three examples:

```js
y = x = f();
y = [f(), x = g()];
x[f()] = g();
```

#### Evaluation example 1

`y = x = f()` is equivalent to `y = (x = f())`,
 because the assignment operator `=` is right-associative.
 However, it evaluates from left to right:

1. The assignment expression `y = x = f()` starts to evaluate.
    1. The `y` on this assignment's left-hand side evaluates
     into a reference to the variable named `y`.
    2. The assignment expression `x = f()` starts to evaluate.
        1. The `x` on this assignment's left-hand side evaluates
         into a reference to the variable named `x`.
        2. The function call `f()` prints "F!" to the console and
         then evaluates to the number `2`.
        3. That `2` result from `f()` is assigned to `x`.
    3. The assignment expression `x = f()` has now finished evaluating;
     its result is the new value of `x`, which is `2`.
    4. That `2` result in turn is also assigned to `y`.
2. The assignment expression `y = x = f()` has now finished evaluating;
 its result is the new value of `y` – which happens to be `2`.
 `x` and `y` are assigned to `2`,
 and the console has printed "F!".

#### Evaluation example 2

`y = [ f(), x = g() ]` also evaluates from left to right:

1. The assignment expression `y = [ f(), x = g() ]` starts to evaluate.
    1. The `y` on this assignment's left-hand evaluates
     into a reference to the variable named `y`.
    2. The inner array literal `[ f(), x = g() ]` starts to evaluate.
        1. The function call `f()` prints "F!" to the console and
         then evaluates to the number `2`.
        2. The assignment expression `x = g()` starts to evaluate.
            1. The `x` on this assignment's left-hand side evaluates
             into a reference to the variable named `x`.
            2. The function call `g()` prints "G!" to the console and
             then evaluates to the number `3`.
            3. That `3` result from `g()` is assigned to `x`.
        3. The assignment expression `x = g()` has now finished evaluating;
         its result is the new value of `x`, which is `3`.
         That `3` result becomes the next element
         in the inner array literal (after the `2` from the `f()`).
    3. The inner array literal `[ f(), x = g() ]`
     has now finished evaluating;
     its result is an array with two values: `[ 2, 3 ]`.
    4. That `[ 2, 3 ]` array is now assigned to `y`.
2. The assignment expression `y = [ f(), x = g() ]` has
 now finished evaluating;
 its result is the new value of `y` – which happens to be `[ 2, 3 ]`.
 `x` is now assigned to `3`,
 `y` is now assigned to `[ 2, 3 ]`,
 and the console has printed "F!" then "G!".

#### Evaluation example 3

`x[f()] = g()` also evaluates from left to right.
 (This example assumes that `x` is already assigned to some object.
 For more information about objects, read Working with Objects.)

1. The assignment expression `x[f()] = g()` starts to evaluate.
    1. The `x[f()]` property access on this assignment's left-hand
     starts to evaluate.
        1. The `x` in this property access evaluates
         into a reference to the variable named `x`.
        2. Then the function call `f()` prints "F!" to the console and
         then evaluates to the number `2`.
    2. The `x[f()]` property access on this assignment
     has now finished evaluating;
     its result is a variable property reference: `x[2]`.
    3. Then the function call `g()` prints "G!" to the console and
     then evaluates to the number `3`.
    4. That `3` is now assigned to `x[2]`.
     (This step will succeed only if `x` is assigned to an object.)
2. The assignment expression `x[f()] = g()` has now finished evaluating;
 its result is the new value of `x[2]` – which happens to be `3`.
 `x[2]` is now assigned to `3`,
 and the console has printed "F!" then "G!".
### Avoid assignment chains

 Chaining assignments or nesting assignments in other expressions can
 result in surprising behavior. For this reason,
 chaining assignments in the same statement is discouraged.

 In particular, putting a variable chain in a `const`, `let`, or `var` statement often does *not* work. Only the outermost/leftmost variable would get declared; other variables within the assignment chain are *not* declared by the `const`/`let`/`var` statement.
 For example:

```js
const z = y = x = f();
```

 This statement seemingly declares the variables `x`, `y`, and `z`.
 However, it only actually declares the variable `z`.
 `y` and `x` are either invalid references to nonexistent variables (in strict mode) or, worse, would implicitly create global variables for `x` and `y` in sloppy mode.

Comparison operators
--------------------

 A comparison operator compares its operands and returns a logical value based on whether the comparison is true.
 The operands can be numerical, string, logical, or object values.
 Strings are compared based on standard lexicographical ordering, using Unicode values.
 In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison.
 This behavior generally results in comparing the operands numerically.
 The sole exceptions to type conversion within comparisons involve the `===` and `!==` operators, which perform strict equality and inequality comparisons.
 These operators do not attempt to convert the operands to compatible types before checking equality.
 The following table describes the comparison operators in terms of this sample code:

```js
const var1 = 3;
const var2 = 4;
```

Comparison operators| Operator | Description | Examples returning true |
| --- | --- | --- |
| Equal (`==`) | Returns `true` if the operands are equal. | `3 == var1`
`"3" == var1``3 == '3'` |
| Not equal (`!=`) | Returns `true` if the operands are not equal. | `var1 != 4var2 != "3"` |
| Strict equal (`===`) |
 Returns `true` if the operands are equal and of the same
 type. See also `Object.is` and
 sameness in JS.
  | `3 === var1` |
| Strict not equal (`!==`) | Returns `true` if the operands are of the same type but not equal, or are of different type. | `var1 !== "3"3 !== '3'` |
| Greater than (`>`) | Returns `true` if the left operand is greater than the right operand. | `var2 > var1"12" > 2` |
| Greater than or equal
 (`>=`)
  | Returns `true` if the left operand is greater than or equal to the right operand. | `var2 >= var1var1 >= 3` |
| Less than
 (`<`)
  | Returns `true` if the left operand is less than the right operand. | `var1 < var2"2" < 12` |
| Less than or equal
 (`<=`)
  | Returns `true` if the left operand is less than or equal to the right operand. | `var1 <= var2var2 <= 5` |

**Note:** `=>` is not a comparison operator but rather is the notation
 for Arrow functions.

Arithmetic operators
--------------------

 An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value.
 The standard arithmetic operators are addition (`+`), subtraction (`-`), multiplication (`*`), and division (`/`).
 These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces `Infinity`). For example:

```js
1 / 2; // 0.5
1 / 2 === 1.0 / 2.0; // this is true
```

In addition to the standard arithmetic operations (`+`, `-`, `*`, `/`), JavaScript provides the arithmetic operators listed in the following table:

Arithmetic operators| Operator | Description | Example |
| --- | --- | --- |
| Remainder (`%`) | Binary operator. Returns the integer remainder of dividing the two operands. | 12 % 5 returns 2. |
| Increment (`++`) |
 Unary operator. Adds one to its operand. If used as a prefix operator
 (`++x`), returns the value of its operand after adding one;
 if used as a postfix operator (`x++`), returns the value of
 its operand before adding one.
  |
 If `x` is 3, then `++x` sets `x` to 4
 and returns 4, whereas `x++` returns 3 and, only then, sets `x` to 4.
  |
| Decrement (`--`) |
 Unary operator. Subtracts one from its operand.
 The return value is analogous to that for the increment operator.
  |
 If `x` is 3, then `--x` sets `x` to 2
 and returns 2, whereas `x--` returns 3 and, only then, sets `x` to 2.
  |
| Unary negation (`-`) | Unary operator. Returns the negation of its operand. | If `x` is 3, then `-x` returns -3. |
| Unary plus (`+`) | Unary operator. Attempts to convert the operand to a number, if it is not already. | `+"3"` returns `3`.
`+true` returns `1`. |
| Exponentiation operator (`**`) |
 Calculates the `base` to the `exponent` power,
 that is, `base^exponent` | `2 ** 3` returns `8`.`10 ** -1`
 returns `0.1`.
  |

Bitwise operators
-----------------

 A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather
 than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has
 a binary representation of 1001. Bitwise operators perform their operations on such
 binary representations, but they return standard JavaScript numerical values.

The following table summarizes JavaScript's bitwise operators.

| Operator | Usage | Description |
| --- | --- | --- |
| Bitwise AND | `a & b` | Returns a one in each bit position for which the corresponding bits of both operands are ones. |
| Bitwise OR | `a | b` | Returns a zero in each bit position for which the corresponding bits of both operands are zeros. |
| Bitwise XOR | `a ^ b` | Returns a zero in each bit position for which the corresponding bits are the same. [Returns a one in each bit position for which the corresponding bits are different.] |
| Bitwise NOT | `~ a` | Inverts the bits of its operand. |
| Left shift | `a << b` | Shifts `a` in binary representation `b` bits to the left, shifting in zeros from the right. |
| Sign-propagating right shift | `a >> b` | Shifts `a` in binary representation `b` bits to the right, discarding bits shifted off. |
| Zero-fill right shift | `a >>> b` | Shifts `a` in binary representation `b` bits to the right, discarding bits shifted off, and shifting in zeros from the left. |

### Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:

* The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones).
 Numbers with more than 32 bits get their most significant bits discarded.
 For example, the following integer with more than 32 bits will be converted to a 32-bit integer:
```

Before: 1110 0110 1111 1010 0000 0000 0000 0110 0000 0000 0001
After:                 1010 0000 0000 0000 0110 0000 0000 0001
```

* Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
* The operator is applied to each pair of bits, and the result is constructed bitwise.

 For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111.
 So, when the bitwise operators are applied to these values, the results are as follows:

| Expression | Result | Binary Description |
| --- | --- | --- |
| `15 & 9` | `9` | `1111 & 1001 = 1001` |
| `15 | 9` | `15` | `1111 | 1001 = 1111` |
| `15 ^ 9` | `6` | `1111 ^ 1001 = 0110` |
| `~15` | `-16` | `~ 0000 0000 … 0000 1111 = 1111 1111 … 1111 0000` |
| `~9` | `-10` | `~ 0000 0000 … 0000 1001 = 1111 1111 … 1111 0110` |

 Note that all 32 bits are inverted using the Bitwise NOT operator, and that values with
 the most significant (left-most) bit set to 1 represent negative numbers
 (two's-complement representation). `~x` evaluates to the same value that
 `-x - 1` evaluates to.

### Bitwise shift operators

 The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be
 shifted.
 The direction of the shift operation is controlled by the operator used.

 Shift operators convert their operands to thirty-two-bit integers and return a result of either type `Number` or `BigInt`: specifically, if the type
 of the left operand is `BigInt`, they return `BigInt`;
 otherwise, they return `Number`.

The shift operators are listed in the following table.

Bitwise shift operators| Operator | Description | Example |
| --- | --- | --- |
| Left shift(`<<`) |
 This operator shifts the first operand the specified number of bits to
 the left. Excess bits shifted off to the left are discarded. Zero bits
 are shifted in from the right.
  | `9<<2` yields 36, because 1001 shifted 2 bits to
 the left becomes 100100, which is 36.
  |
| Sign-propagating right shift (`>>`) |
 This operator shifts the first operand the specified number of bits to
 the right. Excess bits shifted off to the right are discarded. Copies of
 the leftmost bit are shifted in from the left.
  | `9>>2` yields 2, because 1001 shifted 2 bits to the right
 becomes 10, which is 2. Likewise, `-9>>2` yields -3, because the sign is preserved.
  |
| Zero-fill right shift (`>>>`) |
 This operator shifts the first operand the specified number of bits to
 the right. Excess bits shifted off to the right are discarded. Zero bits
 are shifted in from the left.
  | `19>>>2` yields 4, because 10011 shifted 2 bits to the right
 becomes 100, which is 4. For non-negative numbers, zero-fill right shift
 and sign-propagating right shift yield the same result.
  |

Logical operators
-----------------

 Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value.
 However, the `&&` and `||` operators actually return the value of one of the specified operands, so if these
 operators are used with non-Boolean values, they may return a non-Boolean value.
 The logical operators are described in the following table.

Logical operators| Operator | Usage | Description |
| --- | --- | --- |
| Logical AND (`&&`) | `expr1 && expr2` |
 Returns `expr1` if it can be converted to `false`;
 otherwise, returns `expr2`. Thus, when used with Boolean
 values, `&&` returns `true` if both
 operands are true; otherwise, returns `false`.
  |
| Logical OR (`||`) | `expr1 || expr2` |
 Returns `expr1` if it can be converted to `true`;
 otherwise, returns `expr2`. Thus, when used with Boolean
 values, `||` returns `true` if either operand is
 true; if both are false, returns `false`.
  |
| Logical NOT (`!`) | `!expr` |
 Returns `false` if its single operand that can be converted
 to `true`; otherwise, returns `true`.
  |

 Examples of expressions that can be converted to `false` are those that
 evaluate to null, 0, NaN, the empty string (""), or undefined.

 The following code shows examples of the `&&` (logical AND)
 operator.

```js
const a1 = true && true; // t && t returns true
const a2 = true && false; // t && f returns false
const a3 = false && true; // f && t returns false
const a4 = false && 3 === 4; // f && f returns false
const a5 = "Cat" && "Dog"; // t && t returns Dog
const a6 = false && "Cat"; // f && t returns false
const a7 = "Cat" && false; // t && f returns false
```

The following code shows examples of the || (logical OR) operator.

```js
const o1 = true || true; // t || t returns true
const o2 = false || true; // f || t returns true
const o3 = true || false; // t || f returns true
const o4 = false || 3 === 4; // f || f returns false
const o5 = "Cat" || "Dog"; // t || t returns Cat
const o6 = false || "Cat"; // f || t returns Cat
const o7 = "Cat" || false; // t || f returns Cat
```

The following code shows examples of the ! (logical NOT) operator.

```js
const n1 = !true; // !t returns false
const n2 = !false; // !f returns true
const n3 = !"Cat"; // !t returns false
```

### Short-circuit evaluation

 As logical expressions are evaluated left to right, they are tested for possible
 "short-circuit" evaluation using the following rules:

* `false && anything` is short-circuit evaluated to false.
* `true || anything` is short-circuit evaluated to true.

 The rules of logic guarantee that these evaluations are always correct. Note that the
 *anything* part of the above expressions is not evaluated, so any side effects of
 doing so do not take effect.

 Note that for the second case, in modern code you can use the Nullish coalescing operator (`??`) that works like `||`, but it only returns the second expression, when the first one is "nullish", i.e. `null`
 or `undefined`.
 It is thus the better alternative to provide defaults, when values like `''` or `0` are valid values for the first expression, too.

BigInt operators
----------------

Most operators that can be used between numbers can be used between `BigInt` values as well.

```js
// BigInt addition
const a = 1n + 2n; // 3n
// Division with BigInts round towards zero
const b = 1n / 2n; // 0n
// Bitwise operations with BigInts do not truncate either side
const c = 40000000000000000n >> 2n; // 10000000000000000n
```

One exception is unsigned right shift (`>>>`), which is not defined for BigInt values. This is because a BigInt does not have a fixed width, so technically it does not have a "highest bit".

```js
const d = 8n >>> 2n; // TypeError: BigInts have no unsigned right shift, use >> instead
```

BigInts and numbers are not mutually replaceable — you cannot mix them in calculations.

```js
const a = 1n + 2; // TypeError: Cannot mix BigInt and other types
```

This is because BigInt is neither a subset nor a superset of numbers. BigInts have higher precision than numbers when representing large integers, but cannot represent decimals, so implicit conversion on either side might lose precision. Use explicit conversion to signal whether you wish the operation to be a number operation or a BigInt one.

```js
const a = Number(1n) + 2; // 3
const b = 1n + BigInt(2); // 3n
```

You can compare BigInts with numbers.

```js
const a = 1n > 2; // false
const b = 3 > 2n; // true
```

String operators
----------------

In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.

For example,

```js
console.log("my " + "string"); // console logs the string "my string".
```

The shorthand assignment operator `+=` can also be used to concatenate strings.

For example,

```js
let mystring = "alpha";
mystring += "bet"; // evaluates to "alphabet" and assigns this value to mystring.
```

Conditional (ternary) operator
------------------------------

 The conditional operator
 is the only JavaScript operator that takes three operands.
 The operator can have one of two values based on a condition.
 The syntax is:

```js
condition ? val1 : val2
```

 If `condition` is true, the operator has the value of `val1`.
 Otherwise it has the value of `val2`. You can use the conditional operator anywhere you would use a standard operator.

For example,

```js
const status = age >= 18 ? "adult" : "minor";
```

 This statement assigns the value "adult" to the variable `status` if
 `age` is eighteen or more. Otherwise, it assigns the value "minor" to
 `status`.

Comma operator
--------------

 The comma operator (`,`)
 evaluates both of its operands and returns the value of the last operand.
 This operator is primarily used inside a `for` loop, to allow multiple variables to be updated each time through the loop.
 It is regarded bad style to use it elsewhere, when it is not necessary.
 Often two separate statements can and should be used instead.

 For example, if `a` is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to update two variables at once.
 The code prints the values of the diagonal elements in the array:

```js
const x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const a = [x, x, x, x, x];

for (let i = 0, j = 9; i <= j; i++, j--) {
  // ^
  console.log(`a[${i}][${j}]= ${a[i][j]}`);
}
```

Unary operators
---------------

A unary operation is an operation with only one operand.

### delete

 The `delete` operator deletes an object's property.
 The syntax is:

```js
delete object.property;
delete object[propertyKey];
delete objectName[index];
```

where `object` is the name of an object, `property` is an existing property, and `propertyKey` is a string or symbol referring to an existing property.

 If the `delete` operator succeeds, it removes the property from the object.
 Trying to access it afterwards will yield `undefined`.
 The `delete` operator returns `true` if the operation is possible; it returns `false` if the operation is not possible.

```js
delete Math.PI; // returns false (cannot delete non-configurable properties)

const myObj = { h: 4 };
delete myObj.h; // returns true (can delete user-defined properties)
```

#### Deleting array elements

 Since arrays are just objects, it's technically possible to `delete` elements from them.
 This is, however, regarded as a bad practice — try to avoid it.
 When you delete an array property, the array length is not affected and other elements are not re-indexed.
 To achieve that behavior, it is much better to just overwrite the element with the value `undefined`.
 To actually manipulate the array, use the various array methods such as `splice`.

### typeof

 The `typeof` operator returns a string indicating the type of the unevaluated operand.
 `operand` is the string, variable, keyword, or object for which the type is to be returned.
 The parentheses are optional.

Suppose you define the following variables:

```js
const myFun = new Function("5 + 2");
const shape = "round";
const size = 1;
const foo = ["Apple", "Mango", "Orange"];
const today = new Date();
```

The `typeof` operator returns the following results for these variables:

```js
typeof myFun; // returns "function"
typeof shape; // returns "string"
typeof size; // returns "number"
typeof foo; // returns "object"
typeof today; // returns "object"
typeof doesntExist; // returns "undefined"
```

 For the keywords `true` and `null`, the `typeof`
 operator returns the following results:

```js
typeof true; // returns "boolean"
typeof null; // returns "object"
```

For a number or string, the `typeof` operator returns the following results:

```js
typeof 62; // returns "number"
typeof "Hello world"; // returns "string"
```

 For property values, the `typeof` operator returns the type of value the
 property contains:

```js
typeof document.lastModified; // returns "string"
typeof window.length; // returns "number"
typeof Math.LN2; // returns "number"
```

For methods and functions, the `typeof` operator returns results as follows:

```js
typeof blur; // returns "function"
typeof eval; // returns "function"
typeof parseInt; // returns "function"
typeof shape.split; // returns "function"
```

For predefined objects, the `typeof` operator returns results as follows:

```js
typeof Date; // returns "function"
typeof Function; // returns "function"
typeof Math; // returns "object"
typeof Option; // returns "function"
typeof String; // returns "function"
```

### void

 The `void` operator specifies an expression to be evaluated without returning a value. `expression` is a JavaScript expression to evaluate.
 The parentheses surrounding the expression are optional, but it is good style to use them to avoid precedence issues.

Relational operators
--------------------

A relational operator compares its operands and returns a Boolean value based on whether the comparison is true.

### in

 The `in` operator returns `true` if the specified property is in the specified object.
 The syntax is:

```js
propNameOrNumber in objectName
```

where `propNameOrNumber` is a string, numeric, or symbol expression representing a property name or array index, and `objectName` is the name of an object.

The following examples show some uses of the `in` operator.

```js
// Arrays
const trees = ["redwood", "bay", "cedar", "oak", "maple"];
0 in trees; // returns true
3 in trees; // returns true
6 in trees; // returns false
"bay" in trees; // returns false
// (you must specify the index number, not the value at that index)
"length" in trees; // returns true (length is an Array property)

// built-in objects
"PI" in Math; // returns true
const myString = new String("coral");
"length" in myString; // returns true

// Custom objects
const mycar = { make: "Honda", model: "Accord", year: 1998 };
"make" in mycar; // returns true
"model" in mycar; // returns true
```

### instanceof

 The `instanceof` operator returns `true`
 if the specified object is of the specified object type. The syntax is:

```js
objectName instanceof objectType
```

where `objectName` is the name of the object to compare to `objectType`, and `objectType` is an object type, such as `Date` or `Array`.

 Use `instanceof` when you need to confirm the type of an object at runtime.
 For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.

For example, the following code uses `instanceof` to determine whether `theDay` is a `Date` object. Because `theDay` is a `Date` object, the statements in the `if` statement execute.

```js
const theDay = new Date(1995, 12, 17);
if (theDay instanceof Date) {
  // statements to execute
}
```

Basic expressions
-----------------

All operators eventually operate on one or more basic expressions. These basic expressions include identifiers and literals, but there are a few other kinds as well. They are briefly introduced below, and their semantics are described in detail in their respective reference sections.

### this

 Use the `this` keyword to refer to the current object.
 In general, `this` refers to the calling object in a method.
 Use `this` either with the dot or the bracket notation:

```js
this["propertyName"];
this.propertyName;
```

Suppose a function called `validate` validates an object's `value` property, given the object and the high and low values:

```js
function validate(obj, lowval, hival) {
  if (obj.value < lowval || obj.value > hival) {
    console.log("Invalid Value!");
  }
}
```

You could call `validate` in each form element's `onChange` event handler, using `this` to pass it to the form element, as in the following example:

```html
<p>Enter a number between 18 and 99:</p>
<input type="text" name="age" size="3" onChange="validate(this, 18, 99);" />
```

### Grouping operator

 The grouping operator `( )` controls the precedence of evaluation in
 expressions. For example, you can override multiplication and division first, then
 addition and subtraction to evaluate addition first.

```js
const a = 1;
const b = 2;
const c = 3;

// default precedence
a + b \* c     // 7
// evaluated by default like this
a + (b \* c)   // 7

// now overriding precedence
// addition before multiplication
(a + b) \* c   // 9

// which is equivalent to
a \* c + b \* c // 9
```

### new

You can use the `new` operator to create an instance of a user-defined object type or of one of the built-in object types. Use `new` as follows:

```js
const objectName = new ObjectType(param1, param2, /\* …, \*/ paramN);
```

### super

 The `super` keyword is used to call functions on an object's parent.
 It is useful with classes to call the parent constructor, for example.

```js
super(args); // calls the parent constructor.
super.functionOnParent(args);
```

* « Previous
* Next »