Declaring Variables and Constants

Tutorial 2 of 5

Introduction

In this tutorial, we will be focusing on the basics of JavaScript - declaring variables and constants. Variables are fundamental to any programming language and they are used to store information. Constants, on the other hand, are similar to variables but, as the name implies, their value remains constant throughout the program.

By the end of this tutorial, you will learn:

  • The difference between variables and constants
  • How to declare and use variables and constants
  • Good practices when working with variables and constants

Prerequisites: Basic understanding of JavaScript syntax and programming concepts.

Step-by-Step Guide

In JavaScript, you can declare a variable using var, let or const. var was the traditional way to declare variables but with ES6, let and const were introduced.

Variables

Variables declared with var are function-scoped, meaning they are only available within the function they're declared in. Variables declared with let are block-scoped, meaning they are only available within the block they're declared in.

To declare a variable, you would do the following:

var name = "John";
let age = 20;

Constants

Constants are block-scoped like let, but once a value is assigned to a const, it cannot be changed.

To declare a constant, you would do the following:

const PI = 3.14;

Code Examples

Example 1: Variables

// Declare a variable named 'greeting' and assign a string value to it
let greeting = "Hello, World!";
console.log(greeting); // Outputs: Hello, World!

Example 2: Constants

// Declare a constant named 'maxValue' and assign a number value to it
const maxValue = 100;
console.log(maxValue); // Outputs: 100

Summary

In this tutorial, we've covered the basics of declaring variables and constants in JavaScript. We learned that variables can be declared using var or let, and constants can be declared using const. We also saw the difference between function-scoped and block-scoped variables.

Next, you can dive deeper into JavaScript by learning about data types, control flow, and functions.

Practice Exercises

  1. Declare a variable named city and assign your favorite city's name to it, then print it to the console.
  2. Declare a constant named gravity and assign the value 9.8 to it, then print it to the console.
  3. Try to assign a new value to the gravity constant and observe what happens.

Solutions

// Exercise 1
let city = "New York";
console.log(city); // Outputs: New York

// Exercise 2
const gravity = 9.8;
console.log(gravity); // Outputs: 9.8

// Exercise 3
gravity = 10; // This will throw an error because you can't reassign a value to a constant