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

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

In defense of the modern web

I expect I'll annoy everyone with this post: the anti-JavaScript crusaders, justly aghast at how much of the stuff we slather onto modern websites; the people arguing the web is a broken platform for interactive applications anyway and we should start over;

React users; the old guard with their artisanal JS and hand authored HTML; and Tom MacWright, someone I've admired from afar since I first became aware of his work on Mapbox many years ago. But I guess that's the price of having opinions.