Frontend Development: Var, Let and Const — What's the difference?

Peter Jeon·2023년 6월 21일
0

Frontend Development

목록 보기
24/80
post-custom-banner

Var, Let and Const

When we delve into the world of JavaScript, one of the first things we encounter is how to declare variables. In JavaScript, there are three ways to do this: using var, let, or const. Each of these keywords has different attributes that make them unique and useful in different scenarios.

Here's a brief comparison of var, let, and const:

Propertyvarletconst
ScopeFunction scopeBlock scopeBlock scope
HoistingYesYes, but not initializedYes, but not initialized
Re-declarableYesNoNo
Re-assignableYesYesNo

Understanding Scope

Scope

In JavaScript, scope determines the accessibility or visibility of variables, functions, and objects in some particular code region. It controls the visibility and accessibility of variables and other such items in areas of your code.

  • Function Scope: If a variable is declared within a function using the var keyword, it can only be accessed within that function.
  • Block Scope: If a variable is declared inside a block (i.e., between '{ }'), it can only be accessed within that block. This is where let and const come in.

Var

Var

The var keyword is function scoped, meaning the variable declared with var is restricted to the function within which it is declared.

function exampleFunction() {
  var x = 1;
  if (true) {
    var x = 2;  // same variable!
    console.log(x);  // 2
  }
  console.log(x);  // 2
}

Let

let, introduced in ES6, is block-scoped. A block is chunk of code bounded by {}. A variable declared with the keyword let in a block, can only be used within that block.

let x = 1;
if (true) {
  let x = 2;  // different variable
  console.log(x);  // 2
}
console.log(x);  // 1

Const

Variables declared with the keyword const maintain constant values. const declarations share some similarities with let declarations.

const number = 42;
try {
  number = 99;
} catch(err) {
  console.log(err);
  // expected output: TypeError: invalid assignment to const `number'
  // Note - error messages will vary depending on browser
}
console.log(number);
// expected output: 42

Conclusion

In conclusion, var, let and const each have their unique uses and are all essential tools in a JavaScript developer's toolkit. While var can be function-scoped and re-declared, let is block-scoped and not re-declarable. const, on the other hand, is block-scoped, not re-declarable and, additionally, not re-assignable.

profile
As a growing developer, I am continually expanding my skillset and knowledge, embracing new challenges and technologies
post-custom-banner

0개의 댓글