DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

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. πŸ‘πŸ»πŸ‘πŸ»

🌚 Life is too short to browse without dark mode