JavaScript

var Vs let in JavaScript

var Vs let in JavaScript

The main difference is the scope rules:

🔹The let variable can only be available inside the scope it's declared, they are scoped to the immediate enclosing block denoted by { }

🔸The var variable belongs to the global scope or the local scope if they are declared inside a function.

❌ There's also a difference when creating global properties.

Example:

var foo = "I'm added to the global obj as a property.";


console.log(window.foo); / /I'm added to the global obj as a property.


let foo = "I'm not added to the global obj as a property."

console.log(window.foo); // undefined . .

🔸Besides scoping rules and global object creation, there are a few other interesting functionalities to note when comparing let vs var like hoisting, and declaration.

❌ Which variable do you prefer and why?

Gigi Codes

Gigi | React Developer🔺 Mentor 🇻🇪 Venezolana📍San Francisco, Ca 👩🏼‍💻 Frontend Engineer @forethought.ai