DEV Community

Cover image for Demystifying JavaScript: let, var, and const Explained with Examples

Demystifying JavaScript: let, var, and const Explained with Examples

Jack Pritom Soren on February 16, 2024

JavaScript, being a versatile and widely-used programming language, offers several ways to declare variables, namely let, var, and const. Understan...
Collapse
 
efpage profile image
Eckehard

While everything you explained was quite correct, it can be helpful to mention, that things might be quite different in some situations.

let a = {}

a.a=10
a.b=20
a.c=a.a*a.b

console.log(a) //-> { a: 10, b: 20, c: 200 }
Enter fullscreen mode Exit fullscreen mode

"a" is an Object, properties can be used as variables, but they do not need to be declared in Javascript.

Things get even stranger if you use Classes:

class c {
  constructor(){
    this.a = 10
    this.b = 20
  }
  mul(){ return this.a * this.b }
}
let OB = new c()
console.log(OB.mul())
Enter fullscreen mode Exit fullscreen mode

Variables inside a class need to be prefixed by "this", but they do not need let or const either. Also, methods (= functions of a class ) do not need to be defined at all, you just write down the name()

Collapse
 
kvetoslavnovak profile image
kvetoslavnovak

What is the point to mix varaiables with properties and methods of an object?

Collapse
 
efpage profile image
Eckehard

The point is the different syntax and the different rules. You cannot - for example - define a constant inside a class. It lies in the history of JS, but is not helpful in any way.

In most other languages you can use the same code in a function or in a class method (= function). In JS you have to rewrite anything, even if you want to do the exact same thing. That is at least confusing.

Collapse
 
eastmann profile image
Maxim Klochkov • Edited

I think you have a mistake in your var Example - message is defined within a function scope so priniting it out in global scope will produce an error:

console.log(message); // message is not defined
Enter fullscreen mode Exit fullscreen mode