JavaScript Programming Fundamentals
Fundamental Concepts of JavaScript
JavaScript (JS)
Defined as a high-level, dynamic, untyped, and interpreted programming language.
Characteristics:
Prototype-based: Uses prototypes rather than classes to define object types.
First-class functions: Functions can be assigned to variables, passed as arguments, or returned from other functions.
Multi-paradigm: Supports multiple styles of programming, including:
Object-oriented
Imperative
Functional programming
Despite name similarity and certain syntactic overlaps, it is noted that JavaScript and Java are otherwise unrelated and have distinctly different semantics.
Common Uses of JavaScript
Roles of JavaScript in web development include:
Rollovers
Cookies: Enable storage of user-specific data on client-side.
Status Bar Messages: Display messages to users within the browser's status bar.
Slide Shows: Create dynamic image presentations.
Browser Detection: Identify the type of browser for compatibility purposes.
Forms Validation: Check user input before submitting forms.
Additional uses:
Redirecting Visitors
Detecting Plug-ins
Random Images and Quotes: Enable variability in content presentation.
Playing Random Sounds
Pop-up Windows
Cycling Banners
Displaying Current Date/Last Modified Date
Loading Multiple Frames
Advantages of JavaScript
Less Server Interaction: Reduces the need for server requests by validating user input directly on the client side before submitting.
Immediate Feedback: Users receive instant responses without page reloads when errors or omissions occur.
Increased Interactivity: Allows for the creation of dynamic interfaces that respond to user interaction, enhancing user experience.
Richer Interface: Can implement complex components like drag-and-drop.
Disadvantages of JavaScript
Client-Side Limitations: It doesn't allow reading or writing of files for security reasons.
Networking Restrictions: JavaScript lacks support for networking applications.
No Multithreading: JavaScript does not support multithreading or multiprocessor capabilities, which may limit performance in high-load scenarios.
Brief History of JavaScript
Creation: Developed by Brendan Eich in May 1995 while at Netscape Communications, originally named LiveScript.
Purpose: Designed to enhance the functionalities of web browsers, making web pages interactive.
Integration: Can be embedded directly within HTML. Modern browsers efficiently handle JavaScript to ensure display and security, primarily executing client-side.
Integrating JavaScript in HTML Documents
Five Methods of Integration:
In
<script>
tag within the<head>
:In
<script>
tag within the<body>
:Inline with HTML as event handlers:
External JavaScript file:
Using the JavaScript pseudo-protocol:
JavaScript Code Examples
JavaScript in
<head>
Section:
<html>
<head>
<script type="text/javascript">
function Hello_World() {
alert("Hello World! Welcome to JavaScript.");
}
</script>
</head>
<body>
<input type="button" onclick="Hello_World()" value="Click-Me" />
</body>
</html>
JavaScript in
<body>
Section:
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.write("Hello World! Welcome to JavaScript.");
</script>
</body>
</html>
JavaScript in both
<head>
and<body>
Sections:
<html>
<head>
<script type="text/javascript">
function Hello_World() {
alert("Hello World! Welcome to JavaScript.");
}
</script>
</head>
<body>
<script type="text/javascript">
document.write("Hello World! Welcome to JavaScript.");
</script>
<input type="button" onclick="Hello_World()" value="Click Me" />
</body>
</html>
JavaScript in an External File:
Contents of script.html:
// Function to display a greeting message
function showGreeting() {
alert("Hello! Welcome to my website.");
}
// Function to change the text of a paragraph
function changeText() {
document.getElementById("demo").innerHTML = "The text has been changed!";
}
HTML file that includes the external JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>External JavaScript Example</title>
</head>
<body>
<h1>External JavaScript Example</h1>
<p id="demo">This is a sample text.</p>
<button onclick="showGreeting()">Click for Greeting</button>
<button onclick="changeText()">Change Text</button>
<script src="script.html"></script>
</body>
</html>
JavaScript Variable Naming Rules
Valid Variable Names:
Can include letters, digits, underscores, but not punctuation (other than underscore).
Examples:
first_name
,lastName
,_3rdplace
Invalid Variable Names:
Cannot begin with a number.
Cannot have spaces.
Cannot use reserved words.
Cannot match the names of built-in functions or objects.
Examples:
Invalid:
1stName
,first name
,case
Valid:
firstName
,first_name
Creating Variables in JavaScript
Two Methods:
Explicit Declaration:
Utilizing
var
,let
, orconst
to declare variables:
var product_cost = 12.75; // Declares a variable named product_cost with value 12.75
var password = "secret"; // Declares a variable named password with string "secret"
Implicit Declaration:
Assigning a value to a non-declared variable creates it implicitly:
grade = 86; // Creates a variable named grade and assigns it 86
Remark = "Failed"; // Creates Remark and assigns it "Failed"
Arithmetic Operators in JavaScript
Operators and Examples:
Addition (
+
):javascript x = 10; y = 5; z = x + y; // Results in 15
Subtraction (
-
):javascript x = 10; y = 5; z = x - y; // Results in 5
Multiplication (
*
):javascript x = 10; y = 5; z = x * y; // Results in 50
Division (
/
):javascript x = 10; y = 5; z = x / y; // Results in 2
Modulo (
%
):javascript x = 10; y = 5; z = x % y; // Results in 0
Increment (
++
):javascript x = 10; x++; // x becomes 11
Decrement (
--
):javascript x = 10; x--; // x becomes 9
Data Types in JavaScript
Numeric
Examples:
javascript var age = 12; var gross_pay = 12345.67; var temperature = 37.9; var final_score = 102;
String
javascript var my_string = "Hello"; var address = "123 Street, Kayen, Dededo, Guam"; var result = "123"; var secret_word = "ALIBABA"; var full_name = "John" + "Smith"; // Output: "John Smith"
Boolean (logical values):
javascript var result = true; var response = false; var bigger = 56 > 4; var smaller = 12 < 3;
Comparison Operators in JavaScript
Operators and Examples:
Equal to (
==
):javascript x = 7; y = 7; x == y // returns true
Strict Equal to (
===
):javascript x = 8; y = "8"; x === y // returns false (different types)
Less than (
<
):javascript x = 7; y = 8; x < y // returns true
Greater than (
>
):javascript x = 10; y = 5; x > y // returns true
Greater than or equal to (
>=
):javascript x = 7; y = 8; x >= y // returns false
Less than or equal to (
<=
):javascript x = 7; y = 8; x <= y // returns true
Not equal to (
!=
):javascript x = 7; y = 8; x != y // returns true
Logical Operators in JavaScript
Operators and Examples:
AND (
&&
): Both conditions must be true:javascript x = 5; y = 15; x < 10 && y > 10 // returns true
OR (
||
): At least one condition must be true:javascript x = 5; y = 15; x > 10 || y > 100 // returns false
NOT (
!
): Reverses the boolean value:javascript !(x == y) // returns true if x is not equal to y
Assignment Operators in JavaScript
Basic Assignment Operator:
=
: Assigns the right operand to the left operand.Example:
x = y
Shorthand Assignment Operators: Combine operation and assignment:
Addition Assignment (
+=
):javascript x += y // equivalent to x = x + y
Subtraction Assignment (
-=
):javascript x -= y // equivalent to x = x - y
Multiplication Assignment (
*=
):javascript x *= y // equivalent to x = x * y
Division Assignment (
/=
):javascript x /= y // equivalent to x = x / y
Modulo Assignment (
%=
):javascript x %= y // equivalent to x = x % y