Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keyboard shortcut to extract local variable in JS/TS in Visual Studio Code

I am looking for a shortcut that is available in Eclipse and called "extract local variable". It will assign the return value of the selected function invocation to a variable:

enter image description here

Is something similar available in VSC for Javascript and Typescript?

like image 292
Frederik Claus Avatar asked Dec 31 '22 06:12

Frederik Claus


1 Answers

You can use the "Refactor..." shortcut Ctrl+Shift+R to extract the expression to a constant. Example:

function main(){
  return "foo".replace("o", "a")
}

Mark the expression "foo".replace("o", "a") or the whole line → "Extract to constant in enclosing scope", name it to test and the function will be refactored to the following:

function main(){
  const test = "foo".replace("o", "a")
  return test
}

There is also the "Quick Fix" command (Ctrl+.) for fixes and refactorings.


If you want an extra shortcut just for this action, define it manually in keybindings.json (docs):

  {
    "key": "shift+ctrl+alt+r",
    "command": "editor.action.codeAction",
    "args": {
      "kind": "refactor.extract.constant"
    }
  }
like image 57
ford04 Avatar answered Jan 13 '23 19:01

ford04