DeveloperBreeze

Variables and Constants

Section 2.1: Syntax and Basics

Tutorial 2.1.2: Variables and Constants


Variables and Constants in JavaScript

In JavaScript, variables and constants are used to store data that your program can use and manipulate. This tutorial explains how to declare, initialize, and use variables and constants effectively.


Declaring Variables

Variables in JavaScript can be declared using three keywords: var, let, and const.

  1. var (Legacy):
  • Used in older JavaScript versions but largely replaced by let and const.
  • Example:
     var message = "Hello, World!";
     console.log(message);
  1. let (Modern):
  • Preferred for declaring variables that can change value.
  • Example:
     let age = 25;
     age = 26; // Allowed
     console.log(age); // 26
  1. const (Constants):
  • Used for variables whose value should not change.
  • Example:
     const PI = 3.14;
     console.log(PI); // 3.14

Rules for Naming Variables

  1. Must start with a letter, underscore (_), or dollar sign ($).
  • Valid: name, _age, $price
  • Invalid: 1name, @value
  1. Case-sensitive:
  • age and Age are different.
  1. Avoid JavaScript reserved keywords (e.g., let, const, var).

Variable Initialization

Variables can be declared without assigning a value. Uninitialized variables are undefined.

Example:

let greeting;
console.log(greeting); // undefined

Using let and const in Practice

  1. When to Use let:
  • Use let for variables whose value may change.
  • Example:
     let score = 10;
     score += 5; // score is now 15
  1. When to Use const:
  • Use const for constants or variables that should remain unchanged.
  • Example:
     const API_KEY = "12345";
     // API_KEY = "67890"; // Error: Assignment to constant variable

Scope of Variables

  1. Block Scope (let and const):
  • Variables are accessible only within the block they are declared in.
  • Example:
     {
       let x = 10;
       console.log(x); // 10
     }
     console.log(x); // Error: x is not defined
  1. Function Scope (var):
  • Variables are accessible within the entire function they are declared in.
  • Example:
     function test() {
       var y = 20;
       console.log(y); // 20
     }
     console.log(y); // Error: y is not defined

Best Practices

  1. Use const by default; switch to let if the value needs to change.
  2. Avoid using var in modern JavaScript.
  3. Use meaningful names for variables.

Exercise

  1. Declare a variable name using let and assign it your name. Log it to the console.
  2. Declare a constant BIRTH_YEAR with your birth year. Try to change its value and note the error.

Example:

let name = "Alice";
console.log(name);

const BIRTH_YEAR = 1990;
// BIRTH_YEAR = 2000; // Error: Assignment to constant variable

Related Posts

More content you might like

Tutorial
javascript

Comparison and Logical Operators

Example:

let age = 20;
let hasID = true;

if (age >= 18 && hasID) {
  console.log("Access granted.");
} else {
  console.log("Access denied.");
}
// Output: "Access granted."

Dec 11, 2024
Read More
Tutorial
javascript

Arithmetic Operators

Operator precedence determines the order in which operations are performed in an expression.

  • Order of Operations:

Dec 11, 2024
Read More
Tutorial
javascript

Non-Primitive Data Types (Objects, Arrays, and Functions)

  for (let fruit of fruits) {
    console.log(fruit);
  }

Functions are blocks of code designed to perform specific tasks. They are reusable and can take inputs (parameters) and return outputs.

Dec 11, 2024
Read More
Tutorial
javascript

Primitive Data Types

  • Syntax: Strings can be enclosed in single ('), double ("), or backticks (` ``).
  • Examples:
  let name = "Alice";
  let greeting = 'Hello';
  let message = `Welcome, ${name}!`; // Template literal
  console.log(message); // "Welcome, Alice!"

Dec 11, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!