Java Script
Alert() Method
• The alert() method in JavaScript is used to display a (warning)
message to the users. It displays an alert dialog box that
consists of some specified message (which is optional) and an
OK button. When the dialog box pops up, we have to click "OK"
to proceed.
• The alert dialog box takes the focus and forces the user to
read the specified message. So, we should avoid overusing
this method because it stops the user from accessing the
other parts of the webpage until the box is closed.
Syntax: alert("Hello! I am an alert box!!");
Data Types- typeof()
JavaScript has 8 Datatypes
• String.
• Number.
• Bigint.
• Boolean.
• Undefined.
• Null.
• Symbol.
• Object.
The typeof operator returns a string indicating the type of
the operand's value.
typeof()
typeof "John"; // Returns "string"
typeof 3.14; // Returns "number"
typeof NaN; // Returns "number"
typeof false; // Returns "boolean"
typeof [1,2,3,4] ; // Returns "object"
typeof {name:'John', age:34} ; // Returns "object"
typeof new Date(); // Returns "object"
typeof function () {} ; // Returns "function"
typeof myCar; // Returns "undefined" *
typeof null; // Returns "object“
The operand can be written inside () or directly.
Prompt() Method
prompt() instructs the browser to display a dialog with an
optional message prompting the user to input some text,
and to wait until the user either submits the text or cancels
the dialog.
Syntax
prompt()
prompt(message)
prompt(message, defaultValue)
Ex: prompt(“What is your name?”, “John Doe”);
Variable
JavaScript Variables can be declared in 4 ways:
• Automatically x = 5;
• Using var var x = 5;
• Using let let x = 5;
• Using const const x = 5;
Note
The var keyword was used in all JavaScript code from 1995 to 2015.
The let and const keywords were added to JavaScript in 2015.
The var keyword should only be used in code written for older browsers .
String
JavaScript strings are primitive and immutable: All
string methods produces a new string without altering
the original string.
Some important JavaScript string functions:
String.length
String concatenation
String.charAt(index) let text1 = "Hello";
let text2 = "World!";
String.slice(fromIndex, toIndex)
let text3 = text1+ " " + text2;
String.toUpperCase()
Using concat()-
String.toLowerCase() let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ",
String.concat() text2);
Console.log
The console.log() static method outputs a message to
the console. The message may be a single string (with
optional substitution values), or it may be any one or
more JavaScript objects.
Example:
console.log("Hello world!");
let a = 2;
console.log(a);
Functions in JS
A JavaScript function is defined with the function keyword, followed
by a name, then parentheses ().
Function names can contain letters, digits, underscores, and dollar
signs (same rules as variables).
The parentheses may include parameter names separated by
commas:
(parameter1, parameter2, ...) no data type is provided to
parameters.
Syntax:
function myFunction(para1, para2) {
return para1 * para2;
}
Math.floor();
The Math.floor() method rounds a number DOWN to the nearest
integer.
let x = Math.floor(1.6);
This will result 1. Math.floor() method will always result the
number that is before the decimal.
Math.random()
The Math.random() static method returns a floating-point,
pseudo-random number that's greater than or equal to 0 and less
than 1, with approximately uniform distribution over that range —
which you can then scale to your desired range.
let n = Math.random(); Range n >= 0 & n < 1.
if, else, and else if
• Same as in Java and C.
=== (Strict Equality Operator):
•It checks both value and type for equality.
5 === '5'; // false, because the types are different (number vs. string)
5 === 5; // true, because both the value and type are the same
== (Equality Operator):
•It checks only the value for equality, not considering the
types.
5 == '5'; // true, because the string '5' is coerced into a number before comparison
5 == 5; // true, because both values are the same
!== & !=
!== (Strict Inequality Operator):
•It checks both value and type for inequality.
5 !== '5'; // true, because the types are different (number vs. string)
5 !== 5; // false, because both the value and type are the same
!= (Inequality Operator):
•It checks only the value for inequality, not considering
the types.
5 != '5'; // false, because the string '5' is coerced into a number before
comparison, and the values are the same
Array Syntax
• let cars = []; //Declaring the array
• let cars = ["Saab", "Volvo", "BMW"]; //Decl & Initi..
• const cars = ["Saab", "Volvo", "BMW"];
OR
• let cars = [
"Saab",
"Volvo",
"BMW"
];
Length & includes()
• Array.length provides the size of the array.
const myArray = [1, 2, 3, 4, 5];
console.log(myArray.length); // Outputs: 5
• Array.includes(variable or value to be checked) is
useful for checking the presence of a specific value
in the array.
console.log(myArray.includes(3)); // Outputs: true
push() & pop() in Array
push() and pop() are two Array methods in
JavaScript. push() is used to add an element to the end of
an array, and pop() is used to remove the last element from
an array.
Here's an example:
let fruits = ["apple", "banana", "kiwi"];
console.log(fruits); // ["apple", "banana", "kiwi"]
fruits.push("orange");
console.log(fruits); // ["apple", "banana", "kiwi", "orange"]
fruits.pop();
Loops
There are types of loops:
• while loop: same syntax
• for loop: same syntax
• do-while: same syntax
• For-in
• for-of
Document
Object Model
(DoM)
DOM What?
• DOM is a programming interface for HTML(HyperText Markup
Language) and XML(Extensible markup language) documents. It
defines the logical structure of documents and the way a
document is accessed and manipulated.
• DOM is a way to represent the webpage in a structured hierarchical
way so that it will become easier for programmers and users to
glide through the document. With DOM, we can easily access and
manipulate tags, IDs, classes, Attributes, or Elements of HTML using
commands or methods provided by the Document object.
• Using DOM, the JavaScript gets access to HTML as well as CSS of
the web page and can also add behavior to the HTML elements. so
basically Document Object Model is an API that represents
and interacts with HTML or XML documents.
querySelector()
• The querySelector() method returns the first element that
matches a CSS selector.
• To return all matches (not only the first), use
the querySelectorAll()[index] instead.
• Both querySelector() and querySelectorAll() throw a
SYNTAX_ERR exception if the selector(s) is invalid.
Syntax-
document.querySelector("p");
Get the first element with class="example":
document.querySelector(".example");
document.querySelector(“li a"); //to select a specific
element within a hierarchy, known as combining
getElementBy
• var tag = document.getElementsByTagName('p’);
• var class = document.getElementsByClassName('item’);
• var id = document.getElementById('header’);
• In getElementBy, we use the name directly without using ., #. As the
selector is already specified in functions name.
• In case of tag and class, this function returns array instead of a element.
• In querySelector(), combining selectors can return an array as well.
.style Rules-
• To style the element using querySelector() or getElementBy(), we
use the style and property as a function with value in “” (string).
• By function, it means using . (dot) in it.
Syntax- Property value
• document.querySelector(“h1”).style.color = “orange”;
• document.querySelector(“h1”).style.fontSize = “4rem”;
• Instead of – in property (font-size), we use camel-casing
(fontSize).
classList property
The Element.classList is a read-only property that returns a live
DOMTokenList collection of the class attributes of the element.
This can then be used to manipulate the class list.
Although the classList property itself is read-only, you can modify
its associated DOMTokenList using the add(), remove(), replace(),
and toggle() (to add if removed or remove if added) methods.
Syntax: element.className.
Document.querySelector(“button”).classList.add/remove/
toggle(“invisible”);
• As the invisible class is defined, it’ll work same way in button
.textContent-
• textContent is kind of similar with innerHTML.
• The difference is that innerHTML provides the way to
manipulate inner html within a selected tag.
• While textContent will only manipulate the text inside the tag.
• <h1><strong>Hello</strong></h1> innerHTML can
manipulate the strong tag inside ‘h1’, making it <em>Good
Bye</em>.
• But textContent is limited to the text only (Hello).
get & setAttribute()-
• getAttribute() is used to get the value assigned to a particular attribute.
Its takes single input which is the attribute itself.
document.querySelector(‘a’).getAttribute(“href”); //return the link of google or etc.
• setAttribute() is used to set the value to a particular attribute. Its takes
two single input which is the attribute itself and the value to be
assigned.
document.querySelector(‘a’).setAttribute(“href”, “https//www.bink.com”); OR
document.querySelector(‘a’).setAttribute(“href”, variable);
.addEventListener()
The addEventListener() method of the EventTarget interface sets up a
function that will be called whenever the specified event is delivered to the
target.
• The addEventListener() method attaches an event handler to an
element without overwriting existing event handlers.
• You can add many event handlers to one element.
• You can add many event handlers of the same type to one element, i.e
two "click" events.
<script>
var element = document.getElementById("myBtn");
element.addEventListener("click", myFunction);
element.addEventListener("click", mySecondFunction);
</script>
.addEventListener()
In Event Listeners, We can add a function inside the
function(){ … }.
<script>
var element = document.getElementById("myBtn");
element.addEventListener("click", function(parameter) {
myFunction(parameter.p); // calling myFunction
});
</script>
.p is the object of parameter.
Audio.play();
• Create a variable of object Audio() and pass the path &
audio file as parameter.
• Then using play() function with variable, sound will be
played.
Example-
let audio = new Audio('sounds/crash.mp3');
audio.play();
Object Constructors
function HouseKeeper (name, age, skills, yearOfExperience){
this.name = name;
this.age = age;
this.skills = skills;
this.yearOfExperience = yearOfExperience;
this.cleaning = function() {
alert("Cleaning in progress...");
}
}
let houseKeeper1 = new HouseKeeper("Sara", 23, ["cleaning", "laundry",
"Cooking"], 3);
let houseKeeper2 = new HouseKeeper("Nita", 29, ["Cooking", "Gardening"],
5);
About this
In a constructor function this does not have a value. It is a substitute for the new
object. The value of this will become the new object when a new object is created.
• Within constructor there can exist a function with definition as well.
Keydown event
document.addEventListener("keydown", function(event) {
switch (event.key) {
case ‘key’:
// do something;
break;
}
}
The keydown event triggers when a key is pressed
down on the keyboard. It provides an event object
with details about the key press, including the pressed
key value (event.key).
Keydown event
Commonly used to capture and respond to key
presses globally in JavaScript applications, it's
often attached to the document or window. Unlike
other events, it doesn't work well with specific
selectors, typically requiring
document.addEventListener('keydown',
function(event) {...});.
setTimeOut()
The setTimeout() method calls a function after a number of
milliseconds.
1 second = 1000 milliseconds.
Notes
The setTimeout() is executed only once.
If you need repeated executions, use setInterval() instead.
<script>
const myTimeout = setTimeout(myGreeting, 5000);
function myGreeting() {
document.getElementById("demo").innerHTML = "Happy
Birthday!"
}
</script>
clearTimeOut()
Use the clearTimeout() method to prevent the function
from starting.
To clear a timeout, use the id returned from setTimeout():
<script>
const myTimeout = setTimeout(myGreeting, 5000);
//declared before
function myStopFunction() {
clearTimeout(myTimeout);
}
</script>
setInterval()
The setInterval() method calls a function at specified intervals
(in milliseconds).
The setInterval() method continues calling the function
until clearInterval() is called, or the window is closed.
1 second = 1000 milliseconds.
<script>
const element = document.getElementById("demo");
let myInterval = setInterval(function() {
element.innerHTML += "Hello“
}, 1000);
</script>
clearInterval()
The clearInterval() method clears a timer set with
the setInterval() method.
Note
To clear an interval, use the id returned from setInterval():
<script>
let myInterval = setInterval(function() {
element.innerHTML += "Hello“
}, 1000);
function myStop() {
clearInterval(myInterval);
}
</script>
appendChild()
The appendChild() method appends a node (element) as
the last child of an element.
let parent = document.querySelector(‘.container’);
let child = document.createElement(‘div’);
child.className = ‘box’;
parend.appendChild(child);
Append = add (something) to the end of a written document.