Petko Kamenov
Petko Kamenov

Reputation: 2426

What is the shortcut in Visual Studio Code for console.log

I want to know what is the shortcut for console.log in Visual Studio Code?

Upvotes: 230

Views: 205129

Answers (27)

kasif mansuri
kasif mansuri

Reputation: 135

enter image description here

just install this extension.. select any variable press ctrl shift l...boom dome

Upvotes: 5

mohammad
mohammad

Reputation: 3

Add this to a snippet file with $0:

"Print to console": {
    "scope": "javascript,typescript",
    "prefix": "cl",
    "body": [
        "console.log($0);",
    ],
    "description": "Log output to console"
}

It seems $0 is a better approach to auto focus to that area. If you use $1 instead of $0, autocomplete doesn't work when you want to type something between parentheses (for example a variable name).

I wanted to say that in a comment but comments are unavailable for me.

Upvotes: 0

Berkin Sansal
Berkin Sansal

Reputation: 503

With the Stable Build v1.77 (March 2023), there is a new built-in command;
runCommands // run one or more commands in sequence

If you want to just bind a keyboard shortcut to create a console log statement with selected text, you can do the following:

By pressing CTRL+ALT+L , first it will copy the selected text, then insert a line after the selected text line, then output the console log statement with the selected text as a text in the left-side and as a value in the right-side.

{
    "key": "ctrl+alt+l",
    "command": "runCommands",
    "when": "editorTextFocus",
    "args": {
        "commands": [
            "editor.action.clipboardCopyAction",
            "editor.action.insertLineAfter",
            {
                "command": "editor.action.insertSnippet",
                "args": {
                    "snippet": "console.log('${CLIPBOARD}: ' + ${CLIPBOARD});"
                }
            }
        ]
    }
}
  1. File > Preferences > Keyboard Shortcuts
  2. Above the search bar on the right you'll see this icon enter image description here Click on it. (When hovered over it it says: Open keyboard shortcuts (JSON)
  3. Add this to the JSON settings:

Upvotes: 0

saeed mohseni
saeed mohseni

Reputation: 21

in vs code press ctrl+shift+P or from view menu click command palette then click snippets: configure user snippets next click javascript and edit javascript.json to below code

{
"Print to console": {
    "prefix": "log",
    "body": [
        "console.log('$1');",
        "$2"
    ],
    "description": "Log output to console"
}

}

finally in js function write log and press tab key and select 'Print to console'

Upvotes: 0

The fastest way is:

Press l and select log in pop-up list

console.log shortcut visual studio code

Now, always when you press l, you just need to press Enter to console.log()

console.log shortcut visual studio code

Upvotes: 8

Gianfranco P
Gianfranco P

Reputation: 10794

Make your own snippets in 3 easy steps.

  1. Select Configure User Snippets from the Command Palette (Ctrl + Shift + P)

    configure snippets

  2. Select Global Snippet or Snippets for <your-project>

select where to save snippets

  1. Edit the file, Save and Profit! 🤑
{
  "consoleLog": {
    "prefix": "clg",
    "body": "console.log(${1:object});",
    "description": "Displays a message in the console"
  },
}

Upvotes: 8

ChromeKK
ChromeKK

Reputation: 160

BEST COMBO

I learned the first feature of Turbo Console Log (II, III, IV were not useful for me).

Then added this snippet, that is perfectly fitting to the Turbo Console Log:

  {
    "key": "ctrl+alt+l",
    "command": "editor.action.insertSnippet",
    "when": "editorTextFocus && !editorHasSelection",
    "args": {
      "snippet": "console.log('$1')"
    }
  }

Upvotes: 5

Sebastian Sebald
Sebastian Sebald

Reputation: 16846

Update Feb, 2019:

As suggested by Adrian Smith and others: If you want to bind a keyboard shortcut to create a console log statement, you can do the following:

  1. File > Preferences > Keyboard Shortcuts
  2. Above the search bar on the right you'll see this icon enter image description here Click on it. (When hovered over it it says: Open keyboard shortcuts (JSON)
  3. Add this to the JSON settings:
{
  "key": "ctrl+shift+l",
  "command": "editor.action.insertSnippet",
  "when": "editorTextFocus",
  "args": {
    "snippet": "console.log('${TM_SELECTED_TEXT}$1')$2;"
  }
}

Pressing CTRL+SHIFT+L will output the console snippet. Also, if you already have text selected it will be put inside the log statement.


If you rather want intellisene/autocomplete:

Go to Preferences -> User Snippets -> Choose Typescript (or whatever language you want) or a 'Global Snippet File' depending on your need. A json file should open. You can add code snippets there.

There is already a snippet for console.log commented out:

"Print to console": {
    "scope": "javascript,typescript,javascriptreact",
    "prefix": "log",
    "body": [
        "console.log('$1');",
        "$2"
    ],
    "description": "Log output to console"
}

You used to have to do this for every language, but now in the 'Global Snippet File' you can set the scope property which allows you to explicitly declare multiple languages.

Should you need the exact name of the language: check it by clicking the Select Language Mode button in the right side of the VS Code bottom toolbar. It will prompt you to select a language at the top and in the process will show the JSON name of the language in parenthesis, which you can enter in the snippet file as in the example above.


Also, you should set "editor.snippetSuggestions": "top", so your snippets appear above intellisense. Thanks @Chris!

You can find snippet suggestions in Preferences -> Settings -> Text Editor -> Suggestions

Upvotes: 390

Plooftech
Plooftech

Reputation: 3

Another alternative, if you're using VSCode, is to use the Turbo Console Log extension which not only enables the Shortcut, but also smartly inserts custom text depending on your selected text. You can adjust it's settings to also log the file name/line number:

GIF Showing functionality

Obviously, installing an extension is not the same as changing keyboard shortcuts, but it's a good option if you want functionality similar to @aderchox 's Answer

Upvotes: 0

Sabunkar Tejas Sahailesh
Sabunkar Tejas Sahailesh

Reputation: 4926

All the above answers works fine, but if you don't want to change the configuration of the visual studio code, rather want auto-completion for console.log(object); you can simply use this shortcut clg and press Ctrl+Space for suggestion and hit Enter
Note : This feature is avaliable when you install JavaScript (ES6) code snippets extension.

Similarly you have auto-completion for :

  • clg for console.log(object);
  • clo for console.log('object :', object);
  • ccl for console.clear(object);
  • cer for console.error(object);
  • ctr for console.trace(object);
  • clt for console.table(object);
  • cin for console.info(object);
  • cco for console.count(label);

    (This list continues...)

    Also, Another great extension in this regard is Turbo Console Log. I'm personally using both of these on my daily basis and enjoy their combination.

References:

  1. link for JavaScript(ES6) code snippets :

https://marketplace.visualstudio.com/items?itemName=xabikos.JavaScriptSnippets

enter image description here

  1. Preview from Visual Studio Code:

enter image description here

Upvotes: 228

aderchox
aderchox

Reputation: 4074

Printing the value of a variable is very simple, but also something very repeatedly & frequently needed and done, so it necessitates the quickest of the shortcuts!

So I recommend another solution in which you don't even need to select anything. You also neither need to copy/paste the variable's name, nor need to type in a snippet's prefix. And it works for all languages too, with only a single hotkey! :) (thanks to the vscode's "when" expressions)

  • Here's a preview of how it works in action:

enter image description here

  • Here are the steps you have to take to install it:

    1. Install the multi-command extension from the extension store.

    2. Open the settings.json file of your vscode (in case you don't know how, hit Ctrl + Shift + p. This will open up a command palette at the top. Write "Preferences: Open Settings (JSON)" in it, and hit enter!) then add the below item to it (will be explained):

  // generating a print statement of the current word on the next line, in different languages
  "multiCommand.commands": [
    {
      "command": "multiCommand.jsGeneratePrint",
      "sequence": [
        "editor.action.addSelectionToNextFindMatch",
        "editor.action.clipboardCopyAction",
        "editor.action.insertLineAfter",
        {
          "command": "editor.action.insertSnippet",
          "args": {
            "snippet": "console.log(\"$CLIPBOARD: \", $CLIPBOARD);"
          }
        },
      ]
    },
    {
      "command": "multiCommand.javaGeneratePrint",
      "sequence": [
        "editor.action.addSelectionToNextFindMatch",
        "editor.action.clipboardCopyAction",
        "editor.action.insertLineAfter",
        {
          "command": "editor.action.insertSnippet",
          "args": {
            "snippet": "System.out.println(\"$CLIPBOARD: \" + $CLIPBOARD);"
          }
        },
      ]
    },
  ],
  1. Now open the keybindings.json file (Write this in the command palette: "Preferences: Open keyboard Shortcuts (JSON)") and add the below items to it (will be explained):
    {
        "key": "ctrl+b",
        "command": "multiCommand.jsGeneratePrint",
        "when": "editorTextFocus && editorLangId == javascript"
    },
    {
        "key": "ctrl+b",
        "command": "multiCommand.javaGeneratePrint",
        "when": "editorTextFocus && editorLangId == 'java'"
    }

And voila!, we're done. Now, just put the pointer on a variable's name and hit the ctrl+b (I'm comfortable with ctrl+b, but you can change it as you prefer).

  • Here's how it works (for the curious) :
    • The first snippet above: We created a "compound command" (thanks to the "multi-command" extension) which simply means a "sequence of multiple commands together as a new command". The sequence we have used is: 1. Select the current word which the pointer is at, 2. copy it to the clipboard, 3. go to the next line, 4. generate the print statement using the word already copied to the clipboard. and Voila! NOTICE however that we have to define one of these compound commands per each language, as different programming languages differ in how they print!
    • The second snippet above: We create "two different hotkeys, but with the same key combinations". Most importantly they're different in their "where" conditions(in which we have specified the language of the code "where" this hotkey must work in), and then we add each of the compound commands to its own hotkey.

You can extend this method to cover any other languages as well, by just repeating the same pattern (It can also be extended in other ways, but I won't make this answer any longer). Hope that'll save you some time. :)

Upvotes: 9

Sandeep Amarnath
Sandeep Amarnath

Reputation: 6917

Install ES7 React/Redux/GraphQL extension and then type clg + Enter/Return key for console.log()

enter image description here

Upvotes: 1

tinker
tinker

Reputation: 642

I use autohotkey to achieve the same effect, Simply type "cc" then space, and it will output a console log. Haven't tried snippets, not sure how this compares

; vscode
#IfWinActive ahk_exe Code.exe

    SetTitleMatchMode 2

    ; Move by word - Backwards
    Capslock & d:: Send ^+k
    ::cc::console.log("test321:" {+}){left}
    ::cl::logger.info("test321:" {+}){left}
    ::cd::logger.debug("test321:" {+}){left}
    ::ss::JSON.stringify(test, null, 2){ctrl down}{left 3}{ctrl up}

#IfWinActive 

Upvotes: 0

Marek W
Marek W

Reputation: 95

Type co and hit tab or enter.

Should work out of the box.

Upvotes: -1

user9895412
user9895412

Reputation:

I don't know what extension I'm using but I simply type log and hit tab to autocomplete console.log(); placing the cursor between the braces.

Upvotes: 7

Waleed Shahzaib
Waleed Shahzaib

Reputation: 1706

Type 'clg' then hit ctrl + space and hit enter, it will auto complete to console.log().
For this you only need to install an extension i.e. JavaScript (ES6) code snippets.

Upvotes: 9

zazadada
zazadada

Reputation: 9

As an alternative you can create a function easy to write that invokes the console.log and then just call that function.

 var a = funtion (x) {console.log(x)}
 a(2*2);        //prints 4

Upvotes: 0

palmaone
palmaone

Reputation: 168

clg + tab

or as mentioned above,

log + enter (second option in dropdown)

This is an old question, but I hope is useful to some one else.

Upvotes: 12

Hiran Walawage
Hiran Walawage

Reputation: 2185

Anyone looking for For advanced customizations open and edit keybindings.json

enter image description here

Click this little icon to open keybindings.json.

Use this code for generate both console.log() & to generate console.log("Word") for selected text.

{
  "key": "ctrl+shift+l",
  "command": "editor.action.insertSnippet",
  "when": "editorTextFocus",
  "args": {
    "snippet": "console.log('${TM_SELECTED_TEXT}$1')$2;"
  }
}

Upvotes: 17

Srishti Gupta
Srishti Gupta

Reputation: 1273

When you type the word log, you will see something like this:

Choosing the method that says Log to the console

Choose the one which says Log to the console in case you see different log options (that would basically be possible when you have some identifier with the name log.

Click Enter.

console.log() typed automatically!

The intellisense will do its job!

Upvotes: 12

nedemir
nedemir

Reputation: 965

Type log and hit enter. It will auto-complete console.log();

Upvotes: 94

Param Singh
Param Singh

Reputation: 1366

Here's a better solution

{
        "key": "cmd+shift+c",
        "command": "editor.action.insertSnippet",
        "when": "editorTextFocus",
        "args": {
            "snippet": "console.log('${TM_SELECTED_TEXT}', $TM_SELECTED_TEXT$1);"
        }
    }

Upvotes: 3

Ragavan Rajan
Ragavan Rajan

Reputation: 4397

The below one is currently selected text with single quotes. Hope it helps

// Place your key bindings in this file to overwrite the defaults
[{
    "key": "ctrl+shift+c",
    "command": "editor.action.insertSnippet",
    "when": "editorTextFocus",
    "args": {
        "snippet": "console.log('${TM_SELECTED_TEXT}$1')$2;"
    }

}]

Upvotes: 2

medoingthings
medoingthings

Reputation: 3015

In case anybody is interested in putting the currently selected text into the console.log() statement:

{
    "key": "cmd+shift+l",
    "command": "editor.action.insertSnippet",
    "when": "editorTextFocus",
    "args": {
      "snippet": "console.log(${TM_SELECTED_TEXT}$1)$0;"
    }
}

Upvotes: 10

Adrian Smith
Adrian Smith

Reputation: 1073

In Atom there is a nice shortcut for console.log() and I wanted the same in VS Code.

I used the solution by @kamp but it took me a while to figure out how to do it. Here are the steps I used.

  1. Go to: File > Preferences > Keyboard Shortcuts

  2. At the top of the page you will see a message that says: For advanced customizations open and edit keybindings.json

Click on link

  1. This opens two panes: the default keybindings, and your custom bindings.

Enter code in right pane

  1. Enter the code provided by @kamp

Upvotes: 26

kamp
kamp

Reputation: 585

Other way is to open keybindings.json file and add your desired key combination. In my case it's:

{
    "key": "cmd+shift+l",
    "command": "editor.action.insertSnippet",
    "when": "editorTextFocus",
    "args": {
      "snippet": "console.log($1)$0;"
    }
}

Upvotes: 23

Chris
Chris

Reputation: 58132

The top answer by @Sebastian Sebald is perfectly fine, but hitting a similar problem (not console.log specifically, but rather it "missing") I wanted to also contribute an answer.

Your prefix is indeed working - by default its log and in your case you have changed it to c. When you type log (or c) VSCode will generate a full list of "all the thingsâ„¢" based on many factors (ie I don't know what factors, probably class relevance).

Things like snippets tend to gravitate towards the bottom. To bump them to the top, despite their length, add this to your settings:

"editor.snippetSuggestions": "top"

Upvotes: 51

Related Questions