DEV Community

Cover image for How To Write a Good JavaScript Code
PratyushSawan
PratyushSawan

Posted on • Updated on

How To Write a Good JavaScript Code

In this Blog, we gonna tell you the best way to write a javaScript code which I learned till my learning journey.

So, I gonna discuss 5 points which I used to write my javaScript code and it is very helpful for me to read and update my previous codeBases. And these tips can also helpful for you. So, please read once if you are a JS developer or gonna be a JS developer.


pretty js code

1. JavaScript is CaseSensitive

This means when You use your Shift or CapsLock keys it really matters. Unlike in HTML and CSS Where you can use UPPER and lowercase letters, But in JS the casing of the words matters.

Example:-

var greenDuck ="This Duck is Green";
console.log(greenduck);
Enter fullscreen mode Exit fullscreen mode

Above code will show an error

Uncaught ReferenceError: greenduck is not defined.
Enter fullscreen mode Exit fullscreen mode

2. Use camleCase Words

practice of writing phrases such that each word or abbreviation in the middle of the phrase begins with a capital letter, with no intervening spaces or punctuation. Common examples include "iPhone" and "eBay".

//variable starts with a Lowercase letter
var greenDuck;

//objects and classes start with UpperCase letter
var date = new Date();

//Constants are All-Caps
const NAME;
Enter fullscreen mode Exit fullscreen mode

3. WhiteSpace Matters (for Human)

JavaScript doesn't care about whiteSpaces but as a human, you should. So, use whiteSpaces in your code for make it more readable for humans. It is useful when you work with a team.

//With whiteSpaces(human readable)
var date = new Date();
document.body.innerHTML = "<h1>" + date + "</h1>";

//without whiteSpaces (machine Readable difficult for humans)
var date=new Date();document.body.innerHTML="<h1>"+date+"</h1>";
Enter fullscreen mode Exit fullscreen mode

4. End Each Statment with a SemiColon(;)

Technically javaScript doesn't care you use a semicolon or not except some specific situations. But if you do not use it then your code is difficult to be read for humans. So, Good practice is to use a semicolon at the end of your statement in your codebase.

  • Semicolon is just a matter of opinion Do What Works best for you

5. Use Comments Liberally.

// A single line comment starts with two slashes.

/* A multi-line comment
starts with a slash and an asterisk
and ends with an asterisk and a slash */
Enter fullscreen mode Exit fullscreen mode

This is the end. if you found this blog post helpful then, please comment and give a reaction.

Top comments (0)