Variables - potatoscript/javascript GitHub Wiki

πŸ”€ Variables in JavaScript πŸ“Š

Variables are one of the most important concepts in programming. In JavaScript, variables are used to store data values that you can use later in your program. For example, you can store numbers, text (strings), or even more complex data like objects and arrays.

In this section, we’ll dive into how variables work in JavaScript and how you can use them to make your programs more powerful and flexible.


Step 1: Declaring a Variable πŸ“

To declare (create) a variable in JavaScript, you use one of the following keywords:

  • let: Used to declare variables that can be changed (mutable).
  • const: Used to declare variables that cannot be changed (immutable).
  • var: Older way to declare variables, generally avoid using var in modern JavaScript because let and const are better.

Let’s explore how these work!

Using let to Declare a Variable:
let age = 10;
  • let creates a variable called age and assigns the value 10 to it.
  • You can later change the value of this variable if needed.
Using const to Declare a Variable:
const pi = 3.14;
  • const creates a variable called pi and assigns the value 3.14 to it.
  • Once a value is assigned to a const variable, it cannot be changed later.
Using var (Not Recommended):
var name = "John";
  • var is the traditional way to declare variables, but it can cause problems in large programs. We’ll use let or const instead.

Step 2: Types of Data You Can Store in Variables πŸ“š

Variables in JavaScript can hold different types of data, including:

  1. String: A string is used to store text.

    • Example:
      let name = "Lucy";
      
    • Strings are surrounded by quotes (" " or ' ').
  2. Number: A number is used to store numerical data.

    • Example:
      let age = 25;
      
  3. Boolean: A boolean stores either true or false.

    • Example:
      let isStudent = true;
      let isAdult = false;
      
  4. Array: An array is a collection of values (which can be of any type).

    • Example:
      let fruits = ["apple", "banana", "cherry"];
      
  5. Object: An object is a collection of key-value pairs, used to store more complex data.

    • Example:
      let person = { name: "Lucy", age: 25, isStudent: true };
      
  6. Null: Represents a variable with no value.

    • Example:
      let nothing = null;
      
  7. Undefined: A variable that has been declared but not assigned a value yet.

    • Example:
      let unknown;
      

Step 3: Reassigning a Variable πŸ”„

You can change the value of a variable declared with let.

  • Example:
    let score = 50;
    score = 100;  // Now the value of score is 100
    

However, you cannot reassign a value to a const variable:

  • Example:
    const pi = 3.14;
    pi = 3.14159;  // Error! You cannot reassign a value to a const variable.
    

Step 4: Using Variables in Expressions βž— βž•

You can use variables in mathematical expressions, such as addition, subtraction, multiplication, and division.

  • Example:
    let num1 = 10;
    let num2 = 5;
    let result = num1 + num2;  // result is 15
    

You can also use variables with strings:

  • Example:
    let greeting = "Hello";
    let name = "Lucy";
    let message = greeting + ", " + name + "!";  // "Hello, Lucy!"
    

Step 5: Displaying Variables on the Webpage 🌐

You can display the value of a variable on your webpage using document.write(), or better, with JavaScript DOM manipulation.

  • Example using document.write():
    let message = "Welcome to JavaScript!";
    document.write(message);  // This will display "Welcome to JavaScript!" on the webpage.
    

Step 6: Variable Scope 🧐

The scope of a variable refers to where in your code you can access that variable. Variables declared with let or const have block-level scope, which means they are only accessible inside the block of code where they are defined.

  • Global Scope: If a variable is declared outside of any function or block, it’s accessible everywhere in the script.

    Example:

    let globalVar = "I'm global!";
    
    function showMessage() {
        alert(globalVar);  // Can access globalVar because it's in global scope.
    }
    
  • Local Scope: If a variable is declared inside a function, it’s accessible only inside that function.

    Example:

    function showLocalMessage() {
        let localVar = "I'm local!";
        alert(localVar);  // This will work because localVar is inside the same function.
    }
    
    alert(localVar);  // Error! localVar is not accessible outside the function.
    

Step 7: Best Practices for Variables πŸ§‘β€πŸ’»

  1. Use descriptive names for your variables to make your code easy to read.

    • Bad: let a = 10;
    • Good: let age = 10;
  2. Use const whenever possible to prevent accidental reassignment.

  3. Follow naming conventions: Variables should start with a lowercase letter and use camelCase (e.g., userAge, totalAmount).

  4. Avoid using reserved keywords like let, const, and var as variable names.


Key Takeaways πŸ“

  • let allows variables to be reassigned, while const makes the variable constant (unchangeable).
  • Variables can store different types of data, such as strings, numbers, and arrays.
  • You can use variables in mathematical operations and string concatenation.
  • Understanding variable scope helps prevent bugs and errors in your code.