DEV Community

Cover image for Best Practices while Declaring JavaScript Variables
Joseph Mania
Joseph Mania

Posted on • Originally published at techmaniac649449135.wordpress.com

Best Practices while Declaring JavaScript Variables

At first, var was the only global scope variable, but now we have let and const. Any experienced JavaScript developer will warn you against using the var scope. Don’t prompt many questions, stay with me until the last dot.

Avoid using letters.

It’s as simple as that. We need to understand what the variable stands for. Let the developer know what the value is representing. For example let fl=getFullNames(), its total different when another developer writes let fullNames=getFullNames(). It’s one of the core values while writing clean codes. Trust me, it might help you when you forget, or you want to alter something.

Always prefer const or let over var

Yes, both can be used to represent a variable, but with a different meaning. For const is used just like in other languages, the declared word is final and you cannot alter the value.

Var scope is initialized during hoisting hence might bow up some problems while working on a big project. The positive thing about let and const is that you might declare them in one block, again on the next block you declare with different values. Remember this cannot be achieved by var. Remember you can declare a variable twice when you use let.

Eg let marks=90
Function addMarks(){
Let marks=97;
Alert(marks)
//It will print 97
}
Alert(marks)

It will print the first 90.

But the best practice is to use a single variable for each name. It will help you when it comes to debugging your code. Avoid declaring these variables that you have already declared. Even when the project is large, try your level best to use a single let or constant for each sign and ents.

Declare variables directly during initialization

Here are two samples.
let marks, total
Marks=20
Total=80

Example 2:
Let marks=20; total=80

Use the second version. It shortens your code. Remember we need precise, short, and functioning code.

I believe we are now focusing only on const and lets. Always prefer to declare the variables at the top or outside the function. Your code might be easier to read. Hope at some point you will meet the error “undefined”, thus practice will save you from that error.

Avoid using words like name, constant, true, remember this is a global inbuilt js words. Kindly use your own local words.

Top comments (0)