JavaScript Notes
JavaScript Notes
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
prompt()
prompt(message)
prompt(message, defaultValue)
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
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 ().
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.
== (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):
5 !== 5; // false, because both the value and type are the same
!= (Inequality Operator):
the types.
5 != '5'; // false, because the string '5' is coerced into a number before
OR
• let cars = [
"Saab",
"Volvo",
"BMW"
];
Length & includes()
console.log(myArray.length); // Outputs: 5
in the array.
an array.
Here's an example:
let fruits = ["apple", "banana", "kiwi"];
fruits.push("orange");
fruits.pop();
Loops
• 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.
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 id = document.getElementById('header’);
• In case of tag and class, this function returns array instead of a element.
• document.querySelector(“h1”).style.color = “orange”;
• document.querySelector(“h1”).style.fontSize = “4rem”;
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-
• While textContent will only manipulate the text inside the tag.
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.
<script>
var element = document.getElementById("myBtn");
element.addEventListener("click", myFunction);
element.addEventListener("click", mySecondFunction);
</script>
.addEventListener()
<script>
var element = document.getElementById("myBtn");
element.addEventListener("click", function(parameter) {
myFunction(parameter.p); // calling myFunction
});
</script>
Example-
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...");
}
}
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.
switch (event.key) {
case ‘key’:
// do something;
break;
}
}
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.
child.className = ‘box’;
parend.appendChild(child);