JS Variables

HTML
CSS
C#
SQL

JavaScript Variables (var, let, const)

What is a Variable?

Variables are fundamental to all programming languages. They serve as containers for storing various types of data, such as text strings, numbers, and more. These containers allow you to set, update, and access data whenever needed. Simply put, variables are symbolic names representing values.

To create a variable, you use the `var` keyword, and the assignment operator (`=`) assigns a value to the variable. For example: `var variableName = value;`

Naming Conventions for JavaScript Variables

Follow these rules when naming a JavaScript variable:

– The name must start with a letter, underscore (_), or dollar sign ($).
– It cannot start with a number.
– It can only contain alphanumeric characters (A-z, 0-9) and underscores.
– Spaces are not allowed.
– It cannot be a JavaScript keyword or reserved word.

Declaration of JavaScript Variables

There are three ways to declare a JavaScript variable:

1. Using `var`:

  var name = “Iqra Technology”;
  var age = 26;
  var isGood = true;

   // Declaring a Variable
   var userName;

   // Assigning a value
   userName = “Amir Shaikh”;

2. Using `let` and `const` (ES6):

   // Declaring variables
   let characterName = “Harry Potter”;
   let characterAge = 11;
   let isCharacterStudent = true;

   // Declaring a constant
   const PI = 3.14;
   console.log(PI); // 3.14
  
  // Trying to reassign (this will result in an error)
  PI = 10; // Error

Unlike `var`, which declares function-scoped variables, both `let` and `const` declare variables scoped at the block level (`{}`). Block scoping means that a new scope is created within a pair of curly brackets {}.

Differences Between `var`, `let`, and `const`

1. Var:

– Traditional way of declaring variables.
– Function-scoped, not block-scoped.
– Can be reassigned and updated.
– Hoisted to the top of their scope during execution.

   var score = 80;
   function updateScore() {
   var score = 90;
   // Function-scoped
   }

2. Let:

– Introduced in ES6, offers block-scoping.
– Can be reassigned, but not re-declared in the same scope.
– Provides more predictable behavior compared to `var`.

   let count = 10;
   if (true) {
   let count = 20;
   // Block-scoped
   }

3. Const:

– Also introduced in ES6, block-scoped.
– Cannot be reassigned once declared.
– Provides a constant reference to the value.

const PI = 3.14;
   PI = 4; // Error: Cannot reassign a constant variable.

When to Use Each?

– Use `var` if you’re working with older codebases.
– Prefer `let` when you need a variable that can be reassigned.
– Use `const` when the variable’s value should remain constant.

Course Video