Understanding JavaScript Variables

JavaScript variables are fundamental to how we handle data in the language. Variables can be thought of as named containers where we can store, manipulate, and retrieve data values. In JavaScript, we have different ways of declaring variables - var, let, and const.

The 'var' Keyword

The var keyword is the oldest way to declare variables in JavaScript. It's been around since the beginning of the language.

var x = 5;
var y = 6;
var sum = x + y;
console.log(sum); // 11

In this example, we declare three variables x, y, and sum.

Note: Variables declared with var are function-scoped, meaning they exist within the function they were declared in, or globally if declared outside a function. One peculiar behaviour of var is 'hoisting', where variables can be referenced before they're declared.

The 'let' Keyword

The let keyword was introduced in ECMAScript 2015, also known as ES6. let provides block scoping, which means the variable is only available within the block where it's declared. This can be more predictable and easier to work with compared to var.

let a = 5;
let b = 6;
let product = a * b;
console.log(product); // 30

In this code snippet, a, b, and product are variables declared with let. If we tried to reference a, b, or product outside of their block, we would get an error.

The 'const' Keyword

The const keyword, also introduced in ES6, is used to declare variables that are constant, or immutable. Once a const variable is assigned, it cannot be reassigned.

const PI = 3.14159;
console.log(PI); // 3.14159

In this example, PI is a constant variable that holds the value of pi. If you try to reassign PI to another value, you would get an error.

Note: While const variables are immutable, this doesn't apply to their properties if the variable is an object. So, const objects can have properties changed or added.

Variable Naming Rules

Variable names in JavaScript have to follow certain rules:

  1. They should begin with a letter, dollar sign ($), or an underscore (_). They cannot start with a number.
  2. They can include alphanumeric characters, but no spaces or special characters, except for $ and _.
  3. Variable names are case sensitive.

For example, myVar, _myVar, my_var, $myVar are all valid variable names, but 123myVar, my var, my-var are not.

In conclusion, understanding JavaScript variables and their rules is foundational to mastering the language. The var, let, and const keywords offer different options for variable declaration and scope, each with its own use cases and quirks. As you write more JavaScript, you'll get a better feel for when to use each one.