Introduction to JS notes
Introduction to JS notes
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
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)"
Local Time:
UTC Time:
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>
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 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.
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.
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
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"
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.
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.
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.
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:
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.
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.
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.
Example:
var names = ["Mary", "Murray", "Murphy", "Max"];
var new_names = names.concat("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.
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.
Example:
<script>
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1);
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:
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.
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.
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.
(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");
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();
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();