JavaScript Basics - Exercise 5
JavaScript adds interactivity and dynamic behavior to web pages. While HTML defines the structure and CSS controls the appearance, JavaScript makes the page respond to user actions - handling events, validating forms, updating content without reloading the page, fetching data from servers, and creating animations.
A high-level language (like JavaScript) uses human-readable syntax and abstracts away hardware details such as memory management. A low-level language (like Assembly) is closer to machine code and directly interacts with the hardware. High-level languages are easier to write and read, but they require translation to machine code before execution.
- HTML provides the structure and content of the page (headings, paragraphs, images, links).
- CSS controls the visual appearance and layout (colors, fonts, spacing).
- JavaScript adds behavior and interactivity (responding to clicks, updating content dynamically).
Capabilities: DOM manipulation, form validation, API requests (fetch), real-time updates, animations, and running server-side code with Node.js.
Limitations: Single-threaded execution, no direct file system access in the browser, behavior can vary slightly across browsers, and it is not ideal for CPU-intensive tasks.
ECMAScript is the official specification and standard that defines the core features of JavaScript. It is maintained by ECMA International. JavaScript is an implementation of the ECMAScript standard. Periodic updates - such as ES6 (ES2015), ES2017, and ES2020 - add new features like arrow functions, let/const, template literals, async/await, and more.
Different browsers (Chrome, Firefox, Safari, Edge) may implement JavaScript features at different times. Newer ECMAScript features may not be supported in older browsers. Developers use compatibility tables (like caniuse.com) and tools like Babel (a transpiler) to convert modern JavaScript to a syntax that older browsers can understand, ensuring a consistent experience for all users.
An IDE (Integrated Development Environment) is a software application that provides tools for writing, editing, and debugging code in one place - including syntax highlighting, code completion, error detection, and an integrated terminal. VS Code is popular because it is free, lightweight, highly extensible (with thousands of extensions), has excellent built-in JavaScript and TypeScript support, and a large developer community.
The browser Developer Console (accessed via F12 or right-click -> Inspect -> Console) allows you to:
- Run JavaScript code directly in the browser
- View
console.log()output and error messages - Inspect and debug variables and objects
- Monitor network requests and page performance
- Test small code snippets quickly without a file
'use strict' is a directive that enables strict mode in JavaScript. When strict mode is on:
- Using undeclared variables throws a
ReferenceErrorinstead of silently creating a global variable - Certain dangerous or confusing features are disallowed
- Silent errors become thrown errors, making debugging easier
It is placed at the top of a script file or inside a function: 'use strict';
Separation of Concerns means dividing a web application into distinct parts where each part handles a specific responsibility:
- HTML - structure and content
- CSS - presentation and styling
- JavaScript - behavior and interactivity
Keeping these in separate files makes code easier to maintain, debug, and collaborate on. Mixing JavaScript directly inside HTML (e.g., inline onclick attributes) violates this principle.
In a dynamically typed language, you do not declare variable types - they are determined at runtime based on the value assigned. A variable can hold a number and later hold a string without any error. This is different from statically typed languages like Java or TypeScript where types must be declared explicitly.
let value = 42; // type: number
value = "hello"; // type: string (no error)
value = true; // type: boolean (no error)
Garbage collection is an automatic memory management feature in JavaScript. When you create objects or variables, memory is allocated for them. When those objects are no longer reachable (no references to them exist), the JavaScript engine automatically frees that memory. Developers do not need to manually allocate or deallocate memory, unlike in lower-level languages such as C or C++.
JIT compilation is a technique used by modern JavaScript engines (like V8 in Chrome) where JavaScript code is compiled to machine code at runtime, just before execution - rather than being interpreted line by line. Frequently executed code ("hot code") is detected and optimized. This gives JavaScript near-native performance while still being easy to write and distribute as plain text source code.
JavaScript supports multiple programming styles (paradigms):
- Procedural - writing step-by-step instructions in sequence
- Object-Oriented - organizing code into objects with properties and methods
- Functional - treating functions as values, avoiding state changes and side effects
Developers can mix these styles depending on the problem they are solving.
In JavaScript, functions are "first-class citizens," meaning they can be treated just like any other value:
- Assigned to variables:
const greet = function() {} - Passed as arguments to other functions (callbacks)
- Returned from other functions (closures, higher-order functions)
- Stored in arrays or objects
You can include JavaScript using the <script> tag in two ways:
- Inline: Write JavaScript directly inside the tag (not recommended for large code)
- External: Link an external
.jsfile usingsrcattribute -<script src="script.js"></script>
Best practice: Use an external file and place the <script> tag just before the closing </body> tag, or use the defer attribute so the script loads after the HTML is parsed.
In a compiled language (e.g., C++, Go), the entire source code is translated to machine code before the program runs. In an interpreted language, the code is executed line by line at runtime. JavaScript is traditionally described as interpreted, but modern engines use JIT compilation - compiling code on the fly at runtime - to achieve much better performance than pure interpretation.
VS Code extensions are add-ons installed from the Extensions Marketplace to enhance the editor's functionality. Useful extensions for JavaScript development include:
- ESLint - identifies and fixes code quality issues
- Prettier - automatically formats code consistently
- Live Server - launches a local development server with live reload
- GitLens - enhances Git integration inside VS Code
- Path Intellisense - autocompletes file paths
JavaScript uses an event-driven programming model. Code does not run sequentially all the time - instead, it waits for events (such as a button click, key press, page load, or a timer) and then executes the appropriate handler function. This makes JavaScript well-suited for building interactive user interfaces.
document.getElementById('myBtn').addEventListener('click', function() {
console.log('Button was clicked!');
});
Despite having similar names, JavaScript and Java are completely different languages:
- JavaScript is dynamically typed, primarily interpreted/JIT-compiled, and runs in the browser (or on the server via Node.js). It is mainly used for web development.
- Java is statically typed, compiled to bytecode (runs on JVM), and is used for backend applications, Android development, and enterprise software.
The naming similarity was a marketing decision when JavaScript was first released - the two languages share very little in common.