Important JavaScript Notes
1. Basics of JavaScript
Features of JavaScript:
- Object-based scripting language.
- Handles dates and time.
- Light-weight and client-side technology.
- Case-sensitive.
- Predefined objects like Math, Date.
Comparison Operators:
- ==, !=, >, <, >=, <=, ===, !==
2. JavaScript Objects
Creating Objects:
var person = {
firstname: "John",
lastname: "Doe",
age: 30,
eyecolor: "blue"
};
Getter and Setter Methods:
let car = {
get color() { return this.defColor; },
set color(newColor) { this.defColor = newColor; }
};
3. Functions and Events
Event Handlers:
Example: onClick, onMouseOver, onUnload.
Function called from HTML:
<body onload="welcome()"></body>
<script>
function welcome() { alert("Welcome!"); }
</script>
Prompt and Confirm Methods:
var name = prompt("Enter your name:");
var isSure = confirm("Are you sure?");
4. String and Array Methods
String Methods:
- charAt(index), indexOf(substring), replace(old, new).
Array Methods:
- concat(): Combines arrays.
- join(delimiter): Converts array to string.
5. Web Development
Cookies:
Set: document.cookie = "name=value;expires=date;";
Read:
var cookies = document.cookie.split(";");
Window and Location Objects:
Window Methods: open(), close(), alert().
Location Methods: reload(), assign(), replace().
6. Interactive Elements
Slideshow Example:
var images = ["1.jpg", "2.jpg", "3.jpg"];
var index = 0;
function nextSlide() {
index = (index + 1) % images.length;
document.getElementById("slide").src = images[index];
Drop-down Menu for Redirection:
<select onchange="window.location=this.value;">
<option value="https://www.google.com">Google</option>
</select>
7. Regular Expressions
Search Method:
var str = "Hello World!";
var result = str.search(/World/i);
8. Form Validation
Name and Email Validation:
function validate() {
if (!document.form.name.value) alert("Name is required.");
if (!document.form.email.value.includes("@")) alert("Invalid email.");