Javascript 3
Javascript 3
JavaScript (JS) is a text-based programming language used both on the client and server sides,
allowing you to make web pages interactive. It is one of the three core technologies of World
Wide Web content production (along with HTML and CSS).
JavaScript is used to make web pages interactive. It can add animations, control multimedia,
display dynamic content, and more. JavaScript is also used in game development, mobile app
development, and server-side programming.
JavaScript is a high-level, interpreted programming language. This means that it is relatively
easy to learn and use and that it does not need to be compiled before it can be
executed. JavaScript is also a dynamic language, which means that it can be changed while it is
running.
JavaScript is a very versatile language. It can be used to create various web applications, from
simple games to complex web-based applications. JavaScript is also used in a variety of other
non-web applications, such as game development, mobile app development, and server-side
programming.
Things that you can do with JavaScript:
Embedding JavaScript in a web page refers to the process of integrating JavaScript code directly
into the HTML document of a webpage. This integration allows the JavaScript code to be
executed within the context of the webpage, enabling functionalities such as interactivity,
dynamic content manipulation, form validation, and more.
There are three ways to embed JavaScript in a web page:
• Inline JavaScript: This is the simplest way to embed JavaScript in a web page. You can
simply write your JavaScript code between a pair of <script> and </script> tags. For
example:
Code
<script>
alert("Hello,world!");
</script>
This code will display an alert box with the message "Hello, world!" when the page loads.
• External JavaScript: You can also embed JavaScript in a web page by linking to an
external JavaScript file. To do this, you use the <script> tag with the src attribute. For
example
Code
<script src="my-script.js"></script>
This code will load the JavaScript file my-script.js when the page loads.
• Event Handlers: You can also use JavaScript to handle events on a web page. For
example, you can use JavaScript to display an alert box when a user clicks on a
button. To do this, you use the onclick attribute on the button tag. For example:
Code
<button onclick="alert('Hello, world!')">Click Me!</button>
This code will display an alert box with the message "Hello, world!" when the user clicks
on the Button.
Create a rollover effect that can change the color of its text using the style attribute.
<p
onmouseover=”this.style.color=’red'”
onmouseout=”this.style.color=’blue'”>
Move the mouse over this text to change its color to red. Move the mouse away to
change the text color to blue.
</p>
Comparison in JavaScript
Comparison in JavaScript refers to the process of evaluating two values or expressions to
determine whether they are equal, not equal, greater than, less than, greater than or equal to, or
less than or equal to. This is done using comparison operators, which return a Boolean value of
true or false.
• ==: Equal to
• !=: Not equal to
• ===: Strictly equal to
• !==: Strictly not equal to
• >: Greater than
• <: Less than
• >=: Greater than or equal to
• <=: Less than or equal to
The first two operators, == and !=, perform type coercion before comparing the values. This
means that they will try to convert the values to the same type before comparing them. For
example, if you compare a number to a string, the string will be converted to a number before the
comparison is made.
The next two operators, === and !==, perform strict equality comparisons. This means that they
will only return true if the values are the same type and value. For example, the following code
will return false, because the two values are different types:
JavaScript
1 === "1" // false
The last two operators, > and <, compare the values based on their order. Numbers are compared
numerically, and strings are compared lexicographically. For example, the following code will
return true, because the number 10 is greater than the number 5:
JavaScript
10 > 5 // true
Comparison operators are often used in conditional statements to control the flow of a
program. For example, the following code will print "The number is greater than 10" if the value
of the variable number is greater than 10:
JavaScript
if(number>10){
console.log("The number is greater than 10");
}
Comparison operators can also be used in expressions to create more complex comparisons. For
example, the following code will return true if the value of the variable number is greater than 10
and less than 20:
JavaScript
10 < number < 20 // true
Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Comparisons</title>
</head>
<body>
<h1>JavaScript Comparisons</h1>
<div id="output"></div>
<script>
// JavaScript code for comparisons
document.addEventListener("DOMContentLoaded", function() {
// Define variables
let a = 5;
let b = 10;
let c = 5;
let d = "5";
// Prepare output
let output = "";
// Equality comparisons
output += "<h2>Equality comparisons:</h2>";
output += "a == c: " + (a == c) + "<br>"; // true (loose equality, value comparison)
output += "a === c: " + (a === c) + "<br>"; // true (strict equality, value and type
comparison)
output += "a == d: " + (a == d) + "<br>"; // true (loose equality, type coercion)
output += "a === d: " + (a === d) + "<br><br>"; // false (strict equality, different
types)
// Relational comparisons
output += "<h2>Relational comparisons:</h2>";
output += "a < b: " + (a < b) + "<br>"; // true
output += "a <= c: " + (a <= c) + "<br>"; // true
output += "a > b: " + (a > b) + "<br>"; // false
output += "b >= c: " + (b >= c) + "<br><br>"; // true
// Logical comparisons
output += "<h2>Logical comparisons:</h2>";
output += "(a < 10) && (b > 5): " + ((a < 10) && (b > 5)) + "<br>"; // true
output += "(a < 10) || (b < 5): " + ((a < 10) || (b < 5)) + "<br>"; // true
output += "!(a === b): " + (!(a === b)) + "<br>"; // true
// Display output
document.getElementById("output").innerHTML = output;
});
</script>
</bodyc>
</html>
Built-in functions in JavaScript
Built-in functions in JavaScript are functions that are provided by the JavaScript language itself,
available for use without needing to define them explicitly. These functions are part of the
JavaScript runtime environment and can be accessed directly.
JavaScript comes with a rich set of built-in functions that perform common tasks such as
manipulating strings, working with arrays, performing mathematical operations, interacting with
the browser's Document Object Model (DOM), and more.
Here are some examples of built-in functions in JavaScript:
1. String Functions:
- `toUpperCase()`: Converts a string to uppercase.
- `substring()`: Extracts a part of a string.
- `indexOf()`: Returns the index of the first occurrence of a specified value in a string.
2. Array Functions:
- `push()`: Adds one or more elements to the end of an array and returns the new length of the
array.
- `pop()`: Removes the last element from an array and returns that element.
- `forEach()`: Executes a provided function once for each array element.
3. Math Functions:
- `Math.random()`: Returns a pseudo-random number between 0 and 1.
- `Math.floor()`: Rounds a number down to the nearest integer.
- `Math.max()`: Returns the largest of zero or more numbers.
4. DOM Functions:
- `document.getElementById()`: Returns a reference to the element by its ID.
- `document.createElement()`: Creates a new HTML element.
- `addEventListener()`: Attaches an event handler to the specified element.
Pattern matching
Pattern matching in JavaScript is a programming paradigm that allows developers to match
values against a pattern and execute code based on the match. It is not a native feature of
JavaScript, but there are several ways to implement it.
One way to implement pattern matching in JavaScript is to use regular expressions. Regular
expressions are sequences of characters that define a search pattern. They can be used to search
for patterns in text and to replace text with other text.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pattern Matching Example</title>
</head>
<body>
<h1>Pattern Matching Example</h1>
<p id="output"></p>
<script>
// Example string
let text = "The quick brown fox jumps over the lazy dog.";
document.getElementById("output").innerHTML = output;
</script>
</body>
</html>
JavaScript Object
In JavaScript, objects are variables that can store many values. Objects are similar to real-world
objects, having properties and methods.
• Properties
are the values associated with an object. A JavaScript object is a collection of unordered
properties. Properties can usually be changed, added, and deleted, but some are read only.
• Methods
are functions that are defined inside objects. Methods are used to perform actions on the
object.
For example, a car object might have properties like color, make, and model. It might also have
methods like drive() and stop().
Objects are a fundamental part of JavaScript. They are used to store and organize data, and to
perform actions on that data.
Here is an example of a JavaScript object:
const car = {
color: "red",
make: "Toyota",
model: "Camry",
drive: function() {
console.log("The car is driving.");
},
stop: function() {
console.log("The car has stopped.");
}
};
This object has three properties: color, make, and model. It also has two methods: drive() and
stop().
To access a property of an object, you use the dot notation. For example, to access the color
property of the car object, you would use the following code:
JavaScript
const carColor = car.color;
To call a method of an object, you use the parentheses notation. For example, to call the drive()
method of the car object, you would use the following code:
JavaScript
car.drive();
Objects are a powerful tool in JavaScript. They allow you to store and organize data, and to
perform actions on that data flexibly and efficiently.
Code(working on console)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Object Example</title>
</head>
<body>
<h1>JavaScript Object Example</h1>
<script>
// Define a JavaScript object
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
email: "john@example.com",
address: {
street: "123 Main St",
city: "Anytown",
country: "USA"
},
hobbies: ["reading", "coding", "hiking"],
sayHello: function() {
return "Hello, my name is " + this.firstName + " " + this.lastName;
}
};
1. Displaying Messages:
You can use `alert()`, `confirm()`, and `prompt()` functions to display messages or dialogs:
javascript
// Alert dialog
alert("Hello, this is an alert message!");
// Confirm dialog
let result = confirm("Are you sure you want to proceed?");
if (result) {
console.log("User confirmed!");
} else {
console.log("User cancelled!");
}
// Prompt dialog
let name = prompt("Please enter your name:", "");
console.log("Hello, " + name + "!");
2. Event Handling:
You can respond to user interactions, such as clicks, key presses, mouse movements, etc., using
event listeners:
html
<button id="myButton">Click Me</button>
<script>
// Event listener for button click
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
</script>
3. Updating HTML Content:
You can dynamically update the content of HTML elements:
Html
<p id="demo">This is some text.</p>
<script>
// Update content of paragraph
document.getElementById("demo").innerHTML = "This is updated text.";
</script>
4. Taking Input:
You can take input from users using forms and handle it using JavaScript:
html
<form id="myForm">
<input type="text" id="nameInput" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
<script>
// Event listener for form submission
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault(); // Prevent default form submission
let name = document.getElementById("nameInput").value;
alert("Hello, " + name + "!");
});
</script>
These are just a few examples of how you can interact with users using JavaScript. Depending
on your application's requirements, you can combine these techniques to create rich and
interactive user experiences on the web.
<h2>Length Converter</h2>
<script>
// Function to convert Kilometers to Meters
function convertKilometersToMeters(valNum) {
document.getElementById("outputMeters").innerHTML = valNum * 1000;
}
</body>
</html>
Form Checking
Form validation is the process of checking user input for errors before submitting it to a
server. This is important because it helps to ensure that the data is accurate and complete and that
it can be processed correctly.
There are several different ways to validate forms in JavaScript. One common approach is to use
regular expressions to check for patterns in the input. For example, you could use a regular
expression to check that an email address is in a valid format.
Another approach to form validation is to use the built-in validation features of
HTML5. HTML5 provides several attributes that can be used to specify the type of data that is
expected in a field and to provide feedback to the user if the input is invalid.
Form validation is an important part of any web application. By taking the time to validate your
forms, you can help to ensure that your data is accurate and complete and that your users have a
positive experience.
Here are some of the benefits of using JavaScript for form validation:
Overall, JavaScript form validation is a valuable tool that can help to improve the accuracy,
security, and user experience of your website.
code
<html>
<head>
<title>Form Validation</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<h2>Registration Form</h2>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br>
<span id="emailError" class="error"></span><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br>
// Username validation
if (username === "") {
document.getElementById("usernameError").innerHTML = "Username is required";
return false;
}
// Email validation
if (email === "") {
document.getElementById("emailError").innerHTML = "Email is required";
return false;
} else if (!validateEmail(email)) {
document.getElementById("emailError").innerHTML = "Invalid email format";
return false;
}
// Password validation
if (password === "") {
document.getElementById("passwordError").innerHTML = "Password is required";
return false;
} else if (password !== confirmPassword) {
document.getElementById("passwordError").innerHTML = "Passwords do not
match";
return false;
}
function validateEmail(email) {
// Regular expression for validating email format
let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
</script>
</body>
</html>
Testing
• Testing is a proactive process that is used to prevent errors from occurring in the first
place.
• Testing is typically done by a separate team of testers, who are not responsible for writing
the code.
• Testing can be done manually, or by using automated testing tools.
• The goal of testing is to verify that the code meets all of its requirements.
Debugging
• Debugging is a reactive process that is used to find and fix errors that have already
occurred.
• Debugging is typically done by the developers who wrote the code.
• Debugging is done using a variety of tools and techniques, such as using a debugger to
step through the code line by line, or by using print statements to output the values of
variables.
• The goal of debugging is to fix errors in the code so that it works as expected.
Both testing and debugging are essential for ensuring the quality of JavaScript code. By
following a disciplined approach to testing and debugging, developers can help to ensure that
their code is reliable and meets all of its requirements.
Its main function is to provide the Its primary function is to manipulate and provide
requested output to the end user. access to the respective database as per the request.
It does not provide security for data. It provides more security for data.
HTML, CSS, and javascript are used. PHP, Python, Java, Ruby are used.
No need of interaction with the server. It is all about interacting with the servers.