Variables are fundamental elements in every programming language that allow storage and manipulation of data. They represent memory locations used to store various types of information, including numbers, text, logical values, objects, and more. In JavaScript, variables enable programmers to store data in computer memory and manipulate it based on program requirements. For example, variables are used in programs to:
- Store user data
- Perform mathematical operations
- Manage user interface elements
When learning any programming language, understanding the
importance of variables is crucial. Imagine variables as memory boxes. Each box
can hold different types of data, and you cannot put letters into a box meant
for numbers. In JavaScript, the type of memory box, variable; you use depends
on the value assigned to it. Here’s an example:
let myVariable = 10;
In this case, the variable myVariable is assigned the value 10, and the JavaScript interpreter treats it as a number. Note that variable names can be any combination of letters, numbers, and underscores. It’s a good practice to start variable names with a lowercase letter, CamelCase notation and avoid using special symbols or keywords. Descriptive variable names help make your code more readable and maintainable. Remember not to name variables with single letters like a, b, or c. Instead, develop a habit of choosing meaningful names that convey the purpose of the variable. This practice benefits both you and anyone who reviews your code.
Precisely because JavaScript is not a strictly typed language, it is not the best choice for most financial and other calculations. That’s why TypeScript was created, which uses static typing. However, this does not mean you should immediately switch to TypeScript. JavaScript has a lot to teach and offer you. Unlike other programming languages, JavaScript has far fewer variable types. And unlike, for example, the PHP programming language, which has different data types like undefined and symbol, JavaScript uses the number type for all kinds of numbers, including hexadecimal ones.
Data Types in the JavaScript Programming Language
JavaScript has two main types of variables: primitive data types, also known as basic data types and complex data types or objects. Let’s explore these types:
- Primitive Data Types:
- String: Used to represent textual data.
- Number: Represents numeric values.
- Boolean: Represents logical values (true or false).
- null: Represents the absence of a value.
- undefined: Indicates that a variable is not defined.
- Symbol: Used to create unique identifiers.
- Complex Data Types:
- Object: Contains properties with values.
- Array: Represents ordered collections of values accessible via indices.
- Function: Objects with associated functionality that can be invoked from other parts of the program.
- Date: Used for date manipulation.
- RegExp: Represents regular expressions.
- Map: Manipulates values using keys.
- Set: A collection where each value can appear only once.
Understanding how these data types look and how they are used is best demonstrated through practical examples. Let’s create a simple example in Visual Studio Code. However, before we dive into variables and our next lesson, let’s organize our code better to avoid repetition and improve the tutorial’s appearance. Assuming you’re familiar with HTML and CSS or Bootstrap, we won’t explain those aspects in this JavaScript tutorial. First, create a new folder named “lessons” within your project and move the “lesson1.html” file into it. Then create a new file named “index.html” and type html:5, followed by pressing TAB to generate the basic HTML structure. Finally, open your browser and visit the official Bootstrap web site to grab the necessary links for using Bootstrap in your project.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
<title>JavaScript Tutorial</title>
</head>
<body>
<h1 class="bg-dark text-light
text-center py-2">JavaScript Tutorial</h1>
<br/><br/><br/>
<h5 class="bg-dark text-light
text-center py-2" id="footer">
Copyright © 2023 <strong>Manuel Radovanović</strong>
All rights reserved.
</h5>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe" crossorigin="anonymous"></script>
</body>
</html>
Then transfer the rest to footer.html so that the index.html file remains empty. View the contents of footer.html
<br/><br/><br/>
<h5 class="bg-dark text-light
text-center py-2" id="footer">
Copyright © 2024 <strong>Manuel Radovanovic</strong>
All rights reserved.
</h5>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe" crossorigin="anonymous"></script>
</body>
</html>
Next, type the following code into index.html.
<header></header>
<h2 class="bg-primary text-light text-center py-3">Contents</h2>
<div class="container">
<div>
<h2><font color="seagreen">Lessons</font></h2>
<ul>
<li><a href="lessons/lesson1.html">
Lesson 1. Hello
World
</a></li>
<li><a href="lessons/lesson2.html">
Lesson
1. Variables and data types
</a></li>
</ul>
</div>
</div>
<script src="js/includes.js"></script>
<footer></footer>
Create a new js folder in your project. In the js folder, create a new file and name it includes.js, then type the following JavaScript code into it.
// Loading header
fetch('/includes/header.html')
.then(response => response.text())
.then(data => {
document.querySelector('header').innerHTML = data;
});
//
Loading footer
fetch('/includes/footer.html')
.then(response => response.text())
.then(data => {
document.querySelector('footer').innerHTML = data;
});
Connecting headers and footers to a page using the JavaScript programming language can be very problematic because JavaScript is not executed on the server like the PHP programming language. Thanks to the built-in function fetch we can do this task. If you did everything as we said to do, right click on index.html in the panel explorer. Then click Open with Live Server in the drop-down menu. Check if any content has appeared on your local web address in your browser. If so and you have no error; return to Visual Studio Code and modify lesson1.html to look like this:
<header></header>
<h2 class="bg-primary text-light
text-center py-3">Lesson 1. - Hello World</h2>
<div class="container">
<script type="text/javascript">
alert("Hello World, we are
learning JavaScript!");
console.log("This is JavaScript
on Chrome Console!");
document.write("This is my first
JavaScript code!");
</script>
</div>
<script src="../js/includes.js"></script>
<footer></footer>
Open your browser, refresh the index.html page and click on the first link. You will see that the first lesson we did in the previous post, now looks much nicer and better; as part of a larger whole, the JavaScript tutorial. If you succeeded and everything works as it should, create a new variables.js file in the js directory. This is the file in which we will code all the JavaScript code related to the second lesson; Variables and data types. Type the following JavaScript code:
document.write("<h2><font color=\"seagreen\">Primitive data
types</font></h2>");
// String
let greeting = "Hello World!";
document.write(greeting + " - " + typeof greeting + "<br>");
// Number
let age = 25;
document.write(age + " - " + typeof age + "<br>");
//
Boolean
let isStudent = true;
document.write(isStudent + " - " + typeof isStudent + "<br>");
// Null
let myNull = null;
document.write(myNull + " - " + typeof myNull + "<br>");
// Undefined
let myUndefined;
document.write(myUndefined + " - " + typeof myUndefined + "<br>");
// Symbol
let sym = Symbol("foo");
document.write(sym.description + " - " + typeof sym + "<br>");
document.write("<h2><font
color=\"seagreen\">Complex data types or
Objects</font></h2>");
// Object
let person = {
name: "Manuel",
age: 47,
isStudent: false
}
document.write(person.name + " - " + typeof person + "<br>");
// Array
let myArray = [1, "two", false];
document.write(myArray[1] + " - " + typeof myArray + "<br>");
//
Function
let name = "Manuel";
function sayHello(name) {
document.write("Hello, " + name + "!
");
}
sayHello("Katarina");
document.write(" - " + typeof sayHello + "<br>");
// Date
let currentDate = new Date();
document.write(currentDate + " - " + typeof currentDate + "<br>");
// RegExp
let myRegExp = /hello/i;
document.write(myRegExp + " - " + typeof myRegExp + "<br>");
// Map
let myMap = new Map();
myMap.set("key1", "value1");
document.write(myMap.get("key1") + " - " + typeof myMap + "<br>");
// Set
let mySet = new Set();
mySet.add("one");
for (let value of mySet.values()) {
document.write(value);
}
document.write(" - " + typeof mySet + "<br>");
document.write("<h2><font
color=\"seagreen\">Constants</font></h2>");
const PI = Math.PI;
document.write("PI = " + PI + "<br>");
Return to the browser, refresh the index.html webpage, then click the second link in lesson 2. The result should look like this:
Primitive
data types
Hello World! - string
25 - number
true - boolean
null - object
undefined - undefined
foo - symbol
Complex data types or Objects
Manuel - object
two - object
Hello, Katarina! - function
Tue May 09 2023 03:55:07 GMT+0200 (Central
European Summer Time) - object
/hello/i - object
value1 - object
one - object
Constants
PI = 3.141592653589793
If you pay attention to the mentioned last part of the
JavaScript code in the variables.js file, you can notice that we also have the
constant PI in the code. What does that mean, what is a constant? A constant is
like a variable, except that its value cannot be changed during program
execution like you can with variables. The constants are used so that, for
example, you do not always have to type the value 3.141592653589793 when you
need this number, but instead type only PI.
In the given example, we declared a constant with the keyword const and assigned it the value PI. For this assignment, instead of typing the value 3.141592653589793, we told the built-in JavaScript static object Math to assign us the value. Once we have assigned a value to a constant, it cannot be changed. Pay attention when you create constants, that unlike variables, you always write them in all capital letters. You can see what all this looks like in the video.
No comments:
Post a Comment