Extract variable

Extract one or more occurrences of an expression into a const variable.

Extract variable

To extract a variable, you need to select the full expression that you would like to extract, and then invoke the refactor or extract context menu.

What do I need to consider?

Extracting targets of method calls can change the 'this' reference

Consider the following example:

const anObject = {
    doSomething() {
        console.log({
            isObject: this === anObject,
            isGlobal: this === globalThis
        })
    }
}

anObject.doSomething(); // prints { isObject: true, isGlobal: false }

Extracting anObject.doSomething into a new variable extracted changes the this reference of the method call and its behavior:

const extracted = anObject.doSomething;
extracted();            // prints { isObject: false, isGlobal: true }

Assignment targets are not extracted

The left side of assignment expressions is not extracted, because it would change the program behavior.

Consider following example:

anObject.aProperty = 123; // assignment to anObject.aProperty

Extracting anObject.aProperty into a variable would mean that the assignment would change the variable, but not the object property:

const aVariable = anObject.aProperty;
aVariable = 123; // does not change anObject.aProperty

P42 does not extract such assignment targets.

Configuration

Related Code Assists

Learn More

Available In