Benefits of declaring a variable type by assignment in JavaScript

Is there any advantage in JavaScript when assigning a temporary value to a new declared variable? For instance...

var a = 0, b = ''; // Somewhere else a = 5; b = 'Goodbye'; 

against

 var a, b; // Somewhere else a = 5; b = 'Goodbye'; 

I know that assigning a variable in a declaration will set its type. But in JavaScript, this can easily be changed by assigning a value of a different type, so it really does not protect it in any way.

What are the advantages / disadvantages of the above?

+4
source share
5 answers

I believe the advantage is: order in your code. This way you will know from the very beginning of the code whose type is var.

The disadvantage is more lines of code and file size.

+4
source

Benefits of declaring a variable type in JavaScript

You cannot do this, therefore n / a.

Is there any advantage to assigning a temporary value to a newly declared variable?

Benefits:

  • It can avoid errors later if you do not install it.

Disadvantages:

  • A timeout / code / bandwidth that assigns a variable that you will never use
  • The absence of an error condition appears during testing if you cannot install it later
+2
source

There are no real advantages. And I would not say that there is a drawback if you can handle the fact that it is undefined until you install it. Understanding how types work, especially in relation to equality, occurs when you mix different types among the same operators, and cross-reference and bandwidth are more important than trying to put strict input paradigms in a dynamic language.

Now, when declaring object literals, this can save you a little hassle to declare all properties in advance.

for instance

myObject.with.way.too.much.hierarchy

If you plan to simply add these properties along the way, you will need to check for the presence of each property in this chain in any scenario where you cannot be sure that they were all defined because I am trying to access an object of a nonexistent object, even if it just checks to see if it will throw an undefined error.

So you will have something obscene:

 if(myObject && myObject.with && myObject.with.way ...//ew 

Note. I am personally inclined to declare all my vars ahead in function, but more like a self-documenting thing.

+1
source
 You have to set an initial value if you will be using any methods on the thing- var s='',A=[]; for(var i=0;i<5;i++){ s+=i; A.push(i); } 

Otherwise, with the exception of minimal documentation, this is optional.

0
source

the code may slow down, or you may get unexpected results when using the undefined variable ..

setting the value of a variable helps you when you use it by randomly checking if it has a known value or type

0
source

Source: https://habr.com/ru/post/1400390/


All Articles