Extract variable

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

Refactoring (Extract)
P42 for VS Code
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 }

Related Code Actions

Learn More

Available In