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
The this keyword is usually used within a function. In general, when the function is attached to an object as a method, this refers to the object that the method is called on. It functions like a hidden parameter that is passed to the function. this is an expression that evaluates to the object, so you can use all the object operations we introduced.
this["propertyName"];
this.propertyName;
doSomething(this);
For example, suppose a function is defined as follows:
function getFullName() {
return `${this.firstName} ${this.lastName}`;
}
We can now attach this function to an object, and it will use the properties of that object when called:
const person1 = {
firstName: "Chris",
lastName: "Martin",
};
const person2 = {
firstName: "Chester",
lastName: "Bennington",
};
// Attach the same function
person1.getFullName = getFullName;
person2.getFullName = getFullName;
console.log(person1.getFullName()); // "Chris Martin"
console.log(person2.getFullName()); // "Chester Bennington"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.
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; // 9Property accessor
The property accessor syntax gets property values on objects, using either dot notation or bracket notation.
object.property;
object["property"];
The working with objects guide goes into more details about object properties.
Optional chaining
The optional chaining syntax (?.) performs the chained operation on an object if it is defined and non-null, and otherwise short-circuits the operation and returns undefined.
This allows you to operate on a value that may be null or undefined without causing a TypeError.
maybeObject?.property;
maybeObject?.[property];
maybeFunction?.();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:
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.
super(args); // calls the parent constructor.
super.functionOnParent(args);