Welcome to our in-depth guide on JavaScript Variables! 📝
In this lesson, we'll dive into the world of variables, learn why they're essential, and get hands-on experience with practical examples. Let's get started!
Variables are like containers in JavaScript. They allow us to store, change, and use data during the execution of our scripts.
There are three ways to declare variables in JavaScript:
var: This is the oldest and least recommended method, as it has a function scope and can lead to unintended global variables.
let: A block-scoped variable, meaning it's only available within the curly braces {}. Use this one instead of var.
const: Similar to let, but once assigned, the value cannot be changed. Use this for immutable values like PI or object references.
Here's an example of how to declare variables using each method:
// var
var name = "John";
// let
let age = 25;
// const
const PI = 3.14;Naming conventions help make our code readable and maintainable. Here are some rules to follow:
Here's a good example:
let firstName = "John";
let _secondName = "Doe";
let my_cool_variable = "Example";To assign a value to a variable, simply use the equals sign (=).
let myVariable;
myVariable = "Hello, World!";Once you've declared and assigned a value to a variable, you can access it anywhere within the scope.
let greeting = "Hello, World!";
console.log(greeting); // Outputs: Hello, World!You can change the value of a variable at any time.
let greeting = "Hello, World!";
greeting = "Hello, CodeYourCraft!";
console.log(greeting); // Outputs: Hello, CodeYourCraft!String: A sequence of characters, such as "Hello, World!".Number: Can be integer or floating-point, like 4 or 3.14.Boolean: Represents true or false values, like true or false.Null: Represents an empty object, often used to indicate the absence of a value.Undefined: Represents a variable that has been declared but not assigned a value.Object: A collection of properties, like { name: "John", age: 25 }.Which keyword is best to use for block-scoped variables in JavaScript?
What's the difference between the `var`, `let`, and `const` keywords in JavaScript?