Data types

let a = 15; 
console.log(a); // 15

b = 15;
console.log(b); // 15

Why give data type to a variable when it already has a value when you declare it?

Your second example declares a global variable, whereas the first declares a variable limited to whatever scope it was defined in.

E.g.

function foo(){
  let bar = 55;
  console.log(bar);
}

foo();
console.log(bar);

// 55
// Uncaught ReferenceError: bar is not defined

As bar is declared within the foo function, it is not available outside of that.

Contrast that with this implicit global:

function foo(){
  bar = 55;
  console.log(bar);
}

foo();
console.log(bar);

// 55
// 55

To make the difference a little clearer, read:

3 Likes

Just to be clear, you are not declaring a data type, just declaring a variable.

1 Like

Iā€™d also like to add that implicit globals should better be avoided; from reading the code you can hardly tell if this is intended or if you just forgot to properly declare the variable. So if you do want to expose something to the global namespace, do so explicitly:

// Browser
window.myGlobalVariable = 42
// NodeJS
global.myGlobalVariable = 42

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.