Skip to content

Latest commit

 

History

History
68 lines (50 loc) · 2.52 KB

File metadata and controls

68 lines (50 loc) · 2.52 KB

2. JavaScript Variables


Example 1: Declaring and Assigning Variables

// Using 'let' to declare and assign a variable
let name = "John";
let age = 30;

// Using 'const' for a constant variable
const pi = 3.14;

In this example, we declare a variable named name and assign the string value "John" to it. We also declare a variable age and assign the number 30 to it. The const keyword is used to declare a constant variable pi with a value of 3.14, which cannot be reassigned.

Example 2: Updating Variables

let count = 5;
count = count + 1; // Updating the 'count' variable

Here, we declare a variable count with an initial value of 5. We then update the variable's value by adding 1 to it.

Example 3: Data Types

let message = "Hello, world!";
let isRaining = true;
let numbers = [1, 2, 3, 4, 5];
let person = { name: "Alice", age: 25 };

In this example, we declare variables with different data types:

  • message is a string.
  • isRaining is a boolean.
  • numbers is an array.
  • person is an object.

Example 4: Variable Naming and Scope

let globalVar = "I'm global";

function exampleScope() {
  let localVar = "I'm local";
  console.log(globalVar); // Accessible inside the function
  console.log(localVar);  // Accessible within the function
}

console.log(globalVar); // Accessible globally
// console.log(localVar);  // Results in an error - 'localVar' is not defined outside the function

In this example, we declare two variables: globalVar and localVar. globalVar is declared in the global scope and can be accessed both inside and outside the function. localVar is declared within the exampleScope function and is only accessible within that function, demonstrating the concept of variable scope.

Example 5: Hoisting

console.log(x); // undefined (hoisted but not initialized)
var x = 5;

// console.log(y); // ReferenceError (let and const are not hoisted)
let y = 10;

In this example, the var variable x is hoisted to the top of the current scope, but it's not initialized yet, so it's undefined. The let variable y is not hoisted, and attempting to access it before declaration results in a ReferenceError.

These examples illustrate how to declare, assign, and use variables in JavaScript, covering various data types, scoping, and hoisting. Understanding these concepts is essential for working with variables effectively in JavaScript.