DEV Community 👩‍💻👨‍💻

DEV Community 👩‍💻👨‍💻 is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for JavaScript Struggles - Part 1 | Defending Variables
‘Abdelraḥman Dwedar 👨🏻‍💻🇵🇸
‘Abdelraḥman Dwedar 👨🏻‍💻🇵🇸

Posted on • Updated on

JavaScript Struggles - Part 1 | Defending Variables

Defending variables in JS have its own way.

We have three ways to defend a variable let, var, const.

Var Let Const
Changeable ✔ ✔
Block Scope ✔ ✔
Global Scope ✔
Make Arrays ✔ ✔ ✔

We mostly use let because of the block scope which I'll explain in the below. 👇🏻


Let

The keyword let makes a variable only useable within the scope it made in, you can't use it outside that scope.

E.g.

{
    let num = 10;
    console.log(num); // Outputs: 10
}
console.log(num); // ERROR
Enter fullscreen mode Exit fullscreen mode

Var

The keyword var makes a global variable, you can use it everywhere in the code.

E.g.

{
    let num = 10;
    console.log(num); // Outputs: 10
}
console.log(num); // Outputs: 10
Enter fullscreen mode Exit fullscreen mode

Const

The keyword const makes an unchangeable variable, you can't change its value.

E.g.

const pi = 3.14159265359;
pi = 4; // ERROR
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
lukeshiru profile image
Luke Shiru

We mostly use let because it saves more memory which makes the code run faster.

That's incorrect. We use it because of the block scope. Memory has nothing to do with it, and I'm willing to bet that let is more heavy in memory than var because it needs to track the current block. Here you have an article by a DEV community member mentioning some of the reasons let/const are better than var with a comedic format. You might notice that memory has nothing to do with it.

Cheers!

Collapse
 
abdelrahman_dwedar profile image
‘Abdelraḥman Dwedar 👨🏻‍💻🇵🇸 Author

Thaks for sharing that with me, sorry for the mistake. 🙏🏻
I've heard that the block scope is taking less memory space then the general. Thanks for clearifying. 👍🏻👍🏻

Classic DEV Post from 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!