JavaScript Variables
JavaScript Basics

JavaScript Variables

JavaScript Variables

Variables in JavaScript are essentially containers for storing data values. You can declare JavaScript variables in four different ways:

  1. Automatically: By assigning a value directly to a variable name without using var, let, or const, though this method is not recommended as it can lead to unintended global variables.
  2. Using var: Declares a variable with function-scope or globally scoped if declared outside of a function.
  3. Using let: Declares a block-scoped local variable, meaning the variable is limited to the scope of the block in which it is declared.
  4. Using const: Similar to let in terms of block scope, but establishes a variable that cannot be reassigned after its initial value is set.

In JavaScript, if you assign values to variables without first declaring them with var, let, or const, they are automatically created in the global scope. This can lead to unexpected results and bugs, especially in larger applications, due to potential conflicts with other global variables.

Example:

  • x = 5; assigns 5 to x.
  • y = 6; assigns 6 to y.
  • z = x + y; calculates the sum of x and y, assigning the result, 11, to z.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>

<p>In this example, x, y, and z are undeclared.</p>
<p>They are automatically declared when first used.</p>

<p id="demo"></p>

<script>
x = 5;
y = 6;
z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>

</body>
</html>

When using the var keyword, the variables are explicitly declared, which helps manage their scope better than undeclared variables. var allows the variables to be function-scoped or globally scoped if declared outside any function.

Example using var:

  • var x = 5; declares x and assigns it the value 5.
  • var y = 6; declares y and assigns it the value 6.
  • var z = x + y; declares z and computes the sum of x and y, which results in z storing the value 11.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>

<p>In this example, x, y, and z are variables.</p>

<p id="demo"></p>

<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>

</body>
</html>

Note

The var keyword was used in all JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 2015.

The var keyword should only be used in code written for older browsers.

Example using let

let x = 5;
let y = 6;
let z = x + y;

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>

<p>In this example, x, y, and z are variables.</p>

<p id="demo"></p>

<script>
let x = 5;
let y = 6;
let z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>

</body>
</html>

Example using const

const x = 5;
const y = 6;
const z = x + y

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>

<p>In this example, x, y, and z are variables.</p>

<p id="demo"></p>

<script>
const x = 5;
const y = 6;
const z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>

</body>
</html>

Mixed Example

const price1 = 5;
const price2 = 6;
let total = price1 + price2;

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>In this example, price1, price2, and total are variables.</p>

<p id="demo"></p>

<script>
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
document.getElementById("demo").innerHTML =
"The total is: " + total;
</script>

</body>
</html>

The variables price1 and price2 are defined using the const keyword, ensuring their values remain constant and immutable, which enhances stability in the code. On the other hand, the variable total is declared with the let keyword, offering flexibility as its value can be modified to accommodate dynamic calculations within the application.

When to Use var, let, or const?

When deciding between var, let, or const for declaring variables in JavaScript, here's a concise guide:

  1. Always declare variables to ensure scope is controlled and to avoid global variable creation unintentionally.
  2. Use const for variables that should not be changed after their initial assignment. This helps maintain data integrity throughout your code.
  3. Use const for data types that won't change their reference, like arrays and objects, even though their contents might be mutable.
  4. Opt for let when you need a variable that might be reassigned, such as counters in loops or values that change based on conditions.
  5. Resort to var only if you need compatibility with older browsers that do not support let or const.

Just Like Algebra

Just like in algebra, variables hold values:

let x = 5;
let y = 6;

Just like in algebra, variables are used in expressions:

let z = x + y;

From the example above, you can guess that the total is calculated to be 11.

JavaScript Identifiers

JavaScript variables are identified by unique names called identifiers, which can range from concise (like x and y) to more descriptive (such as age, sum, totalVolume). Here are the key guidelines for naming JavaScript identifiers positively:

  • Identifiers can include letters, digits, underscores, and dollar signs.
  • They should start with a letter, though $ and _ are also permissible starting characters.
  • Identifier names are case-sensitive, making 'y' and 'Y' distinct variables.
  • Avoid using reserved words as identifiers to prevent conflicts with JavaScript's syntax.

Remember, JavaScript identifiers are case-sensitive, enhancing the precision in variable naming.

The Assignment Operator

In JavaScript, the equal sign (=) serves as an "assignment" operator, rather than an "equal to" operator. This distinction is crucial, especially when comparing it to algebraic principles where such expressions might seem illogical.

For example, in JavaScript, x = x + 5 is a valid statement. It calculates x + 5 and then updates x with this new value, effectively increasing the value of x by 5.

Note: The operator for checking equality in JavaScript is ==, which compares two values to see if they are equivalent.

JavaScript Data Types

In JavaScript, variables can store various data types including numbers like 100 and text values known as strings, such as "John Doe". When considering the basic types, it's helpful to focus primarily on numbers and strings:

  • Strings are enclosed in either double or single quotes. For example, "Hello" or 'World'.
  • Numbers are written without quotes, like 123 or 10.2.

It's important to remember that if you enclose a number in quotes, JavaScript will treat it as a string, thus "123" becomes a text string, not a numerical value.

Example

const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!'

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>Strings are written with quotes.</p>
<p>Numbers are written without quotes.</p>

<p id="demo"></p>

<script>
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';

document.getElementById("demo").innerHTML =
pi + "<br>" + person + "<br>" + answer;
</script>

</body>
</html>

Declaring a JavaScript Variable

Declaring a variable in JavaScript is known as "declaring" a variable. You can declare a JavaScript variable using either the var or let keyword:

  • var carName;
  • let carName;

Initially, after declaration, the variable is undefined, meaning it has no value assigned.

To give the variable a value, you use the assignment operator (=):

carName = "Volvo";

Alternatively, you can declare and assign a value to the variable simultaneously:

let carName = "Volvo";
For example, if you create a variable named carName and assign it the value "Volvo," you can then display this value in an HTML paragraph with the ID "demo" to show the result on a webpage.

Example

<p id="demo"></p>

<script>
let carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>Create a variable, assign a value to it, and display it:</p>

<p id="demo"></p>

<script>
let carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>

One Statement, Many Variables

In JavaScript, you can declare multiple variables in a single statement by starting with the let keyword and separating each variable with a comma. This approach makes your code cleaner and easier to read.

let carName = "Volvo", carModel = "XC90", carColor = "Black";

This single line declares three variables (carName, carModel, carColor) and assigns values to each, effectively consolidating multiple declaration statements into one concise line.

Example

let person = "John Doe", carName = "Volvo", price = 200;

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>

<p>You can declare many variables in one statement.</p>

<p id="demo"></p>

<script>
let person = "John Doe", carName = "Volvo", price = 200;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>

A declaration can span multiple lines:

Example

let person = "John Doe",
carName = "Volvo",
price = 200;

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>You can declare many variables in one statement.</p>

<p id="demo"></p>

<script>
let person = "John Doe",
carName = "Volvo",
price = 200;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>

Value = undefined

In JavaScript, when you declare a variable without assigning a value to it, the default value is undefined. This is common in scenarios where the actual value will be determined later, such as through calculations or user inputs.

Example:

let carName;

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>A variable without a value has the value of:</p>
<p id="demo"></p>

<script>
let carName;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>

Re-Declaring JavaScript Variables

In JavaScript, re-declaring a variable using var within the same scope does not reset its value. This feature can be particularly useful in larger scripts where the same variable might be declared in different parts of the code without losing its initial assigned value.

Example

var carName = "Volvo";
var carName;

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>If you re-declare a JavaScript variable, it will not lose its value.</p>

<p id="demo"></p>

<script>
var carName = "Volvo";
var carName;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>

Note

You cannot re-declare a variable declared with let or const.

This will not work:

let carName = "Volvo";
let carName;

JavaScript Arithmetic

As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:Examplelet x = 5 + 2.

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>The result of adding 5 + 2 + 3 is:</p>
<p id="demo"></p>

<script>
let x = 5 + 2 + 3;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

You can also add strings, but strings will be concatenated:

Example

let x = "John" + " " + "Doe";

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>The result of adding "John" + " " + "Doe" is:</p>
<p id="demo"></p>

<script>
let x = "John" + " " + "Doe";
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Also try this:

Example

let x = "5" + 2 + 3;

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>The result of adding "5" + 2 + 3 is:</p>
<p id="demo"></p>

<script>
let x = "5" + 2 + 3;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Now try this:

Example

let x = 2 + 3 + "5";

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>The result of adding 2 + 3 + "5" is:</p>
<p id="demo"></p>

<script>
let x = 2 + 3 + "5";
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

JavaScript Dollar Sign $

Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable names:

Example

let $ = "Hello World";
let $$$ = 2;
let $myMoney = 5;

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>The dollar sign is treated as a letter in JavaScript names.</p>

<p id="demo"></p>

<script>
let $$$ = 2;
let $myMoney = 5;
document.getElementById("demo").innerHTML = $$$ + $myMoney;
</script>

</body>
</html>

While $ is a valid character to start variable names and function identifiers, its popularity soared with the rise of jQuery, a JavaScript library.

In jQuery, $ is used as a shorthand or alias for jQuery(), the main function in the library. This function is versatile, primarily used to select and manipulate HTML elements based on CSS selectors. For example, $("p") in jQuery means "select all <p> elements on the page," allowing for efficient DOM manipulation. This usage has influenced other libraries and frameworks, where $ is often employed for similar shorthand notations, reflecting its utility and ease of use in JavaScript coding practices.

JavaScript Underscore (_)

Since JavaScript treats underscore as a letter, identifiers containing _ are valid variable names:

Example

let _lastName = "Johnson";
let _x = 2;
let _100 = 5;

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>The underscore is treated as a letter in JavaScript names.</p>

<p id="demo"></p>

<script>
let _x = 2;
let _100 = 5;

document.getElementById("demo").innerHTML = _x + _100;
</script>

</body>
</html>

In JavaScript, using an underscore (_) at the beginning of variable names is a common convention among developers to indicate that a variable or a method is meant to be private or protected. This convention is not enforced by JavaScript's syntax or semantics, as JavaScript does not support true private attributes natively in older versions, but it signals to other developers that the variable or method should not be accessed directly from outside the class or function in which it is declared.

Take a look into your desired course