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:
Prerequisites: Basic understanding of JavaScript syntax and programming concepts.
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 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 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;
// Declare a variable named 'greeting' and assign a string value to it
let greeting = "Hello, World!";
console.log(greeting); // Outputs: Hello, World!
// Declare a constant named 'maxValue' and assign a number value to it
const maxValue = 100;
console.log(maxValue); // Outputs: 100
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.
city
and assign your favorite city's name to it, then print it to the console.gravity
and assign the value 9.8
to it, then print it to the console.gravity
constant and observe what happens.// 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