0% found this document useful (0 votes)
2 views

Introduction to JS notes

The document provides an overview of JavaScript's Math object, Date object, and various methods for user interaction and array manipulation. It details mathematical functions like Math.sin and Math.cos, date formatting, and methods such as alert, confirm, and prompt for user input. Additionally, it covers array methods like join and reverse, explaining their syntax, behavior, and practical examples.

Uploaded by

ravishankars1969
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Introduction to JS notes

The document provides an overview of JavaScript's Math object, Date object, and various methods for user interaction and array manipulation. It details mathematical functions like Math.sin and Math.cos, date formatting, and methods such as alert, confirm, and prompt for user input. Additionally, it covers array methods like join and reverse, explaining their syntax, behavior, and practical examples.

Uploaded by

ravishankars1969
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Math object

· The Math object is a built-in JavaScript object that provides mathematical


operations and constants
· It's static, meaning you cannot create an instance of Math using 'new'
· All methods and properties are accessed directly through the Math object
· All methods return consistent and predictable results across different platforms

1. Math.sin(x):
Definition: The Math.sin() method returns the sine of a number. Sine is a
fundamental trigonometric function, defined as the ratio of the length of the
opposite side to the hypotenuse in a right triangle.
Input: The input x is in radians. If you have degrees, you can convert them to radians
using the formula radians = degrees * (Math.PI / 180).
Range: The result of Math.sin(x) is always between -1 and 1.
Practical Use: Used in simulations, physics calculations, signal processing, and
animations to model periodic phenomena such as waves and oscillations.
Example:
var angleInRadians = Math.PI / 2; // 90 degrees
var sineValue = Math.sin(angleInRadians);
console.log(sineValue); // Output: 1

2. Math.cos(x):
Definition: The Math.cos() method returns the cosine of a number, which is another
fundamental trigonometric function. It is the ratio of the adjacent side to the
hypotenuse in a right triangle.
Input: Like Math.sin(), x is expected to be in radians.
Range: The result of Math.cos(x) is also between -1 and 1.
Practical Use: Similar to sine, cosine is used in calculations involving waveforms,
rotations, and other periodic phenomena.
Example:
var angleInRadians = Math.PI; // 180 degrees
var cosineValue = Math.cos(angleInRadians);
console.log(cosineValue); // Output: -1

3. Math.floor(x):
Definition: The Math.floor() method rounds a number down to the nearest integer. It
effectively truncates the decimal portion of the number, always moving towards
negative infinity.
Behavior:
For positive numbers, it removes the fractional part.
For negative numbers, it moves to the next lower integer.
Use Cases: Useful when you need an integer that is always less than or equal to the
original number, such as in array indexing or when dealing with user input where
only whole numbers are required.
Example:
var positiveNumber = Math.floor(3.8);
var negativeNumber = Math.floor(-3.8);
console.log(positiveNumber); // Output: 3
console.log(negativeNumber); // Output: -4

4. Math.round(x):
Definition: The Math.round() method rounds a number to the nearest integer. It
considers the fractional part to decide whether to round up or down.
Behavior:
If the fractional part is 0.5 or greater, it rounds up.
If less than 0.5, it rounds down.
Use Cases: Commonly used for rounding to the nearest whole number, such as in
financial applications where precise rounding rules are needed.
Example:
var roundedUp = Math.round(2.7);
var roundedDown = Math.round(2.3);
console.log(roundedUp); // Output: 3
console.log(roundedDown); // Output: 2

5. Math.max(x, y):
Definition: The Math.max() method returns the largest of the two numbers provided
as arguments.
Behavior:
Can handle multiple arguments and returns the largest value.
If any argument is not a number or is NaN, the result is NaN.
Use Cases: Useful for finding the maximum value in datasets, comparing user inputs,
and conditional checks in algorithms.
Example:
var maxValue = Math.max(10, 20);
console.log(maxValue); // Output: 20

The Date Object in JavaScript


The Date object in JavaScript is a built-in object that allows developers to create,
manipulate, and format dates and times. It provides a comprehensive set of
methods for handling dates and times in various formats and for different time
zones.

Date Formats
The Date object in JavaScript can be initialized in several ways to suit different needs:
1. Default Constructor:
Creates a Date object representing the current date and time.
Example:
var today = new Date();
console.log(today);
// Output: "Tue Nov 27 2024 12:34:56 GMT+0530 (India Standard Time)"

2. Specific Date and Time:


You can initialize the Date object with a specific date and time using a string in the
ISO 8601 format.
Example:
var specificDate = new Date("2024-12-25T10:30:00");
console.log(specificDate);
// Output: "Wed Dec 25 2024 10:30:00 GMT+0530"

3. Year, Month, Day, etc.:


Initialize a Date object by providing specific components: year, month, day, hour,
minute, and second.
Note: The month is zero-based (0 for January, 11 for December).
Example:
var customDate = new Date(2024, 11, 25, 10, 30, 0);
console.log(customDate);
// Output: "Wed Dec 25 2024 10:30:00"

Working with Date and Time


The Date object provides methods to access and manipulate various components of
date and time.
Getting the Date and Time Components:
Retrieve specific parts of the date using these methods:
var now = new Date();
console.log(now.getFullYear()); // Example output: 2024
console.log(now.getMonth()); // Example output: 10 (November)
console.log(now.getDate()); // Example output: 27
console.log(now.getHours()); // Example output: 12
console.log(now.getMinutes()); // Example output: 34

UTC vs Local Time


JavaScript can handle both local and UTC (Coordinated Universal Time) time formats:

Local Time:

Reflects the user's local time zone.


Example:
console.log(now.toLocaleString());
// Output: "11/27/2024, 12:34:56 PM"

UTC Time:

Universal Time, unaffected by local time zones.


Example:
console.log(now.toUTCString());
// Output: "Wed, 27 Nov 2024 07:04:56 GMT"

Why Use the Date Object?


The Date object is essential in web development for several reasons:
Time-Sensitive Tasks:
Useful for scheduling and managing tasks that need to occur at specific times, such
as reminders, alarms, or periodic updates.

Display and Format Dates:


Helps in dynamically displaying the current date and time on websites.
Formats dates in user-friendly ways, enhancing user experience.

Calculating Time Differences:


Allows you to compute durations or intervals between dates, such as counting days
to a deadline or measuring time elapsed for an event.
By leveraging the Date object, developers can build applications that are time-aware
and responsive to user needs.

Screen Output and Keyboard Input


In JavaScript, the Window object models the browser window in which the HTML
document is displayed. This object contains properties that allow you to interact
with the page, including the document property which is used to access and
manipulate the content of the page.
Writing Output to the Screen
The document.write() method is used to write content directly to the browser
window. When you use this method, the content is rendered as if it were part of the
HTML document.

Syntax:

document.write("Hello");

Result: When you use document.write(), it will write the string provided as the
parameter into the HTML document. If you write document.write("Hello");, the
output in the browser will display the text Hello.
Interpolating Line Breaks
If you want to insert a line break in the output, you can use the <br/> tag, which is
interpreted as a line break in HTML.

Example:
document.write("Hello<br/>World");
Result: This will output the following on the page:
Hello
World
The <br/> tag creates a line break between the two words.

Example Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document Write Example</title>
</head>
<body>
<script>
document.write("Hello<br/>");
document.write("This is an example of using document.write.<br/>");
document.write("Goodbye!");
</script>
</body>
</html>

The Alert Method in JavaScript(refer Slide no 46)


In JavaScript, the alert() method is used to display a dialog box with a message for
the user. This dialog box typically appears as a pop-up window in the browser,
showing the message and an "OK" button that the user can click to close it. This
method is particularly useful for notifying users or displaying important information,
but it does not allow for interactive input, making it ideal for simple notifications.

Example Usage of alert()


The syntax for the alert() method is straightforward:

alert("Your message here");


For instance, if you want to display the sum of two numbers in an alert dialog, you
could write:
var sum = 42;
alert("The sum is: " + sum);

This would result in an alert box showing the message: "The sum is: 42" along with
an "OK" button for the user to dismiss the alert.
Formatting the Message in the Alert Box

While the alert() method does not interpret HTML or XHTML tags, you can use
newline characters (\n) to format your message. This allows you to break the
message into multiple lines within the dialog box. For example:
alert("The sum is:" + sum + "\nThis is a new line.");
This would display the message with a line break, giving a cleaner presentation.

Conclusion
In conclusion, the alert() method is a simple but effective tool for showing messages
to users in JavaScript. By using it properly, you can communicate necessary
information in a straightforward and non-interactive manner. Keep in mind, though,
that excessive use of alerts can be disruptive to the user experience, so it’s best used
sparingly.

The confirm() Method in JavaScript


(refer Slide no Slide no 47)

The confirm() method in JavaScript is used to display a dialog box with a message
and two buttons: OK and Cancel. This method is typically used to ask the user for a
confirmation before proceeding with an action, such as submitting a form,
performing a deletion, or confirming a download.

How confirm() Works


Message Displayed: The confirm() method takes a single string parameter, which is
the message you want to display to the user.

User Interaction: The dialog box will show two buttons:


OK: If the user presses OK, the method returns true.
Cancel: If the user presses Cancel, the method returns false.

Syntax:
var result = confirm("Your message here");
If the user presses OK: The value of result will be true.
If the user presses Cancel: The value of result will be false.

Example:
var question = confirm("Do you want to continue this download?");
if (question) {
console.log("User chose OK. Proceeding with the download...");
} else {
console.log("User chose Cancel. Aborting the download.");
}

How it Works:
When the confirm() method is called, a dialog box appears with the message "Do you
want to continue this download?", along with OK and Cancel buttons.
If the user clicks OK, the variable question will be true, and the message "User chose
OK. Proceeding with the download..." will be logged to the console.
If the user clicks Cancel, the variable question will be false, and the message "User
chose Cancel. Aborting the download." will be logged.

Use Case:
The confirm() method is useful in situations where you need to get user consent
before proceeding, such as confirming actions that cannot be undone (like deleting
something or continuing with a payment). It's an essential tool for controlling the
flow of interactions with users in web applications.
The prompt() Method in JavaScript
(refer Slide noSlide no 48)

The prompt() method is used to display a dialog box that asks the user for input. It
takes two arguments: a message to display to the user and an optional default value
for the input field.

How prompt() Works


Message: The first argument is the message displayed to the user in the dialog box.
Default Value: The second argument is optional and represents the default text that
will appear in the input field. If not provided, the input field will be empty.
When the user types something in the input field and presses OK, the method
returns the text that the user entered. If the user presses Cancel, it returns null.

Syntax:
var result = prompt("Your message here", "Default text here");
If the user enters text and presses OK: The value of result will be the text entered by
the user.
If the user presses Cancel: The value of result will be null.

Example:
var name = prompt("What is your name?", "John Doe");
if (name != null) {
console.log("Hello, " + name + "!");
} else {
console.log("User cancelled the prompt.");
}

Explanation:
The prompt() method displays the message "What is your name?" with a default
value of "John Doe".
If the user enters a name and clicks OK, the value entered by the user will be stored
in the variable name, and the message "Hello, [name]!" will be logged to the console.
If the user clicks Cancel, the variable name will be null, and the message "User
cancelled the prompt." will be logged to the console.

Use Case:
The prompt() method is commonly used when you need to gather user input directly
in a web page. For example, you can use it to ask for the user's name, their
preferences, or any other text-based information before continuing with a process in
your JavaScript application.
Array Methods

1. Array Methods: join()


The join() method in JavaScript is used to combine all elements of an array into a
single string, with a specified separator between them.

Syntax:
array.join(separator);
separator (optional): A string that separates each array element in the resulting
string. If omitted, the default separator is a comma (,).

The method returns a string that contains the concatenated elements of the array,
separated by the specified separator.
How join() Works:

Without a Separator: If you call join() without passing a separator, the array
elements are concatenated with a comma as the default separator.

Example:
var colors = ["Red", "Green", "Blue"];
var result = colors.join(); // Default separator: comma
console.log(result); // Output: "Red,Green,Blue"

With a Custom Separator: If you provide a separator string as an argument, that


string is used to separate the array elements in the resulting string.

Example with custom separator:


var colors = ["Red", "Green", "Blue"];
var result = colors.join(" : "); // Using " : " as the separator
console.log(result); // Output: "Red : Green : Blue"

Example of join() Method:


var names = ["Blue", "Green", "Yellow"];
var name_string = names.join(" : "); // The elements are separated by " : "
console.log(name_string); // Output: "Blue : Green : Yellow"
In the example above:
The join(" : ") method concatenates the elements of the names array using the string
" : " as the separator.
The resulting string is "Blue : Green : Yellow".
2.Array Method: reverse()(refer Slide no 69)

The reverse() method in JavaScript is used to reverse the order of the elements in an
array. When called, it mutates the original array, meaning it directly changes the
order of the elements within the array, rather than creating a new array.

Syntax:
array.reverse();
The reverse() method does not take any parameters.
It modifies the array in place and returns the same array, now with its elements in
reverse order.

How reverse() Works:


When you call the reverse() method on an array, it reverses the order of the
elements in that array. The first element becomes the last, the second element
becomes the second-last, and so on.

Example:
<body>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.reverse();
</script>
</body>

In this example, we define an array fruits with four elements: ["Banana", "Orange",
"Apple", "Mango"].
After calling fruits.reverse(), the order of the elements changes, and the array
becomes ["Mango", "Apple", "Orange", "Banana"].
The resulting array is displayed in the <p> element, which shows:
"Mango,Apple,Orange,Banana".

Key Points:
In-place Modification: The reverse() method modifies the original array. It does not
create a new array.

Mutating the Array: Since reverse() mutates the array, if you need to preserve the
original order, you should create a copy of the array first.

Example:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const reversedFruits = [...fruits].reverse(); // Creates a new array with reversed
order
console.log(fruits); // Original order: ["Banana", "Orange", "Apple", "Mango"]
console.log(reversedFruits); // Reversed order: ["Mango", "Apple", "Orange",
"Banana"]

Returns the Reversed Array: The method returns the reversed array, which can be
assigned to a variable or used directly.

Summary of reverse():
The reverse() method changes the order of elements in an array.
It mutates the original array.
It returns the array with the elements in reverse order.
This method is commonly used when you want to reverse an array for operations
like sorting or displaying items in a different order.

3.Array Method: sort()(refer Slide no Slide no 70)

The sort() method in JavaScript is used to sort the elements of an array in ascending
order by default. The sorting is done based on string comparison, meaning that
elements are first coerced into strings (if they are not already strings) and then
sorted alphabetically.

Syntax:

array.sort();
sort() without any arguments sorts the array elements as strings in lexicographical
(alphabetical) order.

How sort() Works:

String Coercion: If the elements in the array are not already strings, JavaScript will
automatically convert them into strings.

Lexicographical Order: The elements are sorted as strings based on the Unicode
values of the characters. This can lead to unexpected results when sorting numbers,
as they are sorted lexicographically rather than numerically.

Example:
<body>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.sort();
</script>
</body>
In this example, the fruits array contains four strings: ["Banana", "Orange", "Apple",
"Mango"].
When we call fruits.sort(), JavaScript will sort the elements alphabetically as strings.
The sorted array will be: ["Apple", "Banana", "Mango", "Orange"].
Key Points:

Alphabetical Sorting: By default, the sort() method sorts array elements in ascending
order based on their string values.

For example:

["Apple", "Banana", "Mango", "Orange"] becomes ["Apple", "Banana", "Mango",


"Orange"].

String Conversion: If the elements are not already strings, they are converted into
strings before sorting. This can lead to unexpected results, especially when sorting
numbers.

Example with numbers:

const numbers = [10, 2, 5, 1];


console.log(numbers.sort()); // Output: [1, 10, 2, 5] (sorted as strings)

In the above case, the numbers are sorted lexicographically as strings, not
numerically. To sort numbers properly, you need to pass a custom comparison
function to sort().
Modifies the Original Array: The sort() method modifies the original array and
returns the sorted array.

4.Array Method: concat()(Refer Slide no 71)


The concat() method in JavaScript is used to combine or concatenate two or more
arrays (or values) into a new array. It does not modify the original array but returns a
new array containing the elements of the original array followed by the elements of
the arguments passed to the method.

Syntax:
array.concat(value1, value2, ..., valueN);
value1, value2, ..., valueN: These can be arrays or any values (such as strings,
numbers, or other arrays) that you want to concatenate to the original array.

How concat() Works:

Concatenate Arrays: If arrays are passed as arguments to concat(), their elements


are appended to the original array.
Concatenate Non-array Values: You can also concatenate non-array values (like
strings or numbers) to the array. These values will simply be added to the end of the
array.
Does Not Modify the Original Array: The concat() method does not modify the
original array. Instead, it returns a new array that contains the combined elements.

Example:
var names = ["Mary", "Murray", "Murphy", "Max"];
var new_names = names.concat("Moo", "Meow");

console.log(new_names); // Output: ["Mary", "Murray", "Murphy", "Max", "Moo",


"Meow"]

In this example:
The concat() method is called on the names array.
The values "Moo" and "Meow" are passed as arguments to concat().
These values are added to the end of the original names array, resulting in a new
array new_names with the combined values: ["Mary", "Murray", "Murphy", "Max",
"Moo", "Meow"].

Key Points:
Non-modifying: The original array remains unchanged, and a new array is returned
with the concatenated values.

5.Array Method: slice()(refer Slide no 72-73)

The slice() method in JavaScript is used to extract a shallow copy of a portion of an


array into a new array, without modifying the original array. It allows you to specify a
start index and an end index, and it returns a new array containing the elements
from the start index up to, but not including, the end index.

Syntax:
array.slice(start, end);
start: The index at which to begin extraction. If omitted, it defaults to 0.
end: The index at which to end extraction (not including the element at this index). If
omitted, it defaults to the length of the array.
The slice() method does not modify the original array. It returns a new array with the
extracted elements.

How slice() Works:


Start Index: The slice starts from the index specified by the start parameter
(inclusive).
End Index: The slice ends just before the index specified by the end parameter
(exclusive). If end is not provided, it slices until the end of the array.
Returns a New Array: The method returns a new array containing the selected
elements, leaving the original array unchanged.

Example:
<script>
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1);

document.write("Citrus elements are: " + citrus); // Output: Citrus elements are:


Orange,Lemon,Apple,Mango
document.write("<br>");
document.write("Fruits elements are: " + fruits); // Output: Fruits elements are:
Banana,Orange,Lemon,Apple,Mango
</script>

In this example:
fruits.slice(1) extracts the elements starting from index 1 (inclusive) until the end of
the array.
The new array citrus contains ["Orange", "Lemon", "Apple", "Mango"].
The original fruits array remains unchanged: ["Banana", "Orange", "Lemon", "Apple",
"Mango"].

Key Points:
Extracts a Portion: slice() is used to extract a subset of the array, from the start index
up to (but not including) the end index.
Does Not Modify the Original Array: Unlike methods like splice(), slice() does not
change the original array.
Returns a New Array: The method returns a new array with the extracted elements,
which you can store in a new variable.
Examples:

6.Array Method: toString()(refer Slide no 74)

The toString() method in JavaScript is used to convert an array (or any object) into a
string representation. When called on an array, the toString() method converts each
element of the array to a string (if necessary) and concatenates them, separating
them by commas.

Syntax:
array.toString();
This method does not modify the original array. Instead, it returns a string
representation of the array, with the array elements separated by commas.

How toString() Works:


Converts Array Elements to Strings: If the array elements are not already strings,
JavaScript will convert them into strings using the String() function.

Concatenates the Elements: All elements are concatenated into a single string, with
each element separated by a comma.

Does Not Modify the Original Array: The toString() method does not alter the array
itself; it only returns a string version of the array.

Example:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const fruitString = fruits.toString();
console.log(fruitString); // Output: "Banana,Orange,Apple,Mango"
In this example:
The fruits array is converted into a string by calling toString().
The elements are separated by commas, resulting in the string:
"Banana,Orange,Apple,Mango".

Key Points:

String Conversion: Each element of the array is converted into a string (if it is not
already a string) and then concatenated.

Comma-Separated: The elements are separated by commas in the resulting string.

Non-modifying: The toString() method does not modify the original array; it returns a
new string.

Works on Other Objects: The toString() method is not limited to arrays. It can be
used to convert other types of objects to their string representation.

Example with Different Data Types:

const mixedArray = [1, true, null, { name: "John" }];


const result = mixedArray.toString();

console.log(result); // Output: "1,true,,[object Object]"


In this case:
The number 1 is converted to "1".
The boolean true is converted to "true".
The null value becomes an empty string.
The object { name: "John" } is converted to its string representation: "[object
Object]".
Summary of toString():
The toString() method converts an array (or other objects) into a comma-separated
string of elements.
The original array is not modified.
The method is useful when you want to quickly convert an array to a string for
display or manipulation.
Each element is coerced into a string if necessary.

(7-10.)Array Methods for Stacks and Queues: push(), pop(), unshift(), and
shift()(refer Slide no 75)
In JavaScript, the push(), pop(), unshift(), and shift() methods are used to add and
remove elements from an array. These methods are especially useful for
implementing stacks and queues, which are common data structures.

1. push() Method:
Purpose: Adds one or more elements to the end of an array.
Returns: The new length of the array after the element(s) are added.
Use Case: Often used in stacks (LIFO—Last In, First Out), where elements are added
to the end of the array.

Syntax:
array.push(element1, element2, ..., elementN);
Example:
var list = ["Banana", "Orange", "Lemon"];
list.push("Apple");

console.log(list); // Output: ["Banana", "Orange", "Lemon", "Apple"]


In this example, the element "Apple" is added to the end of the list array.

2. pop() Method:
Purpose: Removes the last element from an array.
Returns: The element that was removed.
Use Case: Common in stack operations (LIFO), where you pop elements from the end
of the array.
Syntax:
array.pop();
Example:
var list = ["Banana", "Orange", "Lemon", "Apple"];
var list2 = list.pop();

console.log(list); // Output: ["Banana", "Orange", "Lemon"]


console.log(list2); // Output: "Apple"
Here, the pop() method removes "Apple" from the end of the list array.
3. unshift() Method:
Purpose: Adds one or more elements to the beginning of an array.
Returns: The new length of the array.
Use Case: Often used in queues (FIFO—First In, First Out), where elements are added
to the front of the array.
Syntax:
array.unshift(element1, element2, ..., elementN);
Example:
var list = ["Banana", "Orange", "Lemon"];
list.unshift("Apple");

console.log(list); // Output: ["Apple", "Banana", "Orange", "Lemon"]


In this case, "Apple" is added to the beginning of the array.

4. shift() Method:
Purpose: Removes the first element from an array.
Returns: The element that was removed.
Use Case: Common in queue operations (FIFO), where you shift elements from the
beginning of the array.
Syntax:
array.shift();
Example:
var list = ["Banana", "Orange", "Lemon", "Apple"];
var list2 = list.shift();

console.log(list); // Output: ["Orange", "Lemon", "Apple"]


console.log(list2); // Output: "Banana"
Here, the shift() method removes "Banana" from the beginning of the array.

You might also like