JavaScript by Patrik

JavaScript Variables

Variables are containers for storing data in JavaScript. JavaScript variables can be declared in 4 ways:

  • Automatically
  • var: Declares a variable with function scope. It's less commonly used in modern JavaScript due to its potential for scope-related issues.

  • let: Declares a variable with block scope, limiting it to the block or statement in which it's defined. It allows reassignment.

  • const: Declares a constant variable with block scope. Once assigned, its value cannot be changed.

Choosing between them depends on your needs for variable scope and mutability. const is preferred when you don't intend to change the variable's value, while let is suitable for variables that need to be reassigned. var is generally avoided in modern JavaScript due to its quirks related to scope.

We'll discuss the differences in Scope, Redeclaration, and Hoisting.

...see more

The var declares a variable with function scope.

Scope of var

  • Global scope normally
  • Start to end of the function inside of the function

Redeclaration

  • Yes, can redeclare it in the same scope

Hoisting

  • Hosted at the top of the global scope
  • It can be used before the declaration
...see more

The let keyword was introduced in ES6 (2015).

Scope

  • Block scoped always
  • Start to end of the current scope anywhere

Redeclaration

  • No, can't redeclare in the same scope

Hoisting

  • Hosted at top of some private scope and only available after assigning value
  • Can not be used before the declaration
...see more

The const keyword was introduced in ES6 (2015).

Scope

  • Block scoped always
  • Start to end of the current scope anywhere

Redeclaration

  • No, can't redeclare or reinitialize it

Hoisting

  • Hosted at top of some private and only available after assigning value
  • Can not be used before the declaration
...see more

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

...see more

let is now preferred for variable declaration. It's no surprise as it comes as an improvement to var declarations. It also solves the problem with var that we just covered. Let's consider why this is so.

...see more

Before the advent of ES6, var declarations ruled. There are issues associated with variables declared with var, though. That is why new ways needed to declare variables to emerge.

Comments

Leave a Comment

All fields are required. Your email address will not be published.