THM - JavaScript Essentials
THM - JavaScript Essentials
Variables are containers for storing data values. In JavaScript, they can be declared using var,
let, or const:
var: Function-scoped.
let and const: Block-scoped, offering better control over visibility.
Data Types
Functions
function PrintResult(rollNum) {
alert("User with roll number " + rollNum + " has passed the exam.");
Functions can be reused to avoid repetitive code, such as printing results for multiple
students.
Loops
Loops execute a code block repeatedly while a condition is true. Common types include for,
while, and do...while. Example:
PrintResult(rollNumbers[i]);
}
Request-Response Cycle
In web development, the browser (client) sends a request to the web server, which responds
with the requested data, such as a webpage or resource.
JavaScript Overview
JavaScript (JS) is an interpreted language executed directly in the browser, making it ideal for
creating dynamic web apps. Below is an example covering key concepts:
console.log("Hello, World!");
} else {
// Function
function greet(name) {
greet("Bob");
Key Points:
Internal JS: The script is embedded directly within the HTML document using <script>
tags, placed either in the <head> (for pre-loading) or <body> (for interaction during page
load). Example: adding two numbers and displaying the result using
document.getElementById().innerHTML.
External JS: The JS code is written in a separate .js file and linked to the HTML using the
<script> tag with the src attribute. This keeps the code organised and easier to maintain,
especially for larger projects.
Abuse Example: Malicious JS can exploit these, such as repetitive alerts disrupting the user
experience. Always run JS from trusted sources to prevent potential attacks like XSS.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Age Verification</title>
</head>
<body>
<h1>Age Verification</h1>
<p id="message"></p>
<script>
} else {
</script>
</body>
</html>
https://deobfuscate.io
Best Practices
JavaScript Best Practices:
1. Use Server-Side Validation: Avoid relying solely on client-side validation, as users can
manipulate or disable JavaScript.
2. Avoid Untrusted Libraries: Include only trusted JS libraries to prevent introducing
malicious scripts.
3. Do Not Hardcode Secrets: Never store sensitive information (e.g., API keys) directly in JS
code.
4. Minify and Obfuscate Code: Minify and obfuscate JS in production to improve
performance and make reverse engineering harder.