Courses / JavaScript
1. Variables
Understanding how to declare and use variables in JavaScript.
How It Works
Think of variables as labeled boxes where you can store different items (data). You can open the box, check what's inside, change the contents, or even take it out and use it elsewhere.
You declare a variable using `let`, `const`, or `var`.
You assign a value to the variable.
You can use the variable in expressions or functions.
You can change the value of the variable if it's declared with `let` or `var`.
See It
This code declares a variable `age`, assigns it the value `25`, and logs it to the console. It then updates `age` to `26` and logs the new value, demonstrating how variables can change.
let age = 25;
console.log(age);
age = 26;
console.log(age);Use It
You use variables to store user input data in a web form.
let userName = prompt("Enter your name:");
console.log("Hello, " + userName + "!");Variables are essential for capturing dynamic user input, allowing your application to respond to different data.
Break It
What will this print?
const score = 10;
score = 15; // Attempting to change a const variable
console.log(score);The code throws an error because a variable declared with `const` cannot be reassigned after its initial declaration, which is a rule in JavaScript to maintain constant values.
Change `const` to `let` to allow reassignment of the variable.
let score = 10;
score = 15; // Now it's valid to change the variable
console.log(score);Level Up
Block Scope with `let` and `const`: Understanding block scope helps prevent variable collisions and improves code maintainability.
Destructuring Assignment: This allows unpacking values from arrays or properties from objects into distinct variables, making code cleaner.
Template Literals: Using template literals with variables simplifies string interpolation, enhancing readability.
Prove It
Create a function that takes a number as input and returns the square of that number using a variable.
JavaScript
Variables
Variables are named storage locations for data in JavaScript.
"I need a way to keep track of values without repeating myself."
Variables in JavaScript allow you to store and manipulate data using names, making your code more readable and maintainable.
"I need a way to keep track of values without repeating myself."
Variables in JavaScript allow you to store and manipulate data using names, making your code more readable and maintainable.