JavaScript Fundamentals / JavaScript Basics

Variables

📦 Understanding Variables

A variable is a label that references a value like a number or string. Before using a variable, you need to declare it.

In JavaScript, variable names follow these rules:

  • Variable names are case-sensitive. This means that the message and Message are different variables.

  • Variable names can only contain (a-z, A-Z), (0-9), (_), or ($) and cannot contain spaces. Also, variable names must begin with a letter, an underscore (_) or a dollar sign ($).

  • Variable names cannot use the reserved words.


🛠️ Declaring a variable

To declare a variable, you use the var , let, constkeyword followed by the variable name .

✅ You can use thevar keyword to declare a variable like this:

var variableName;

A variable name can be any valid identifier. For example:

var message;

By default, a variable has a special value undefined if you don’t assign it a value.

✅ You can use the let keyword to declare a variable like this:

let message;

It’s a good practice to use the let keyword to declare a variable.

✅A constant holds a value that doesn’t change. To declare a constant, you use the const keyword. When defining a constant, you need to initialize it with a value immediately. For example:

const workday = 5;

Once you define a constant, you cannot change its value.


🏷️ Initializing a variable

After declaring a variable, you can initialize it with a value. To initialize a variable, you specify the variable name, followed by an equals sign (=) and a value:

variableName = initialValue;

For example,

let message;
message = "Hello";
  • JavaScript allows you to declare two or more variables using a single statement. To separate two variable declarations, you use a comma (,) like this:

let message = "Hello",
    counter = 100;

🧩 Changing a variable

After declaring or initializing a variable, you can change its value by setting a different value. For example:

let message = "Hello";
message = 'Bye';

♦️Undefined vs. undeclared variables

  • An undefined variable is a variable that has been declared but has not been initialized with a value. For example:

let message;
console.log(message);// undefined

In this example, the message variable is declared but not initialized. Therefore, the message variable is undefined.

  • In contrast, an undeclared variable is a variable that has not been declared. For example:

console.log(counter);
console.log(counter);
            ^
ReferenceError: counter is not defined

In this example, the counter variable has not been declared. Hence, accessing it causes a ReferenceError.