Sunday, October 25, 2020

ไม่ต้องเสียเวลาจัด Format + เขียนโค๊ดได้ไวขึ้นด้วย Prettier Formatter

 สวัสดีครับ วันนี้มีบทความมาแนะนำเรื่องเกี่ยวกับการใช้งาน Extension เพื่อเพิ่มสปีดให้เราเขียนโค๊ดได้ไวขึ้นนั้นเอง

เพราะอะไร? จริงๆ แล้วผมเคยเห็นหลายๆคน เสียเวลา มาจัดโค๊ด มาลบช่องว่าง เคาะ intent เพราะก็อปโค๊ดจากที่อื่นมา แถมพิมพ์ก็ช้าอีก เห็นแล้วผมแอบหงุดหงิดเล็กน้อย ฮ่าๆ ผมคิดว่าเราไม่ควรมาเสียเวลาตรงนี้ เรื่องพวกนี้ให้มัน auto เลย (แต่แน่นอน สำหรับมือใหม่ การ auto มันอาจจะทำให้เค้าลืม syntax ลืม code standard ไป) แต่สำหรับคนที่พอเขียนได้ ผมคิดว่า มันช่วยประหยัดเวลามากกว่านะ

สำหรับใครที่ชื่นชอบแบบ Video สามารถดูแบบ Video ได้ผ่าน Youtube เช่นกันครับ

VSCode Extension

เนื่องจากปัจจุบัน คิดว่า VS Code น่าจะเป็น Text Editor หลักของใครหลายๆคนละ และแน่นอนมี Extension ให้เพื่อนๆ ได้เลือกใช้งานมากมาย วันนี้ผมจะมาแนะนำตัวนึงที่ชื่อว่า VS Code Prettier Formatter

เป็นการใช้ Prettier มาช่วยในการ Format โค๊ดของเราครับ (หลายๆ คนอาจจะใช้งานอยู่) แต่ก็มีบางคนที่เค้าไม่รู้ รวมถึงเพื่อนๆ น้องๆ หลายคนที่เคยเรียนคอร์สที่ผมสอน แล้วเห็นว่าทำไมมัน Format โค๊ดได้ง่ายดี แถมไม่ต้อง Save วันนี้ผมจะมาบอกวิธีครับ

  • ไม่ต้องกลัวลืม Save เพราะเราสามารถตั้ง Auto Save ได้
  • ให้มัน format โค๊ดให้เลย หลังจาก Save ไม่ต้อง format หรือจัดโค๊ดเอง
  • สามารถตั้งค่ารูปแบบ format ได้เอง เช่นจะเอา semi colon หรือไม่เอา ก็ได้ เป็นต้น

ติดตั้ง โดยเลือก ปุ่มเฟืองด้านซ้ายล่าง ของ VS Code จากนั้นเลือก => Extensions (หรือกดจากแท็ปซ้ายมือก็ได้)

จากนั้นมองหา ที่ชื่อ Prettier - Code formatter ก็ติดตั้งได้เลย

ทีนี้ เวลาเรา Format Document เราก็จะมี Option ของ Prettier มาให้เราเลือกได้เลย

VS Code Settings

ตัว VS Code Settings เราสามารถเลือกตั้งค่าได้ 2 แบบคือ แยก Project หรือตั้งแบบ User และการตั้งค่า ก็ทำผ่าน UI ของ VS Code ได้เลย หรือจะแก้ผ่าน settings.json ก็ได้เช่นกัน

ทีนี้การ setting มี 2 แบบ เช่น formatOnSave จะให้มันเซฟทุกๆไฟล์เลย หรือให้เซฟเฉพาะไฟล์ JavaScript แต่ไฟล์อื่นไม่ต้องเซฟ ก็ได้เหมือนกัน

"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
},
"editor.formatOnSave": true,

เช่น แบบด้านบน editor.formatOnSave มันจะ format code ตอนเซฟ ทุกๆไฟล์เลย แต่ถ้าเราย้ายไปอยู่ใน object ของ [javascript] หมายถึงว่า เฉพาะไฟล์ javascript จะถูก format ตอนเซฟ ไฟล์อื่นๆ จะไม่ถูก format นั่นเอง

การตั้งค่าต่างๆ

การตั้งค่าต่างๆ ทำผ่าน Settings หรือไฟล์ settings.json ได้เลยครับ

ให้มัน auto save กรณีที่บางคนชอบลืม save file

"files.autoSave": "onFocusChange"

ให้มัน auto format ตอน save

"editor.formatOnSave": true

เลือก auto save เฉพาะไฟล์ เช่น เอาแค่ js, ts, json

โดย default ให้เป็น false ไว้

"editor.formatOnSave": false
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}

สรุป

ก็เป็นตัวอย่างสั้นๆ ให้เห็นว่า การที่เราตั้งค่าให้ VS Code มัน Format Code จัดการเรื่องพวกนี้ให้เรา ก็ทำให้เราโค๊ดดิ้งได้ไวขึ้น เอาเวลาไปเขียนโค๊ด ดีกว่ามาเสียเวลาจัด เคาะช่องว่างเยอะเลย

แต่สิ่งสำคัญ แม้ว่าเราจะมี Code Formatter ช่วยจัดโค๊ดให้เรา เราก็ไม่ควรมองข้ามเรื่องโค๊ด และ style guide ที่แต่ละคน แต่ละทีมมีนะครับ

และนอกเหนือจากนี้ก็ยังมีพวก husky หรือ lint stage ที่มันช่วย format ตอนที่เราจะ commit ผ่าน pre commit ทำให้โค๊ดเรา เป็นรูปแบบเดียวกันในทีมอีกด้วย ก็ลองไปใช้กันดูนะครับ

หวังว่าจะเป็นประโยชน์กับใครหลายๆคน

❤️ Happy Coding

Source : https://devahoy.com/blog/2020/03/vscode-prettier-extension/

Visual Studio Code — Scroll beyond last line

 https://www.youtube.com/watch?v=lsJI0PPGpLY

Visual Studio Code — Insert New Line at the End of Files

 There are two easy methods to make Visual Studio Code insert a new line at the end of files:

Method I

  1. Open Visual Studio Code and go to File (Code if using a Mac) -> Preferences -> Settings; you should now be viewing a settings page

  2. Enter 'insert final newline' in to the search bar

  3. Select the checkbox under the heading 'Files: Insert Final Newline' in the 'Workspace Settings' and/or 'User Settings' tab(s) as required

Settings Page with 'Files: Insert Final Newline' checkbox selected

Method II

  1. Open Visual Studio Code and go to File (Code if using a Mac) -> Preferences -> Settings; you should now be viewing a settings page

  2. Open the JSON settings page by clicking the {} icon at the top right of the page

  3. Enter 'files.insertFinalNewline' in to the search bar of the JSON settings page

  4. Either

    • Click on the white 'edit pen' on the left hand side of the line containing the files.insertFinalNewline JSON key and select True

    or

    • Copy the line containing the files.insertFinalNewline JSON key, paste it into the right hand side JSON file under the 'User Settings' and/or 'Workspace Settings' tab(s) as required, and set its value to true

User Settings JSON with <code>files.insertFinalNewline</code> set to <code>true</code>

Final Result

In either your User Settings or Workspace Settings JSON file, you should have a line reading "files.insertFinalNewline": true, within the provided curly braces ({ }). Additionally, in the Settings page, the checkbox under the heading 'Files: Insert Final Newline' will be selected.

Visual Studio Code will now add an empty line to the end of files when being saved, if there isn't already one.


source : https://stackoverflow.com/questions/44704968/visual-studio-code-insert-new-line-at-the-end-of-files

Friday, October 9, 2020

Getting started with Sequelize and MSSQL

 

Getting started with Sequelize and MSSQL

Sequelize is an ORM which provides for interaction between a number of databases, among which is MS SQL. To manage the MS SQL communication, it leverages another library, tedious. Here are some things to help you get it set up.

JavaScript Setup

You should specify the connection properties with the sequelize parameters since, unfortunately, the standard MSSQL Connection String won’t work here. Additionally, due to the other issues I ran into, I gave up trying to get the URI paramater to work, though in theory it should be workable.

Below is a basic configuration with some extra parameters defined that you’ll probably want.

// sequelize.js
import Sequelize from 'sequelize'

// Note that you must use a SQL Server login -- Windows credentials will not work.
const sequelize = new Sequelize('MyDatabase', 'login', 'password', {
    dialect: 'mssql',
    host: 'localhost',
    port: 1433, // Default port
    dialectOptions: {
        instanceName: 'SQLEXPRESS',
        requestTimeout: 30000
    },
    pool: {
        max: 50,
        min: 0,
        idle: 10000
    }
})

export default sequelize

An easy way to get testing this is to use sequelize’s built-in authenticate() function, taken from the sequelize website and wrapped in a test

// sequelize.test.js
import sequelize from './sequelize'

describe('sequelize', () => {
    it('should connect to the database', () => {
        sequelize
            .authenticate()
            .then(function (err) {
                console.log('Database connection has been established successfully.');
            })
            .catch(function (err) {
                console.log('Unable to connect to the database:', err);
                throw err;
            });
    })
})

If you’re lucky and that worked, you can stop here. If you were like me and need more, keep reading.

Machine / Database Configuration

1) You must enable TCP/IP in SQL Server Configuration Manager

enable tcp screenshot

Help: I can’t find SQL Server Configuration Manager!

Note that if you’re on Windows 10 or a similar environment, this may be a little harder to find. Microsoft has even published a page specifically to help you with this task.

The long and short of it is that you must fully type out the name of the snap-in in the start menu:

ex: SQLServerManager12.msc You may swap out the “12” to match your version of SQL Server:

  • 2008 = 10
  • 2012 = 11
  • 2014 = 12
  • 2016 = 13

2) SQL Server must be set up to allow SQL Server Authentication as a login option

3) You must have Sql Server Browser running in Services. This allows tedious to find the connection.

(Error: SequelizeConnectionError: Failed to connect to localhost:undefined in 15000ms)

sql services screenshot

If it’s not running, don’t forget to setup Automatic start for the future!

4) The login you’re using should be mapped to the database you’re trying to access.

1) Right click the Database Server and click Properties

2) Go to the Security page

3) Under Server Authentication, choose the SQL Server and Windows Authentication mode radio button

4) Click OK

5) Restart the Database Server by right-clicking and it and selecting Restart

Written on August 18, 2016

Source : http://www.eve-corp.com/Sequelize-Mssql/

Block Comment Templates with Examples

 Block Comment Templates with Examples

(McCann)
Last Updated: August 2015


Here are the block commenting templates to use for internal and external block comments in your programs.

Toward the bottom of this document are two examples of internal block comments, along with some commentary about their quality. Hopefully they will help you understand what makes an internal block comment a good one. If you're taking a lower-level programming class, see the example code for that class for additional documentation examples.


Why Block Comments?

Consider the Java API documentation. Each class starts with a (usually lengthy) description of the purpose of the class and how it fits into the Java class hierarchy. That's a block comment. Each method has a similar block of documentation associated with it. Without these comments, the programmer would have a hard time using the class or its method effectively. You should do the same for your code. Java's API is documented using a commenting style that is compatible with a tool called Javadoc. That's great for documentation that lots of people will be referencing, but not so good for commenting one-off student programs. So, we don't use Javadoc, but we do require that you write complete, well-structured block comments for your classes and methods.

In addition, you need to place a block comment ahead of the class containing your main() method. We call this an `external' block comment because it replaces the external documentation that would normally accompany a complete program.


Using the Templates

To make entering block comments as painless as possible, we supply outlines of each type of block comment. The idea behind having these templates is that you can use your editor to add a template to your code and then just type in the appropriate information for each section in the template. This will help because it saves you some typing and makes sure you don't leave out an entire section of information.

To include these in your source code file on a lab machine, edit your source code file, position your cursor on a blank line at the point in your code where you wish to place a template, and then use your editor's file-reading command to read in the template you want. For example, in vi the command to include a file is :r filename. So, to read in the internal.txt template, you'd give the vi command of:
:r /cs/www/people/mccann/templates/internal.txt
Then all you need to do is fill in the template with the details of the method you are trying to document.

Another option is to copy the templates to your directory, delete the explanation text from your copies, and add common information to them that you'd always enter (such as your name in the external block comment template). Then you can add these "pre-editted" blocks to your program and speed up the commenting process even further.


Java Templates:

internal.txt and int.txt:

An internal block comment belongs immediately ahead of each method of your program, with two exceptions. First, main() is assumed to be covered by the external block comment. Second, if your class has a group of getters and setters, you may cover the entire group with one block comment. The file internal.txt has exactly what you see below. int.txt is just the box and section names; it's easier to import into your code, because you don't have to delete the explanations before entering your own text.

       /*---------------------------------------------------------------------
        |  Method [Method Name]
        |
        |  Purpose:  [Explain what this method does to support the correct
        |      operation of its class, and how it does it.]
        |
        |  Pre-condition:  [Any non-obvious conditions that must exist
        |      or be true before we can expect this method to function
        |      correctly.]
        |
        |  Post-condition: [What we can expect to exist or be true after
        |      this method has executed under the pre-condition(s).]
        |
        |  Parameters:
        |      parameter_name -- [Explanation of the purpose of this
        |          parameter to the method.  Write one explanation for each
        |          formal parameter of this method.]
        |
        |  Returns:  [If this method sends back a value via the return
        |      mechanism, describe the purpose of that value here, otherwise
        |      state 'None.']
        *-------------------------------------------------------------------*/



class.txt and cl.txt:

Each class you write, except the class containing main(), must have a block comment of this form ahead of it.

/*+----------------------------------------------------------------------
 ||
 ||  Class [Class Name] 
 ||
 ||         Author:  [Your Name]
 ||
 ||        Purpose:  [A description of why this class exists.  For what
 ||                   reason was it written?  Which jobs does it perform?]
 ||
 ||  Inherits From:  [If this class is a subclass of another, name it.
 ||                   If not, just say "None."]
 ||
 ||     Interfaces:  [If any predefined interfaces are implemented by
 ||                   this class, name them.  If not, ... well, you know.]
 ||
 |+-----------------------------------------------------------------------
 ||
 ||      Constants:  [Name all public class constants, and provide a very
 ||                   brief (but useful!) description of each.]
 ||
 |+-----------------------------------------------------------------------
 ||
 ||   Constructors:  [List the names and arguments of all defined
 ||                   constructors.]
 ||
 ||  Class Methods:  [List the names, arguments, and return types of all
 ||                   public class methods.]
 ||
 ||  Inst. Methods:  [List the names, arguments, and return types of all
 ||                   public instance methods.]
 ||
 ++-----------------------------------------------------------------------*/



external.txt or ext.txt:

At the top of the file containing your program's main() method, place an `external' block comment containing the following content.

/*=============================================================================
 |   Assignment:  Program #[n]:  [Assignment Title]
 |       Author:  [Your Name (Your E-mail Address)]
 |       Grader:  [Your TA or Section Leader's name]
 |
 |       Course:  [Course Number]
 |   Instructor:  L. McCann
 |     Due Date:  [Due Date and Time]
 |
 |  Description:  [Describe the program's goal, IN DETAIL.]
 |
 |     Language:  [Programming language and version used.]
 | Ex. Packages:  [List names and sources of all external packages
 |                required by this program.]
 |                
 | Deficiencies:  [If you know of any problems with the code, provide
 |                details here, otherwise clearly state that you know
 |                of no unsatisfied requirements and no logic errors.]
 *===========================================================================*/



Examples of Good and Bad Block Comments

Contrary to popular student opinion, I don't require all of the commenting as an annoyance to you. It has been estimated that about 70% of programming effort is put into the maintenance of old code, and the rest into the development of new code. It is safe to assume that, should you do some programming in your career, you will be needing to modify someone else's code to fix an old bug or to extend the code's functionality. Commenting exists to help those unfortunate programmers who have to look at the code months or years after it was written. When you write comments for your code, keep that in mind and include useful information rather than details that are plainly obvious. The future programmers will know the language; you don't need to explain what "i ≤ j" means! Instead, explain why it's important that this condition be checked at this point in the code. Do you understand the difference?

As an example, let's imagine that you're going to write a subprogram that searches a list of earthquake intensities to find the most powerful quake. I am not going to show any code for this routine; this is intentional! The internal block comment is meant to give an overview of the construction and operation of the routine. If the reader wants more detail, he or she can move on to read the code, which will have its own comments about the code itself.

A Bad Internal Block Comment

Here's our first example of a block comment for our earthquake intensity search routine. This is not an actual example from a student program, but it does (I hope!) capture most of the mistakes students make when they wait until the last minute to write a comment:
        /*---------------------------------------------------------------------
         |  Method FIND_BIGGEST_QUAKE
         |
         |  Purpose:  Find the biggest earthquake.
         |
         |  Pre-condition: Earthquakes are available.
         |
         |  Post-condition: We found the biggest one.
         |
         |  Parameters:
	 |	quakeList -- the quakes
	 |	size      -- size of the list
         |
         |  Returns:  The biggest quake
         *-------------------------------------------------------------------*/
What's wrong with this comment? Most everything! Where to start?
  • The description of the purpose of the function is useless; we could have figured as much from the name of the method alone! What we really need to know is exactly what job this method performs. For instance, it would be really nice to know what "biggest" means in this context. Largest measure on the Richter Scale? Most damage caused?
  • Pre- and Post-conditions are supposed to tell us what needs to be true before (Pre-) and after (Post-) this method executes. They need to be clear and unambiguous, not wishy-washy. These are wishy-washy.
  • The structure of the quake_list parameter is not even mentioned.
  • How is the list size measured? By number of items or by index position of the last item?
  • Exactly what about the biggest earthquake is being returned? Its position in the list? Its measured size? The entire entry from the list?
Again, the point is that anyone reading this comment will have learned almost nothing about this method. You are forcing the reader to wade through the code to learn anything of substance.

A Good Internal Block Comment

Compare the first attempt to this one:
        /*---------------------------------------------------------------------
         |  Method FIND_BIGGEST_QUAKE
         |
         |  Purpose:  Identify the earthquake from the list of earthquake
	 |	intensities (quakeList) that has the largest magnitude.
	 |	It is assumed that the given list of quake intensities is
	 |	an array-based list of unordered Richter Scale 
	 |	magnitudes; this function performs a simple sequential
	 |	search through the array to locate the position of the
	 |	largest magnitude (the largest value) in the list.
         |
         |  Pre-condition: quakeList holds 1 or more intensities; the
         |      intensities are in no particular order; numEntries holds
         |      the exact number of entries currently in the list.
         |
         |  Post-condition: quakeList and numEntries are unchanged; the 
         |      list position of the entry with the largest magnitude has 
         |      been identified; the position is within the boundaries
         |      of the array.
         |
         |  Parameters:
	 |	quakeList -- the array of earthquake magnitudes.  This
	 |		is an array of real numbers; the first magnitude
	 |		is assumed to be at index 0.
	 |	numEntries -- the quantity of magnitudes in quakeList.
         |
         |  Returns:  The index (position) of the largest earthquake
	 |	magnitude in the quakeList array.
         *-------------------------------------------------------------------*/
Obviously, this comment includes many more details. A programmer reading this comment will have a good understanding of the operation of the method and this knowledge will make reading the code easier, should the programmer find that to be necessary. (It's very possible that all they needed to know about this method was found in the comment.)

Note that the description of the subprogram includes the algorithm(s) used to carry out the work of the routine, but includes no details about the implementation of the algorithm(s). Readers who want that level of detail will need to read the code.

Also note that this comment could have been (nay, should have been) written before the subprogram was written! This is not unusual at all; when you write your code, you should be following a detailed outline that you developed first. Your block comments can be written based on your outline of the operation of the routine. In other words, there is no excuse for you to wait until the last minute to do your commenting!

source : http://u.arizona.edu/~mccann/styletemplates.html

Comment : JavaScript Documentation Standards

Comment : JavaScript Documentation Standards 

What Should Be Documented What Should Be Documented

JavaScript documentation in WordPress takes the form of either formatted blocks of documentation or inline comments.

The following is a list of what should be documented in WordPress JavaScript files:

  • Functions and class methods
  • Objects
  • Closures
  • Object properties
  • Requires
  • Events
  • File headers

Top ↑

Documenting Tips Documenting Tips

Language Language

Short descriptions should be clear, simple, and brief. Document “what” and “when” – “why” should rarely need to be included. The “why” can go in the long description if needed. For example:

Functions and closures are third-person singular elements, meaning third-person singular verbs should be used to describe what each does.

Tip:Need help remembering how to conjugate for third-person singular verbs? Imagine prefixing the function, hook, class, or method summary with “It”:

  • Good: “(It) Does something.”
  • Bad: “(It) Do something.”

Functions: What does the function do?

  • Good: Handles a click on X element.
  • Bad: Included for back-compat for X element.

@since: The recommended tool to use when searching for the version something was added to WordPress is svn blame.

If, after using these tools, the version number cannot be determined, use @since Unknown.

Code Refactoring: Do not refactor code in the file when changes to the documentation.

Top ↑

Grammar Grammar

Descriptive elements should be written as complete sentences. The one exception to this standard is file header summaries, which are intended as file “titles” more than sentences.

The serial (Oxford) comma should be used when listing elements in summaries, descriptions, and parameter or return descriptions.

Top ↑

Formatting Guidelines Formatting Guidelines

The following guidelines should be followed to ensure that the content of the doc blocks can be parsed properly for inclusion in the code reference.

Short descriptions:

Short descriptions should be a single sentence and contain no markup of any kind. If the description refers to an HTML element or tag, then it should be written as “link tag”, not “<a>”. For example: “Fires when printing the link tag in the header”.

Long descriptions:

Markdown can be used, if needed, in a long description.

@param and @return tags:

No HTML or markdown is permitted in the descriptions for these tags. HTML elements and tags should be written as “audio element” or “link tag”.

Top ↑

Line wrapping Line wrapping

DocBlock text should wrap to the next line after 80 characters of text. If the DocBlock itself is indented on the left 20 character positions, the wrap could occur at position 100, but should not extend beyond a total of 120 characters wide.

Top ↑

Aligning comments Aligning comments

Related comments should be spaced so that they align to make them more easily readable.

For example:

1
2
3
4
/**
 * @param {very_long_type} name           Description.
 * @param {type}           very_long_name Description.
 */

Top ↑

Functions Functions

Functions should be formatted as follows:

  • Summary: A brief, one line explanation of the purpose of the function. Use a period at the end.
  • Description: A supplement to the summary, providing a more detailed description. Use a period at the end.
  • @deprecated x.x.x: Only use for deprecated functions, and provide the version the function was deprecated which should always be 3-digit (e.g. @since 3.6.0), and the function to use instead.
  • @since x.x.x: Should be 3-digit for initial introduction (e.g. @since 3.6.0). If significant changes are made, additional @since tags, versions, and descriptions should be added to serve as a changelog.
  • @access: Only use for functions if private. If the function is private, it is intended for internal use only, and there will be no documentation for it in the code reference.
  • @class: Use for class constructors.
  • @augments: For class constuctors, list direct parents.
  • @mixes: List mixins that are mixed into the object.
  • @alias: If this function is first assigned to a temporary variable this allows you to change the name it’s documented under.
  • @memberof: Namespace that this function is contained within if JSDoc is unable to resolve this automatically.
  • @static: For classes, used to mark that a function is a static method on the class constructor.
  • @see: A function or class relied on.
  • @link: URL that provides more information.
  • @fires: Event fired by the function. Events tied to a specific class should list the class name.
  • @listens: Events this function listens for. An event must be prefixed with the event namespace. Events tied to a specific class should list the class name.
  • @global: Marks this function as a global function to be included in the global namespace.
  • @param: Give a brief description of the variable; denote particulars (e.g. if the variable is optional, its default) with JSDoc @param syntax. Use a period at the end.
  • @yield: For generator functions, a description of the values expected to be yielded from this function. As with other descriptions, include a period at the end.
  • @return: Note the period after the description.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * Summary. (use period)
 *
 * Description. (use period)
 *
 * @since      x.x.x
 * @deprecated x.x.x Use new_function_name() instead.
 * @access     private
 *
 * @class
 * @augments parent
 * @mixes    mixin
 *
 * @alias    realName
 * @memberof namespace
 *
 * @see  Function/class relied on
 * @link URL
 * @global
 *
 * @fires   eventName
 * @fires   className#eventName
 * @listens event:eventName
 * @listens className~event:eventName
 *
 * @param {type}   var           Description.
 * @param {type}   [var]         Description of optional variable.
 * @param {type}   [var=default] Description of optional variable with default variable.
 * @param {Object} objectVar     Description.
 * @param {type}   objectVar.key Description of a key in the objectVar parameter.
 *
 * @yield {type} Yielded value description.
 *
 * @return {type} Return value description.
 */

Top ↑

Backbone classes Backbone classes

Backbone’s extend calls should be formatted as follows:

  • @lends This tag will allow JSDoc to recognize the extend function from Backbone as a class definition. This should be placed right before the Object that contains the class definition.

Backbone’s initialize functions should be formatted as follows:

  • Summary: A brief, one line explanation of the purpose of the function. Use a period at the end.
  • Description: A supplement to the summary, providing a more detailed description. Use a period at the end.
  • @deprecated x.x.x: Only use for deprecated classes, and provide the version the class was deprecated which should always be 3-digit (e.g. @since 3.6.0), and the class to use instead.
  • @since x.x.x: Should be 3-digit for initial introduction (e.g. @since 3.6.0). If significant changes are made, additional @since tags, versions, and descriptions should be added to serve as a changelog.
  • @constructs Marks this function as the constructor of this class.
  • @augments: List direct parents.
  • @mixes: List mixins that are mixed into the class.
  • @requires: Lists modules that this class requires. Multiple @requires tags can be used.
  • @alias: If this class is first assigned to a temporary variable this allows you to change the name it’s documented under.
  • @memberof: Namespace that this class is contained within if JSDoc is unable to resolve this automatically.
  • @static: For classes, used to mark that a function is a static method on the class constructor.
  • @see: A function or class relied on.
  • @link: URL that provides more information.
  • @fires: Event fired by the constructor. Should list the class name.
  • @param: Document the arguments passed to the constructor even if not explicitly listed in initialize. Use a period at the end.
    • Backbone Models are passed attributes and options parameters.
    • Backbone Views are passed an options parameter.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Class = Parent.extend( /** @lends namespace.Class.prototype */{
    /**
     * Summary. (use period)
     *
     * Description. (use period)
     *
     * @since      x.x.x
     * @deprecated x.x.x Use new_function_name() instead.
     * @access     private
     *
     * @constructs namespace.Class
     * @augments   Parent
     * @mixes      mixin
     *
     * @alias    realName
     * @memberof namespace
     *
     * @see   Function/class relied on
     * @link  URL
     * @fires Class#eventName
     *
     * @param {Object} attributes     The model's attributes.
     * @param {type}   attributes.key One of the model's attributes.
     * @param {Object} [options]      The model's options.
     * @param {type}   attributes.key One of the model's options.
     */
    initialize: function() {
        //Do stuff.
    }
} );

If a Backbone class does not have an initialize function it should be documented by using @inheritDoc as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
 * Summary. (use period)
 *
 * Description. (use period)
 *
 * @since      x.x.x
 * @deprecated x.x.x Use new_function_name() instead.
 * @access     private
 *
 * @constructs namespace.Class
 * @memberOf   namespace
 * @augments   Parent
 * @mixes      mixin
 * @inheritDoc
 *
 * @alias    realName
 * @memberof namespace
 *
 * @see   Function/class relied on
 * @link  URL
 */
Class = Parent.extend( /** @lends namespace.Class.prototype */{
 // Functions and properties.
} );

Note: This currently doesn’t provide the expected functionality due to a bug with JSDoc’s inheritDoc tag. See the issue here

Top ↑

Local functions Local functions

At times functions will be assigned to a local variable before being assigned as a class member.

Such functions should be marked as inner functions of the namespace that uses them using ~.

The functions should be formatted as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * Function description, you can use any JSDoc here as long as the function remains private.
 *
 * @alias namespace~doStuff
 */
var doStuff = function () {
 // Do stuff.
};
 
Class = Parent.extend( /** @lends namespace.Class.prototype */{
    /**
     * Class description
     *
     * @constructs namespace.Class
     *
     * @borrows namespace~doStuff as prototype.doStuff
     */
    initialize: function() {
        //Do stuff.
    },
 
    /*
     * This function will automatically have it's documentation copied from above.
     * You should make a comment ( not a DocBlock using /**, instead use /* or // )
     * noting that you're describing this function using @borrows.
     */
    doStuff: doStuff,
} );

Top ↑

Local ancestors Local ancestors

At times classes will have Ancestors that are only assigned to a local variable. Such classes should be assigned to the namespace their children are and be made inner classes using ~.

These should be documented as follows:

Top ↑

Class members Class members

Class members should be formatted as follows:

  • Short description: Use a period at the end.
  • @since x.x.x: Should be 3-digit for initial introduction (e.g. @since 3.6.0). If significant changes are made, additional @since tags, versions, and descriptions should be added to serve as a changelog.
  • @access: If the members is private, protected or public. Private members are intended for internal use only.
  • @type: List the type of the class member.
  • @property List all properties this object has in case it’s an Object. Use a period at the end.
  • @member: Optionally use this to override JSDoc’s member detection in place of @type to force a class member.
  • @memberof: Optionally use this to override what class this is a member of.
1
2
3
4
5
6
7
8
9
10
11
12
/**
 * Short description. (use period)
 *
 * @since  x.x.x
 * @access (private, protected, or public)
 *
 * @type     {type}
 * @property {type} key Description.
 *
 * @member   {type} realName
 * @memberof className
 */

Top ↑

Namespaces Namespaces

Namespaces should be formatted as follows:

  • Short description: Use a period at the end.
  • @namespace: Marks this symbol as a namespace, optionally provide a name as an override.
  • @since x.x.x: Should be 3-digit for initial introduction (e.g. @since 3.6.0). If significant changes are made, additional @since tags, versions, and descriptions should be added to serve as a changelog.
  • @memberof: Namespace that this namespace is contained in.
  • @property: Properties that this namespace exposes. Use a period at the end.
1
2
3
4
5
6
7
8
9
10
/**
 * Short description. (use period)
 *
 * @namespace realName
 * @memberof  parentNamespace
 *
 * @since x.x.x
 *
 * @property {type} key Description.
 */

Top ↑

Inline Comments Inline Comments

Inline comments inside methods and functions should be formatted as follows:

Top ↑

Single line comments Single line comments

1
// Extract the array values.

Top ↑

Multi-line comments Multi-line comments

1
2
3
4
5
/*
 * This is a comment that is long enough to warrant being stretched over
 * the span of multiple lines. You'll notice this follows basically
 * the same format as the JSDoc wrapping and comment block style.
 */

Important note: Multi-line comments must not begin with /** (double asterisk). Use /* (single asterisk) instead.

Top ↑

File Headers File Headers

The JSDoc file header block is used to give an overview of what is contained in the file.

Whenever possible, all WordPress JavaScript files should contain a header block.

WordPress uses JSHint for general code quality testing. Any inline configuration options should be placed at the end of the header block.

1
2
3
4
5
6
7
8
9
10
11
12
/**
 * Summary. (use period)
 *
 * Description. (use period)
 *
 * @link   URL
 * @file   This files defines the MyClass class.
 * @author AuthorName.
 * @since  x.x.x
 */
 
/** jshint {inline configuration here} */

Top ↑

Supported JSDoc Tags Supported JSDoc Tags

TagDescription
@abstractThis method can be implemented (or overridden) by the inheritor.
@accessSpecify the access level of this member (private, public, or protected).
@aliasTreat a member as if it had a different name.
@augmentsThis class inherits from a parent class.
@authorIdentify the author of an item.
@borrowsThis object uses something from another object.
@callbackDocument a callback function.
@classThis function is a class constructor.
@classdescUse the following text to describe the entire class.
@constantDocument an object as a constant.
@constructsThis function member will be the constructor for the previous class.
@copyrightDocument some copyright information.
@defaultDocument the default value.
@deprecatedDocument that this is no longer the preferred way.
@descriptionDescribe a symbol.
@enumDocument a collection of related properties.
@eventDocument an event.
@exampleProvide an example of how to use a documented item.
@exportsIdentify the member that is exported by a JavaScript module.
@externalDocument an external class/namespace/module.
@fileDescribe a file.
@firesDescribe the events this method may fire.
@functionDescribe a function or method.
@globalDocument a global object.
@ignore[todo] Remove this from the final output.
@innerDocument an inner object.
@instanceDocument an instance member.
@kindWhat kind of symbol is this?
@lendsDocument properties on an object literal as if they belonged to a symbol with a given name.
@license[todo] Document the software license that applies to this code.
@linkInline tag – create a link.
@memberDocument a member.
@memberofThis symbol belongs to a parent symbol.
@mixesThis object mixes in all the members from another object.
@mixinDocument a mixin object.
@moduleDocument a JavaScript module.
@nameDocument the name of an object.
@namespaceDocument a namespace object.
@paramDocument the parameter to a function.
@privateThis symbol is meant to be private.
@propertyDocument a property of an object.
@protectedThis member is meant to be protected.
@publicThis symbol is meant to be public.
@readonlyThis symbol is meant to be read-only.
@requiresThis file requires a JavaScript module.
@returnDocument the return value of a function.
@seeRefer to some other documentation for more information.
@sinceDocuments the version at which the function was added, or when significant changes are made.
@staticDocument a static member.
@thisWhat does the ‘this’ keyword refer to here?
@throwsDescribe what errors could be thrown.
@todoDocument tasks to be completed.
@tutorialInsert a link to an included tutorial file.
@typeDocument the type of an object.
@typedefDocument a custom type.
@variationDistinguish different objects with the same name.
@versionDocuments the version number of an item.
@yieldDocument the yielded values of a generator function.

Top ↑

Unsupported JSDoc Tags Unsupported JSDoc Tags

TagWhy it’s not supported
@summaryShould not be used. See the example of how to separate a summary from the full description.
@virtualAn unsupported synonym. Use @abstract instead.
@extendsAn unsupported synonym. Use @augments instead.
@constructorAn unsupported synonym. Use @class instead.
@constAn unsupported synonym. Use @constant instead.
@defaultvalueAn unsupported synonym. Use @default instead.
@descAn unsupported synonym. Use @description instead.
@hostAn unsupported synonym. Use @external instead.
@fileoverviewAn unsupported synonym. Use @file instead.
@overviewAn unsupported synonym. Use @file instead.
@emitsAn unsupported synonym. Use @fires instead.
@funcAn unsupported synonym. Use @function instead.
@methodAn unsupported synonym. Use @function instead.
@varAn unsupported synonym. Use @member instead.
@emitsAn unsupported synonym. Use @fires instead.
@argAn unsupported synonym. Use @param instead.
@argumentAn unsupported synonym. Use @param instead.
@propAn unsupported synonym. Use @property instead.
@returnsAn unsupported synonym. Use @return instead.
@exceptionAn unsupported synonym. Use @throws instead.

Last updated: 

I realize this is new, but I found some errors. It’s great that this page exists now.

“@global: List JavaScript globals that are used within the function, with an optional description of the global.”
This is incorrect usage of the @global tag in JSDoc. To quote the JSDoc docs (no pun intended), “Use the @global tag to specify that a symbol should be documented as global.” See http://usejsdoc.org/tags-global.html

The example under Functions is incorrect when it comes to @param and @return. The type should be in braces, and optional parameters are specified by surrounding the name with brackets (in JSDoc style). It should be:

  • @param {type} var Description.
  • @param {type} [var] Description.
  • @return {type} Description.

*/
or:

  • @param {type} var – Description.
  • @param {type} [var] – Description.
  • @return {type} Description.

*/

Lastly, the style given for block comments differs from the one on the coding standards page: https://make.wordpress.org/core/handbook/coding-standards/javascript/#comments.The style on this page matches the PHP one, however. Which should be used?


source : https://make.wordpress.org/core/handbook/best-practices/inline-documentation-standards/javascript/