JS Variables 🎯

beginner
12 min

JS Variables 🎯

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!

Understanding Variables 📝

Variables are like containers in JavaScript. They allow us to store, change, and use data during the execution of our scripts.

Declaring Variables 💡

There are three ways to declare variables in JavaScript:

  1. var: This is the oldest and least recommended method, as it has a function scope and can lead to unintended global variables.

  2. let: A block-scoped variable, meaning it's only available within the curly braces {}. Use this one instead of var.

  3. 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:

javascript
// var var name = "John"; // let let age = 25; // const const PI = 3.14;

Naming Variables 📝

Naming conventions help make our code readable and maintainable. Here are some rules to follow:

  • Use only alphanumeric characters, underscores, and dollar signs.
  • Start with a lowercase letter or an underscore.
  • Avoid using JavaScript reserved keywords as variable names.

Here's a good example:

javascript
let firstName = "John"; let _secondName = "Doe"; let my_cool_variable = "Example";

Assigning Values 💡

To assign a value to a variable, simply use the equals sign (=).

javascript
let myVariable; myVariable = "Hello, World!";

Accessing Variables 💡

Once you've declared and assigned a value to a variable, you can access it anywhere within the scope.

javascript
let greeting = "Hello, World!"; console.log(greeting); // Outputs: Hello, World!

Reassigning Variables 💡

You can change the value of a variable at any time.

javascript
let greeting = "Hello, World!"; greeting = "Hello, CodeYourCraft!"; console.log(greeting); // Outputs: Hello, CodeYourCraft!

Variable Types 📝

  • 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 }.

Quiz 🎯

Quick Quiz
Question 1 of 1

Which keyword is best to use for block-scoped variables in JavaScript?

Quick Quiz
Question 1 of 1

What's the difference between the `var`, `let`, and `const` keywords in JavaScript?