Javascript Notes
Javascript Notes
APPLICATION OF JAVASCRIPT:
Client-side validation,
Dynamic drop-down menus,
Displaying date and time,
Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm
dialog box and prompt dialog box),
Displaying clocks etc.
It provides code re usability because single JavaScript file can be used in several html
pages.
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
Keywords in JavaScript:
Keywords in JavaScript are reserved words that have special meanings and
purposes in the language.
1. break: Used to exit a loop or switch statement.
2. case: Used in a switch statement to specify different code to execute
based on a particular value.
3. catch: Used to catch and handle exceptions in a try-catch block.
4. class: Introduced in ECMAScript 6 (ES6), used to define classes and
create objects using the class-based syntax.
5. const: Used to declare a constant variable with a value that cannot be
reassigned.
6. continue: Used to skip the current iteration of a loop and move to the
next one.
7. debugger: Used to set a breakpoint in your code for debugging
purposes.
8. default: Used in a switch statement to specify the code to execute when
no other case matches.
9. delete: Used to remove a property from an object.
10.do: Used to create a do-while loop.
11.else: Used to specify the code to execute if a conditional statement is
false.
12.export: Used to export variables, functions, or classes from a module in
ES6 modules.
13.extends: Used to create a subclass in class inheritance.
14.false: A boolean value representing the concept of "false."
15.finally: Used in a try-catch-finally block to specify code that always
executes, whether an exception is thrown or not.
16.for: Used to create a for loop.
17.function: Used to declare a function.
18.if: Used to create a conditional statement.
19.import: Used to import variables, functions, or classes from a module in
ES6 modules.
20.in: Used to check if an object has a certain property.
21.instanceof: Used to check if an object is an instance of a particular class
or constructor function.
22.new: Used to create an instance of a constructor function or a class.
23.null: A special value representing the absence of an object.
24.return: Used to specify the value to return from a function.
25.super: Used to call a method on the superclass in class inheritance.
26.switch: Used to create a switch statement for multi-case branching.
27.this: Refers to the current context or object.
28.throw: Used to throw an exception.
29.true: A boolean value representing the concept of "true."
30.try: Used to create a try-catch block for exception handling.
31.typeof: Used to check the data type of an expression.
32.var: Used to declare a variable (older way, avoid using var in favor of let
and const in modern JavaScript).
33.void: Used to evaluate an expression and return undefined.
34.while: Used to create a while loop.
35.with: Used to create a block in which you can access object properties
without specifying the object explicitly (not recommended and
discouraged in modern JavaScript).
function example() {
var x = 10;
if (true) {
var x = 20; // This reassigns the outer 'x'
}
console.log(x); // Outputs 20
}
let:
Variables declared with let are block-scoped, meaning they are only accessible within
the nearest enclosing pair of curly braces (block) where they are defined.
Variables declared with let can be reassigned, but they cannot be re-declared within
the same scope.
function example() {
let x = 10;
if (true) {
let x = 20; // This creates a new 'x' in the inner block
}
console.log(x); // Outputs 10
}
const:
Variables declared with const are also block-scoped.
const variables must be initialized when declared, and their values cannot be
changed after initialization. They are used for defining constants.
You cannot reassign or redeclare a const variable within the same scope.
const pi = 3.14159;
pi = 3.14; // This will result in an error
Operators In Javascript
JavaScript has 8 types of operators that allow you to perform operations on values and
variables. Here are some common types of operators with examples:
Arithmetic Operators:
These operators perform basic mathematical operations.
let x = 10;
let y = 5;
Comparison Operators:
These operators compare two values and return a Boolean result.
let a = 5;
let b = 10;
Logical Operators:
These operators are used for logical operations and work with Boolean values.
let isTrue = true;
let isFalse = false;
Assignment Operators:
These operators assign values to variables.
let num = 10;
num += 5; // Equivalent to num = num + 5
num -= 3; // Equivalent to num = num - 3
num *= 2; // Equivalent to num = num * 2
num /= 4; // Equivalent to num = num / 4
switch Statement: The switch statement is used to select one of many code blocks to be
executed. It's often used when you have multiple conditions to check against a single value
let day = "Monday";
switch (day) {
case "Monday":
console.log("It's the start of the workweek.");
break;
case "Friday":
console.log("It's almost the weekend!");
break;
default:
console.log("It's an ordinary day.");
}
Ternary Operator: The ternary operator (? :) allows you to write a condensed form of an if-
else statement.
let isRaining = true;
let weather = isRaining ? "Take an umbrella" : "Enjoy the sunshine";
console.log(weather);
JAVASCRIPTS LOOPS:
For Loop
While Loop
Do…while Loop
For….in Loop
For…..of Loop
for Loop:
The for loop is used to execute a block of code a specified number of times.
for (let i = 0; i < 5; i++) {
console.log(i);
}
The for loop consists of three parts: initialization, condition, and iteration.
It's widely used for iterating over arrays, performing repetitive tasks, and counting
operations.
while Loop: The while loop is used to execute a block of code as long as a specified
condition is true.
let count = 0;
while (count < 5) {
console.log(count);
count++;
}
The condition is checked before each iteration, and the loop continues as long as the
condition is true.
It's used when you don't know in advance how many times the loop should run.
do...while Loop: The do...while loop is similar to the while loop, but it always executes the
block of code at least once, and then it continues as long as the condition is true.
let count = 0;
do {
console.log(count);
count++;
} while (count < 5);
The condition is checked after each iteration.
It's used when you want to ensure that a block of code is executed at least once.
for...in Loop: The for...in loop is used to iterate over the properties of an object.
const person = { name: "Alice", age: 30 };
for (let key in person) {
console.log(key + ": " + person[key]);
}
It's primarily used for iterating over the properties of objects, not for arrays.
Use it with caution, as it may also iterate over properties in the object's prototype
chain.
for...of Loop: The for...of loop is used to iterate over the values of iterable objects, such as
arrays and strings.
const fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
console.log(fruit);
}
Alert Box (alert): The alert box is used to display a simple message to the user. It only has an OK
button and is often used for informational purposes.
Prompt Box (prompt): The prompt box allows you to prompt the user for input. It displays a
message, an input field, and OK/Cancel buttons.
} else {
Confirm Box (confirm): The confirm box is used to get a yes/no response from the user. It displays a
message and OK/Cancel buttons.
let result = confirm("Are you sure you want to delete this item?");
if (result) {
alert("Item deleted.");
} else {
alert("Deletion canceled.");
JavaScript Events
Mouse events:
onmouseover: When the cursor of the mouse comes over the element
Keyboard events:
onkeydown & onkeyup: When the user press and then release the key
Form events:
onchange: When the user modifies or changes the value of a form element
Window/Document events:
onunload: When the visitor leaves the current webpage, the browser unloads it
writeln("string"): writes the given string on the doucment with newline character at the end.
getElementsByTagName(): returns all the elements having the given tag name.
getElementsByClassName(): returns all the elements having the given class name.
JAVASCRIPT ARRAY
1. By array literal
<script>
var emp=["Aditya","Vimal","Sumit"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
</script>
<script>
var i;
emp[0] = "Aditya";
emp[1] = "Vimal";
emp[2] = "Sumit";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
</script>
Here, you need to create instance of array by passing arguments in constructor so that we don't have
to provide value explicitly.
<script>
var emp=new Array("Aditya","Vimal","Sumit");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
1. push(): Adds one or more elements to the end of an array and returns the new length of the
array.
2. pop(): Removes the last element from an array and returns that element.
let arr = [1, 2, 3, 4]; let removed = arr.pop(); // arr is now [1, 2, 3], removed is 4
3. unshift(): Adds one or more elements to the beginning of an array and returns the new
length of the array.
4. shift(): Removes the first element from an array and returns that element.
let arr = [1, 2, 3, 4]; let removed = arr.shift(); // arr is now [2, 3, 4], removed is 1
let arr1 = [1, 2]; let arr2 = [3, 4]; let combined = arr1.concat(arr2); // combined is [1,
2, 3, 4]
let arr = [1, 2, 3, 4, 5]; let subArray = arr.slice(1, 4); // subArray is [2, 3, 4]
7. splice(): Changes the contents of an array by removing, replacing, or adding elements in-
place.
let arr = [1, 2, 3, 4, 5]; arr.splice(2, 1, 'a', 'b'); // arr is now [1, 2, 'a', 'b', 4, 5]
9. map(): Creates a new array with the results of calling a provided function on every element
in the array.
let arr = [1, 2, 3]; let doubled = arr.map((element) => element * 2); // doubled is [2,
4, 6]
10. filter(): Creates a new array with all elements that pass a provided test.
let arr = [1, 2, 3, 4, 5]; let evenNumbers = arr.filter((element) => element % 2 === 0); //
evenNumbers is [2,4]