Understanding variables
Understanding variables
In JavaScript, there are three ways to declare variables: `var`, `let`, and `const`. While they may seem
similar at first glance, they each have their unique behaviors and best use cases. Let’s break down their
differences using the code snippet below.
‘var’: The Traditional Way
`var` was the original way to declare variables in JavaScript, and it's still valid in modern code. However,
its outdated, don’t be a granny!
It comes with some quirks that can lead to unexpected behavior. Variables declared with `var` are
function-scoped, meaning they are only visible within the function they are defined in (or globally if
outside a function).
Example from the code:
var genre = 'Horror';
console.log(genre); // Outputs: Horror (Don’t know what Console.log() is? Read my other post on it!)
The `genre` variable is declared using `var`, making it accessible throughout the function scope it resides
in. If declared outside of any function, it becomes a global variable. One thing to be cautious about: `var`
allows re-declaration of the same variable, which can cause issues in larger codebases.
`let` is the modern and preferred way to declare variables when you expect their values to change. It is
block-scoped, meaning it is confined within the nearest set of curly braces `{}`—whether that's a loop,
function, or conditional block.
Example:
let name = 'light';
Here, the `name` variable is declared using `let`. You can update or reassign its value, but it will only be
accessible within the block where it’s defined. Unlike `var`, `let` prevents the re-declaration of the same
variable within the same scope, which reduces errors.
`const` is another ES6 addition, used for declaring constants—variables whose values should not be
reassigned after their initial definition. Like `let`, `const` is block-scoped and has the same restriction on
re-declaration within the same block. It is ideal for defining variables that should remain constant, such as
configuration values, object references, or specific strings.
Example from the code:
const back = "it's Light Yagami!";
const number = 100;
In these lines, `back` and `number` are declared using `const`. You cannot reassign a new value to these
variables once they’re defined. However, if the variable is an object or array, its properties or elements
can still be modified (but not reassigned entirely).
Conclusion
Don’t get left behind, buy now at a half price of 9.99 for a limited time only!!! Sales are dropping
quick and time is flying bye quick, let the FOMO takeover and –
Just Kidding 😉
Choosing the right variable declaration in JavaScript is key to writing clean, bug-free code. `let` and
`const` offer more control and clarity, making them the preferred choices in most scenarios. By
understanding the scope and mutability of each declaration, you can write more robust and maintainable
JavaScript!
Happy Coding fellas!