You are on page 1of 13

JavaScript

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()).

Global functions in JavaScript:


1. parseInt() and parseFloat():
 Purpose: These functions are used to convert strings into
integers or floating-point numbers, respectively. They are
commonly used when working with user input or parsing data
from external sources.
Example:
let intValue = parseInt("10"); // intValue = 10
let floatValue=parseFloat("3.14"); // floatValue = 3.14

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

5. decodeURI(), encodeURI(), decodeURIComponent(), and


encodeURIComponent():
 Purpose: These functions are used for encoding and decoding
Uniform Resource Identifiers (URIs) and their components. They
ensure that special characters are properly handled in URLs,
preventing errors and allowing for safe data transmission.

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

6. setTimeout() and setInterval():


a. Purpose: These functions are used to schedule the execution of
a function after a specified delay (setTimeout()) or repeatedly at
a given interval (setInterval()). They are commonly used in
asynchronous programming for tasks such as animation, data
fetching, and periodic updates.
Example:
setTimeout(function() {
console.log("Delayed message");
}, 2000); // Executes after 2 seconds

setInterval(function() {
console.log("Repeating message");
}, 1000); // Executes every 1 second

Defining JavaScript function and calling JavaScript function:

What is a Function in JavaScript?


In JavaScript, a function is a block of reusable code that performs a specific
task or calculates a value. Functions are fundamental building blocks of
JavaScript programs, allowing developers to organize code into logical units,
improve code reusability, and facilitate abstraction.

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, ...);

Example program on defining JavaScript functions and calling JavaScript


functions:
<!DOCTYPE html>
<html lang="en">
<head>
<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>

7
</head>
<body>
<h2>Greeting Program</h2>
<!-- Button to trigger the greeting -->
<button onclick="greetUser()">Click Me</button>
</body>
</html>

Passing of parameters to a function in JavaScript:

Passing parameters to a function in JavaScript allows you to provide input


data to the function, which the function can then use to perform its
operations. Here's how you can do it along with an example program:
Passing Parameters to a Function:
1. Define Parameters: When defining a function, you can specify
parameters inside the parentheses. These parameters act as
placeholders for the values that will be passed to the function when
it's called.
2. Call the Function with Arguments: When calling the function, provide
the actual values (arguments) for the parameters defined in the
function declaration. These arguments are passed to the function in
the order they're listed in the function definition.

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>

Form Handling in JavaScript :


Forms are the basics of HTML. We use HTML form element in order to
create the JavaScript form. For creating a form, we can use the following
sample code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Simple Form</title>
</head>

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>

In the above example:


o Form name tag is used to define the name of the form. The name of
the form here is " myForm ". This name will be referenced in the
JavaScript form.
o The action tag defines the action, and the browser will take to tackle
the form when it is submitted. Here, we have taken no action.
o The method to take action can be either post or get, which is used
when the form is to be submitted to the server. Both types of methods
have their own properties and rules.
o Then input type tag defines the type of inputs we want to create in
our phone here in the above example we used an input tag set as
‘text’ to give inputs for the name and e-mail fields in the form
o Next we have taken the input type as submit for submitting the form
through a button

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.

Referencing the forms in JavaScript:


Now, we have created the form element using HTML, but we also need to
make its connectivity to JavaScript. For this, we use the getElementById ()
method that references the html form element to the JavaScript code.

The syntax of using the getElementById() method is as follows:

let form = document.getElementById('myForm');

Using the Id of the form, we can make the reference.

Submitting the form:


We can use JavaScript to handle form submission and perform actions such
as validation before submitting the form. For example, to prevent the form
from submitting and display an alert when the submit button is clicked, here
is a sample program demonstrating it

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>

This example demonstrates the basics of handling forms in JavaScript,


including accessing form elements, preventing form submission, and
performing actions on form submission.

13

You might also like