Javascript Let and Const

Rate this post

Trebuie modificat!!
Pana la EcmaScript.. the only way to declare a variable in JavaScript was to use the keyword var.

What is hoisting in JavaScript with example?

Hoisting is a result of how JavaScript is interpreted by your browser. Essentially, before any JavaScript code is executed, all variables declared with var are “hoisted”, which means they’re raised to the top of the function scope.

What do you expect to be the output from running getClothing(false)?

function getClothing(isCold) {
if (isCold) {
var freezing = ‘Grab a jacket!’;
} else {
var hot = ‘It’s a shorts kind of day.’;

Astefel ca codul devine
function getClothing(isCold) {
var freezing, hot;
if (isCold) {
freezing = ‘Grab a jacket!’;
} else {
hot = ‘It’s a shorts kind of day.’;

Let and const

Variables declared with let and const eliminate this specific issue of hoisting because they’re scoped to the block, not to the function. Previously, when you used var, variables were either scoped globally or locally to an entire function scope.

!!!Variables declared with let and const are only available within the block they’re declared.

Rules for using let and const

let and const also have some other interesting properties.

Variables declared with let can be reassigned, but can’t be redeclared in the same scope.
Variables declared with const must be assigned an initial value, but can’t be redeclared in the same scope, and can’t be reassigned.

What do you expect to be output from running the following code?

let instructor = ‘James’;
instructor = ‘Richard’;

Use cases

Wwhen should you use let and const?

The general rule of thumb is as follows:

use let when you plan to reassign new values to a variable, and
use const when you don’t plan on reassigning new values to a variable.

!!! Since const is the strictest way to declare a variable, we suggest that you always declare variables with const because it’ll make your code easier to reason about since you know the identifiers won’t change throughout the lifetime of your program. If you find that you need to update a variable or change it, then go back and switch it from const to let.


Is there any reason to use var anymore?

There are some arguments that can be made for using var in situations where you want to globally define variables, but this is often considered bad practice and should be avoided.

Hello there!

I hope you find this post useful!

I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.

If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!

subscribe youtube

Leave a Comment