0

If I am going to use the below example, should I declare a variable (initialize it with zero value in JS) or just use it normally later?


// Currency Converter

var currencyOne = 100; // $ 
var currencyTwo = 0; // Shall we do this to use as below for printing the result out or no need in JS to declare it with zero value?
var exchangeRate = 19.66; // EGP for Example

function CurrencyConverter(amount, rate) {
  return amount * rate;
}

var currencyTwo = CurrencyConverter(currencyOne, exchangeRate);   //I mean to use it here without any declaration first 

console.log(currencyTwo);



outis
  • 75,655
  • 22
  • 151
  • 221
Saoud ElTelawy
  • 197
  • 1
  • 3
  • 15
  • "*I mean to use it here without any declaration*" - that doesn't make sense to me, `var currencyTwo = …` **does** declare the variable – Bergi Oct 16 '22 at 17:40
  • 1
    Btw, these days you should prefer `const` (or `let`, if not functional programming) over `var`, and it'll ensure that you declare them only once. – Bergi Oct 16 '22 at 17:41
  • 2
    "*Shall we declare a variable with zero value*" - what advantage would this have? – Bergi Oct 16 '22 at 17:42
  • I had went through this [ Declaring variables without initialization lead to logical errors which are hard to debug sometimes.] – Saoud ElTelawy Oct 16 '22 at 17:44
  • 2
    Just write `const`. You cannot declare those variables without initialisation. – Bergi Oct 16 '22 at 17:47
  • 1
    See also "[What's the best way to initialize empty variables in JS?](/q/17652726/90527)", "[how often should a javascript variable be defined?](/q/21188843/90527)", "[If re-declaration with var will have effect on existed variable](/q/58219009/90527)", "[What is the difference between "let" and "var"?](/q/762011/90527)", … – outis Oct 16 '22 at 17:49

1 Answers1

1

First, you should use let and const, never var. As to where to declare variables, there is absolutely no point declaring variables earlier than needed, it just makes your code more complicated to understand.

Guillaume Brunerie
  • 4,676
  • 3
  • 24
  • 32
  • 1
    "*there is absolutely no point declaring variables earlier than needed*" - that seems to be subjective, some people prefer to declare all variables at the top of the function. Admittedly, they seem to be in the minority these days, but they might have had a point (that I never understood). – Bergi Oct 16 '22 at 17:49