Java Script
Java Script
Definition of JavaScript:
It is a high level programming language primarily used for creating
interactive effects and functionality to website.
Versatile language that allows developers to add dynamic behavior to
websites ranging from simple function like form validation to complex
application like online games and social media platforms.
It is an essential part of web development alarm say HTML and CSS
forming the web of modern web application.
Features of JavaScript:
JavaScript is supported by all major web browsers making it a
universal language for client slide scripting.
JavaScript is dynamically typed meaning variable types are determined
at runtime offering flexibility in coding.
Objects in JavaScript are based on prototypes rather than classes
enabling dynamic object creation and manipulation.
JavaScript provides powerful APIs for manipulating the document
object model(DOM) of web pages enabling dynamic updates and
interactivity.
JavaScript supports modularity to modules enabling code organization
usability and maintainability in large scale application
JavaScript can be extended through libraries and frameworks like
react, angular offering additional functionality and simplifying
development task
Various objects in JavaScript:
Math Object:
The Math object in JavaScript serves as a toolbox for handling mathematical tasks.
It's a built-in object that doesn't require instantiation; you can access its properties
and methods directly.
Math Constants: It provides constants like Math.PI for the mathematical
constant π, and Math.E for Euler's constant.
Math Methods: These include functions for basic arithmetic operations
(Math.round(), Math.floor(), Math.ceil()), trigonometry (Math.sin(),
Math.cos(), Math.tan()), exponentiation (Math.pow()), logarithms
(Math.log(), Math.log10()), and random number generation (Math.random()).
String Object:
The String object represents a sequence of characters. While strings can be created
using primitive literals (e.g., "hello"), the String object provides additional methods
for manipulating and working with strings.
String Methods: These methods include functions for concatenation
(concat()), finding substrings (indexOf(), lastIndexOf(), includes()), extracting
substrings (substring(), slice()), converting case (toUpperCase(),
toLowerCase()), trimming whitespace (trim()), and more.
Date Object:
The Date object in JavaScript handles dates and times. It enables creating,
manipulating, and formatting dates.
Creating Dates: You can create a Date object with or without parameters. If
no parameters are provided, it represents the current date and time.
Date Methods: Methods like getFullYear(), getMonth(), getDate() retrieve
specific parts of a date, while setFullYear(), setMonth(), setDate() modify
them. Formatting methods like toLocaleString() and toUTCString() convert
dates to strings in different formats.
Boolean and Number Object:
Though JavaScript has primitive boolean and numeric types (true/false, and
numbers), there are wrapper objects Boolean and Number that provide additional
functionality.
2
Wrapper Objects: These can be instantiated with new Boolean() or new
Number(), though it's rarely necessary as JavaScript automatically converts
primitives to objects when needed.
Methods: Boolean object provides methods like valueOf() to get the boolean
value. Number object offers methods for string to number conversion
(parseInt(), parseFloat()), and checking for special numeric values (isNaN(),
isFinite()).
2. isNaN():
Purpose: This function checks whether a value is NaN (Not a
Number). It's particularly useful when dealing with mathematical
operations that may result in non-numeric values.
Example:
isNaN("Hello"); // true
isNaN(42); // false
3
3. isFinite():
Purpose: Checks if a value is a finite number, meaning it is
neither positive nor negative infinity, nor NaN. It's helpful for
validating numerical inputs and avoiding unexpected behavior in
mathematical calculations.
Example:
isFinite(42); // true
isFinite(Infinity); // false
4.eval():
Purpose: The eval() function evaluates a string of JavaScript
code and executes it within the current scope. While powerful, it
should be used with caution due to security risks and potential
performance implications.
Example:
let x = 10;
let y = 20;
eval("console.log(x + y)"); // Outputs: 30
4
Example:
let uri = "https://example.com?q=hello world";
let encodedURI = encodeURI(uri); // Encodes URI
let decodedURI = decodeURI(encodedURI); // Decodes URI
let encodedComponent = encodeURIComponent(uri); // Encodes URI
component
let decodedComponent = decodeURIComponent(encodedComponent); //
Decodes URI component
setInterval(function() {
console.log("Repeating message");
}, 1000); // Executes every 1 second
5
Defining JavaScript functions:
In JavaScript, you define a function using the function keyword, followed by
the function name (if any), a list of parameters enclosed in parentheses
(optional), and then the function body enclosed in curly braces {}. Here's a
breakdown of each component:
1. function keyword: Indicates that you're declaring a function.
2. Function name: It's optional. If provided, it serves as an identifier for
the function, allowing you to call it by name later in your code. Naming
functions is a good practice as it makes your code more readable and
understandable. However, you can also create anonymous functions
without a name.
3. Parameters: Also optional. They are variables listed inside the
parentheses of the function declaration. These act as placeholders for
values that the function will receive when it is called. Parameters are
separated by commas if there are multiple parameters.
4. Function body: It consists of the code that defines what the function
does when it's called. This code can include any valid JavaScript
statements, such as variable declarations, conditional statements,
loops, and other function calls. It's enclosed within curly braces {}.
Syntax:
function functionName(parameter1, parameter2, ...) {
// Function body
// This is where you write the code that defines what the function does
// You can use the parameters to perform operations or calculations
// Optionally, you can use the return statement to send back a value to
the caller
}
6
Calling JavaScript Function:
Calling a JavaScript function involves invoking the function by its name
and providing any necessary arguments. Here's a breakdown of how to
call a function:
1. Function Name: Identify the function you want to call by using its
name.
2. Arguments (if any): If the function expects parameters, provide the
required arguments within parentheses. These arguments are the
values that the function will work with inside its body.
3. Call Syntax: Write the function call with the function name followed
by parentheses containing the arguments (if any).
Syntax:
functionName(argument1, argument2, ...);
7
</head>
<body>
<h2>Greeting Program</h2>
<!-- Button to trigger the greeting -->
<button onclick="greetUser()">Click Me</button>
</body>
</html>
Example Program:
<!DOCTYPE html>
<html lang="en">
<head>
8
<title>Greeting Program</title>
<script>
// Function to greet the user when the button is clicked
function greetUser() {
alert('Hello again! Thanks for clicking the button!');
}
</script>
</head>
<body>
<h2>Greeting Program</h2>
<!-- Button to trigger the greeting -->
<button onclick="greetUser()">Click Me</button>
</body>
</html>
9
<body>
<h2>Simple Form</h2>
<form id="myForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Other than action and methods, there are the following useful methods also which are
provided by the HTML Form Element
10
o submit (): The method is used to submit the form.
o reset (): The method is used to reset the form values.
Example:
document.getElementById('myForm').onsubmit = function(event) {
event.preventDefault(); // Prevent the form from submitting
alert('Form submitted!'); // Display an alert
};
11
This JavaScript code attaches an event listener to the form's submit event.
When the form is submitted, the function prevents the default form
submission behavior using event.preventDefault() and displays an alert
message.
Example Program:
Here's how you can combine HTML and JavaScript to create a simple form
that displays an alert when submitted:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Simple Form</title>
</head>
<body>
<h2>Simple Form</h2>
<form id="myForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById('myForm').onsubmit = function(event) {
event.preventDefault(); // Prevent the form from submitting
alert('Form submitted!'); // Display an alert
};
12
</script>
</body>
</html>
13