Module 2 - JavaScript Basics

Introducing Variables

Variables are one of the most important building blocks of JavaScript. They let you store and manage information, like numbers, words, or even more complex things, so you can use them in your programs. Here’s a simple breakdown of what you need to know about variables:

1. What is a Variable?

A variable is like a labeled box where you can store data. You can put information into it, like a number or a word, and then use that information later in your program.

2. How to Create a Variable (Declaration)

You can create a variable using let, const, or var in JavaScript. For now, focus on let and const, as they’re more commonly used:

let: Use this when the value might change later.

const: Use this when you know the value should never change.

Example:

let age = 25;  // You can change this later
const name = "John"; // You can't change this one

3. Assigning Values

Once you’ve created a variable, you can assign a value to it. This is done using the equals sign (=). In the example above, we assigned 25 to the variable age and "John" to the variable name.

4. Types of Data You Can Store (Data Types)

JavaScript is flexible when it comes to what you can store in a variable. You can put different types of information in, such as:

  • Numbers: let price = 100;
  • Text (strings): let greeting = "Hello!";
  • True/false values (booleans): let isLoggedIn = true;

You don’t need to tell JavaScript what type of data you’re storing—it figures it out on its own!

5. Where You Can Use Your Variables (Scope)

Variables in JavaScript have different rules about where they can be used, called scope:

  • Global Scope: If you create a variable outside of any function or block of code, you can use it anywhere on the page.
  • Block Scope: Variables created inside curly braces ({ }), like in a loop or function, can only be used within that block of code.

6. Changing Values (Reassignment)

If you use let, you can change the value of your variable later. For example:

let age = 25;
age = 26; // Now the value is 26

But if you use const, you can’t change the value:

const name = "John";
name = "Jane"; // This will cause an error because `name` is a constant

7. Rules for Naming Variables

When naming your variables, follow these simple rules:

  • Start with a letter, underscore (_), or dollar sign ($).
  • The rest of the name can include letters, numbers, underscores, or dollar signs.
  • Variable names are case-sensitive: age and Age are different variables!
  • Pick meaningful names that describe the data you’re storing, like userName or totalPrice.

Recap

Variables in JavaScript are like containers for storing information you’ll use in your program. Whether you’re storing a number, some text, or a list, variables help you keep track of data and make your web pages more dynamic and interactive. As you get more comfortable, you’ll learn to use variables to build even more powerful features for your websites!

This version explains variables in a clear, easy-to-digest way, focusing on the basics that are most relevant to beginners, while leaving out more advanced topics like hoisting and ECMAScript standards. It uses relatable examples and keeps the tone friendly and accessible.



Data Types

In JavaScript, data types are the building blocks that allow developers to define and manipulate different kinds of information within their programs. Understanding and using data types correctly is of paramount importance for developers because it profoundly influences how data is processed, stored, and displayed in web applications. When a developer declares a variable, assigns a value, or performs operations on that data, the choice of data type dictates how those actions are executed. For instance, choosing the correct data type for numeric calculations ensures accurate results, while selecting the appropriate data type for text ensures proper text handling and manipulation. Misusing data types can lead to unexpected errors, performance issues, and bugs in the code. Therefore, a sound grasp of JavaScript's data types and their appropriate usage is fundamental for creating robust and efficient web applications. It empowers developers to make informed decisions about how data is represented and processed, ultimately contributing to the reliability and functionality of their software.

JavaScript offers several data types that allow developers to work with various kinds of information. Understanding these data types is crucial for effective programming in JavaScript. Let's explore the different data types, provide examples, and highlight their use cases:

Number:

Example:

let age = 30;

Use Case: Numbers are used for arithmetic operations, calculations, and storing any numeric data, such as ages, prices, and quantities.

String:

Example: 

let name = "John";

Use Case: Strings are used to represent text and characters. They are essential for storing names, descriptions, and textual content on web pages.

Boolean:

Example: 

let isStudent = true;

Use Case: Booleans have two values: true and false. They are used for logical decisions, conditions, and controlling the flow of a program. For example, to check if a user is logged in (true) or not (false).

Undefined:

Example: 

let variable;

Use Case: A variable without a value is undefined by default. It often occurs when a variable is declared but not assigned a value yet.

Null:

Example: 

let data = null;

Use Case: null is used to represent the intentional absence of any object value. It's often employed when a variable needs to be explicitly cleared, or when you want a variable to continue to exist but you want to make sure it is empty.

Other Data Types:

There are other data types – some of which will be introduced in the upcoming chapters.  However, to keep things simple to start, we will stick with these for now.



Declaring Variables

You may have noticed in the previous section that sometimes the variable name is preceded by a “let” or “const” – These keywords represent different ways of declaring a variable.

In JavaScript, variables are used to store and manage data. There are several keywords for declaring variables, each with its own significance, meaning, and best use. Let's discuss the primary variable declaration keywords in JavaScript:

var:

Significance: var was the original way to declare variables in JavaScript.
Meaning: Variables declared with var are function-scoped, meaning their scope is limited to the function in which they are defined, or they have global scope if declared outside any function.
Proper Use: While still widely supported, the use of var has diminished in favor of let and const due to its scoping quirks. It's mainly used in older codebases or where compatibility with older browsers is a concern.

let:

Significance: let was introduced in ECMAScript 6 (ES6) to address the scoping issues of var.
Meaning: Variables declared with let have block-level scope. This means they are confined to the nearest enclosing block, be it a function, loop, or any block statement.
Proper Use: Use let when you want to create variables with limited, predictable scope. It's now the preferred choice for declaring variables in most cases.

const:

Significance: const is also an ES6 addition, designed to create variables that should not be reassigned.
Meaning: Variables declared with const are block-scoped like let, but they must be assigned a value upon declaration and cannot be reassigned. However, the data within a const variable can be mutated if it's an object or an array.
Proper Use: Use const when you want to create variables that should remain constant throughout their lifetime. It's particularly useful for declaring constants or values that should not change.

These keywords have different scoping rules and purposes, which influence their proper use. Here's a summary of their significance and best practices:

  • Use let for variables that may need to be reassigned and are meant to have block-level scope.
  • Use const for variables that should remain constant and have block-level scope. It's a good choice for declaring constants and values that should not change.
  • Use var sparingly, mainly in older code or when compatibility with older browsers is required. In modern JavaScript, it's generally best to use let or const to ensure predictable scoping and avoid common bugs associated with var.

Understanding the significance of these keywords and choosing the right one for a given situation is crucial for writing clean, maintainable, and bug-free JavaScript code.



Coding Conventions

JavaScript, like any programming language, has its own set of best practices and coding conventions that can help improve code readability, maintainability, and overall quality. Here are some common best practices and coding conventions in JavaScript:

  1. Use Meaningful Variable and Function Names:
    Choose descriptive and meaningful names for variables and functions to make your code more self-explanatory.
  2. Indentation and Formatting:
    Use consistent and clear indentation, typically 2 or 4 spaces, to improve code readability.
    Follow a consistent code formatting style, either using spaces or tabs. Popular styles include the Google JavaScript Style Guide and Airbnb JavaScript Style Guide.
  3. Semicolons:
    Always use semicolons to terminate statements. JavaScript's automatic semicolon insertion can lead to unexpected behavior if you omit them.
  4. Braces and Curly Brackets:
    Use braces {} to define blocks of code, even for single statements. This can help prevent bugs and improve readability.
  5. Commenting:
    Add comments to explain complex logic, unusual behavior, or code that might not be immediately obvious to others. Use single-line (//) and multi-line (/* */) comments as appropriate.
  6. Avoid Global Variables:
    Minimize the use of global variables to prevent naming conflicts and to make it easier to understand where a variable is defined and used.
  7. Modularization:
    Organize your code into reusable modules or functions to promote maintainability and code reusability.
  8. Use Strict Mode:
    Enable strict mode at the beginning of your script ("use strict";) to catch common coding mistakes and prevent the use of undeclared variables.

These coding conventions and best practices help improve code quality and make it easier for you and your team to maintain and understand JavaScript code. However, it's essential to adapt them to your specific project and team requirements when necessary.



Comments in JavaScript

Comments in JavaScript are essential for documenting and explaining your code. They come in different forms and serve various purposes. Here's a thorough description of how different types of comments can be effectively used in JavaScript:

Single-Line Comments (//):

Single-line comments are used to add short explanations or comments on a single line. They are useful for annotating code, providing context, or temporarily disabling code.

// This is a single-line comment
var x = 10; // Assigning a value to x

Multi-Line Comments (/* */):

Multi-line comments are used for more extensive explanations or comments spanning multiple lines. They are often used for documenting functions or describing complex algorithms.

/*
This is a multi-line comment.
It can be used to explain
multiple lines of code.
*/
function add(a, b) {
return a + b;
}

Comments for Function Documentation (JSDoc):

JSDoc is a convention for adding comments to describe functions, their parameters, return values, and more. These comments can be processed by documentation generators and integrated development environments (IDEs) for better code understanding.

/**
* Adds two numbers together.
* @param {number} a - The first number to be added.
* @param {number} b - The second number to be added.
* @returns {number} The sum of a and b.
*/
function add(a, b) {
return a + b;
}

Tools like JSDoc can parse these comments to generate documentation for your code.

TODO Comments:

TODO comments are a way to mark areas in your code that need further attention or implementation. They help you keep track of tasks that need to be completed.

// TODO: Implement error handling
function processInput(input) {
// ...
}
 

Debugging Comments:

You can use comments to temporarily disable or enable code for debugging purposes. It's essential to remove or re-enable these comments once you've finished debugging.

var debug = true;
// if (debug) {
// // Debugging code
// }

Explanatory Comments:

Explanatory comments provide context and explanations for complex or non-obvious code. They help other developers (or even your future self) understand your reasoning.

// Parse the input string into an array of words
var words = input.split(' ');

License Comments:

Include license information and copyright notices at the beginning of your source code files to clarify the terms under which the code can be used.

/*
Copyright (c) 2023 Your Name
Licensed under the MIT License.
*/

Header Comments:
Use header comments to describe the purpose of a file, its author, creation date, and other metadata.

/*
Filename: app.js
Author: John Doe
Created: October 14, 2023
Description: This file contains the main application logic.
*/

Commenting Out Code:

You can comment out blocks of code that you want to temporarily disable without removing them. Be cautious not to leave commented-out code in production.

// This code is temporarily commented out
// function unusedFunction() {
// // ...
// }

Effective use of comments in JavaScript can significantly improve code maintainability and collaboration. However, remember that comments should complement the code and not replace clear and self-explanatory code whenever possible.



Changing HTML Content

Changing the contents of an HTML element using JavaScript is a common task and can be accomplished by accessing the element using its unique identifier or by using the Document Object Model (DOM). Here's a detailed explanation of how to change the contents of an HTML element:

Identify the Target Element:

You need to identify the HTML element you want to modify. You can do this by assigning an id attribute to the element or by using selectors like getElementById, getElementsByClassName, or querySelector to find the element in the DOM.

For example, let's say you have the following HTML element with an id:

<p id="myParagraph">This is a paragraph.</p>

Access the Element Using JavaScript:

You can access the target element in your JavaScript code using the getElementById method. If you're using a different type of selector, the process is similar.

// Access the element with the id "myParagraph"
var paragraph = document.getElementById("myParagraph");

Modify the Element's Contents:

Once you have access to the element, you can change its contents by modifying the innerHTML property or by creating new text nodes. Here are two common methods:

a. Using innerHTML: You can set the innerHTML property of the element to change its content. This approach allows you to add HTML tags and structure within the element.

paragraph.innerHTML = "This is the updated paragraph with <strong>bold text</strong>.";

b. Using textContent: To change only the text content of the element, you can use the textContent property. This method will escape any HTML tags, treating them as plain text.

paragraph.textContent = "This is the updated paragraph with <strong>bold text</strong>.";

The textContent approach is safer when dealing with user-generated content, as it prevents the execution of potentially harmful scripts.

Complete Example:

Here's a complete example that changes the content of the "myParagraph" element:

<!DOCTYPE html>
<html>
<body>

<p id="myParagraph">This is a paragraph.</p>

<button onclick="changeContent()">Change Content</button>

<script>
function changeContent() {
var paragraph = document.getElementById("myParagraph");
paragraph.innerHTML = "This is the updated paragraph with <strong>bold text</strong>.";
}
</script>

</body>
</html>

In this example, when the "Change Content" button is clicked, the changeContent JavaScript function is called, which updates the content of the paragraph with new HTML content.

By following these steps, you can dynamically change the contents of HTML elements using JavaScript, allowing you to create interactive and responsive web pages.



Events in JavaScript

What are events in JavaScript?

Events are interactions or occurrences in the web browser that can be detected and responded to by JavaScript. These interactions can be user actions, such as clicking a button or moving the mouse, or system events like the page finishing loading.

In JavaScript, events are crucial for building interactive and dynamic web applications. They allow developers to listen for specific actions or occurrences and execute code in response.

Why are events important in web development?

Events are essential in web development because they enable interactivity and responsiveness. They allow web applications to respond to user input and provide a better user experience.

Events are used to trigger various actions, like validating form input, handling user interface elements (e.g., button clicks), and updating the page dynamically without the need for a full page reload.

They are a fundamental part of modern web development and are used in conjunction with event handlers to create interactive and engaging web applications.

Example: 

Let's consider a simple scenario where you want to create a button that displays an alert when clicked. You would use a "click" event to trigger the alert, and an event handler to specify what happens when the event occurs.

<button id="myButton">Click Me</button>
<script>
// Get the button element by its ID
const button = document.getElementById("myButton");

// Add a click event listener to the button
button.addEventListener("click", function() {
alert("Button Clicked!");
});
</script>

In this example, the "click" event is used to listen for a button click, and the event handler is a function that displays an alert when the button is clicked.

Best Practices:

  • Use events to create a more interactive and user-friendly web application.
  • Understand the various types of events and when to use them based on the desired behavior.
  • Avoid excessive use of events, as too many can make your code harder to maintain. Plan and structure your events carefully.
  • When adding event listeners, use the latest recommended approach (e.g., addEventListener) rather than inline event handlers for better code organization and maintainability.
  • Ensure your event handling code is efficient to maintain smooth performance, especially for complex applications.


Listening for an Event

To add an event listener to a link that opens an alert when clicked, you can use JavaScript to target the link (anchor element) and attach an event listener to it. Here's a detailed explanation of how to do this:

Create an HTML Link (Anchor Element):

Start by creating an HTML link (anchor element) in your HTML document. Give it an id or any other identifier that you can use to target it in JavaScript. For example:

<a id="myLink" href="#">Click me to open an alert</a>

In this example, we've assigned the id "myLink" to the link.

Add JavaScript Code:

Add a <script> element to your HTML document to include JavaScript code. Inside the JavaScript code, you'll attach an event listener to the link element. Here's how you can do it:

<script>
// Get the link element by its id
var link = document.getElementById("myLink");

// Add an event listener to the link
link.addEventListener("click", function(event) {
// Prevent the default behavior (following the link)
event.preventDefault();

// Show an alert when the link is clicked
alert("You clicked the link!");
});
</script>

In this code, we:

  1. Get the link element by its id using document.getElementById("myLink").
  2. Attach an event listener to the link using addEventListener.
  3. Specify "click" as the event we want to listen for.
  4. Provide a function that will be executed when the link is clicked.
  5. Inside the function, we call event.preventDefault() to prevent the default behavior of the link (navigating to the href).
  6. We then use the alert function to display an alert message when the link is clicked.

Complete HTML Example:

Here's a complete HTML example:

<!DOCTYPE html>
<html>
<head>
<title>Open Alert on Link Click</title>
</head>
<body>
<a id="myLink" href="#">Click me to open an alert</a>

<script>
// Get the link element by its id
var link = document.getElementById("myLink");

// Add an event listener to the link
link.addEventListener("click", function(event) {
// Prevent the default behavior (following the link)
event.preventDefault();

// Show an alert when the link is clicked
alert("You clicked the link!");
});
</script>
</body>
</html>

When you click the link in the browser, it will trigger the event listener and display an alert with the message "You clicked the link!"

This example demonstrates how to add an event listener to a link and prevent the default behavior of the link (navigating to the href) while opening an alert when the link is clicked.



Types of Events and Listeners

Mouse Events

Mouse events are triggered by user interactions with the mouse, such as clicking, moving, or hovering over elements on a web page.

Click Event

The "click" event is triggered when the user clicks the mouse button on an element. It's one of the most common mouse events used for interactive elements like buttons and links.

const button = document.getElementById("myButton");
button.addEventListener("click", function() {
console.log("Button clicked!");
});

Mouseover Event

The "mouseover" event is triggered when the mouse pointer enters the boundaries of an element. It's often used for creating hover effects.

const element = document.getElementById("myElement");
element.addEventListener("mouseover", function() {
console.log("Mouse over element!");
});

Mouseout Event

The "mouseout" event is triggered when the mouse pointer leaves the boundaries of an element. It's useful for detecting when the user moves the mouse away from an element.

const element = document.getElementById("myElement");
element.addEventListener("mouseout", function() {
console.log("Mouse left element!");
});

Mousemove Event

The "mousemove" event is triggered when the mouse pointer is moved within the boundaries of an element. It can be used to track the mouse's movement.

const element = document.getElementById("myElement");
element.addEventListener("mousemove", function(event) {
console.log(`Mouse coordinates: X-${event.clientX}, Y-${event.clientY}`);
});

Keyboard Events

Keyboard events are triggered when the user interacts with the keyboard, such as pressing and releasing keys.

Keydown Event

The "keydown" event is triggered when a key on the keyboard is pressed down.

document.addEventListener("keydown", function(event) {
console.log(`Key pressed: ${event.key}`);
});

Keypress Event

The "keypress" event is triggered when a key on the keyboard is pressed down and produces a character.

document.addEventListener("keypress", function(event) {
console.log(`Character pressed: ${event.key}`);
});

Keyup Event

The "keyup" event is triggered when a key on the keyboard is released.

document.addEventListener("keyup", function(event) {
console.log(`Key released: ${event.key}`);
});

Form Events

Form events are used to handle interactions with HTML forms and form elements.

Submit Event

The "submit" event is triggered when a form is submitted, usually by clicking a submit button. It's used to validate and process form data.

const form = document.getElementById("myForm");
form.addEventListener("submit", function(event) {
event.preventDefault(); // Prevent the form from submitting
console.log("Form submitted!");
// Add form validation and submission logic here
});

Reset Event

The "reset" event is triggered when a form's reset button is clicked, resetting the form to its initial state.

const form = document.getElementById("myForm");
form.addEventListener("reset", function() {
console.log("Form reset!");
// Add reset-related logic here
});

Change Event

The "change" event is triggered when the value of an input element changes, such as in text fields, checkboxes, or select elements.

const input = document.getElementById("myInput");
input.addEventListener("change", function() {
console.log("Input value changed!");
// Add input validation or handling logic here
});

Focus and Blur Events

The "focus" event is triggered when an element receives focus, and the "blur" event is triggered when it loses focus.

const input = document.getElementById("myInput");
input.addEventListener("focus", function() {
console.log("Input focused!");
});

input.addEventListener("blur", function() {
console.log("Input blurred!");
});

Document Events

Document events are events related to the entire web page or document itself.

DOMContentLoaded Event

The "DOMContentLoaded" event is triggered when the HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

document.addEventListener("DOMContentLoaded", function() {
console.log("DOM content loaded");
// You can safely manipulate the DOM here
});
 

Load Event

The "load" event is triggered when the entire page, including all its resources (images, styles, scripts), has finished loading.

window.addEventListener("load", function() {
console.log("Page fully loaded");
// Perform actions that require all resources to be loaded
});

Unload Event

The "unload" event is triggered just before the page is unloaded, such as when a user navigates away from the page.

window.addEventListener("unload", function() {
console.log("Page is being unloaded");
// You can use this for cleanup or confirmation prompts
});

These are some of the most common event types in JavaScript. Understanding when and how to use them is essential for creating interactive web applications and ensuring a positive user experience.



Inline Event Handlers

Inline Event Handlers

Inline event handlers are attributes in HTML elements that directly specify the JavaScript code to be executed when an event occurs. While they are straightforward, they are generally discouraged in modern web development due to maintenance and separation of concerns concerns.

Here is an example of an inline event handler:

<button onclick="alert('Button Clicked!')">Click Me</button>

Best Practices:

  • Use event listeners instead of inline event handlers for better code organization and maintainability.
  • Be mindful of event types and select the appropriate type for the desired behavior.
  • Keep your event handling functions clean and modular for easier debugging and maintenance.
  • Use the optional configuration object of addEventListener() to control event propagation and other behavior if needed.
  • Remove event listeners when they are no longer necessary to prevent memory leaks and improve performance.

Videos for Module 2 - JavaScript Basics

2-1: Using the JavaScript Console (4:25)

2-2: Variables in JavaScript (1:29)

2-3: Creating a Variable in JavaScript (3:33)

2-4: Variable Scope (1:55)

2-5: Data Types in JavaScript (7:16)

2-6: Comments (3:05)

2-7: Changing Page Content Using JavaScript (5:03)

2-8: Events in JavaScript (7:27)

2-9: Types of Events (5:13)

2-10: Sandbox 2 Explanation (4:40)

2-11: A2 Explanation (4:55)