Java Script
Java Script
Note
JAVASCRIPT Javascript is a programming language for website. It can manipulate both HTML
and CSS. It can perform logical checks, calculation, modify existing HTML & CSS
codes and more. It is the most popular programming language.
<SCRIPT> TAG The <script> Tag allow us to write JavaScript code inside of our HTML file.
<script>
[Link](“Hello World”);
</script>
[Link](“Hello World”);
[Link](“Hi”);
DEVELOPER Is a useful tool in debugging JavaScript codes also viewing our output using
TOOLS [Link]()
[Link] This code retrieves an element from our HTML using its ID and lets us manipulate
LEMENTBYID() its properties/attributes.
[Link](“some ID”);
VARIABLES Are temporary container that can hold different types of data such a text,
number, collections, object etc. Variables can be named for easy read/write
access by the programmer it is called an identifier.
Using var Uses the var keyword, it can be redeclared and should only used
when you want to support older browsers.
Ex.
var x = 5;
var y = 12.5;
var z = “Hello World”;
DATA TYPES the type of data that the variable is currently holding.
String, Number, Boolean, Undefined. Null, Object, Bigint, Symbol
//String
let name = "DarKLter";
//Number
let number = 5;
//Boolean
let isCoding = false;
//Undefined
let nickName;
//Null
let lastName = null;
"Hello" + "World";
"Answer : " + 12;
"PI : " + 3.14;
Numbers Operators
CONVERT STRING Unsuccessful conversions will result into a NaN (Not a Number) value.
TO NUMBER
//String to Integer
let num = parseInt("5");
//String to Decimal
let pi = parseFloat("3.14");
//Postfix
let x = 0;
[Link](x++); //Output: 0
[Link](x); //Output: 1
Strings
STRING .LENGTH .length is a property that gives the number of characters in a string.
STRING METHODS These different methods can manipulate strings in different ways
Method Usage Description
toUpperCase() [Link](); Turns string to
Uppercase
toLowerCAse() [Link](); Turns string to
Lowercase
trim() [Link](); Removes extra spaces
on start and end of a
string
trimEnd() [Link](); Removes extra space on
the end of a string
trimStart() [Link](); Removes extra spaces
on the start of a string
STRING METHODS These different methods can manipulate string in different ways
Method Usage Description
replace() [Link](from,to); Replaces first matching
word on a string
replaceAll() [Link](from,to); Replaces all matching
word on a string
slice() [Link](start,end); Get a part of a string by
specifying the start and
end index.
Common Use
Arrays
ARRAYS A variable that can store multiple values. The values inside an array is called an
element. The number where an element is located is called the index.
You can create any array with different datatypes.
//Array String
let names = ["DarKLter","KLter","Lesunter","DarkGwapo"];
//Array Number
let numbers = [1.99,2.50,300,450];
//Array Mixed Datatypes
let mixed = ["DarKLter",200,"Lesunter",50,"DarkGwapo"];
//Empty Array
let empty = [];
ARRAY LENGTH We can use the length property to get the length of an array.
READING ARRAY We need to specify the index in order to access a certain element value.
Syntax: identifier[index];
UPDATING ARRAY We need to specify the index in order to change / add a certain element value.
Syntax: identifier[index] = value;
[Link](names); //Output:
Dark,DarKLter,KLter,Lesunter,DarkGwapo,Karl,Lester
DELETING ARRAY There are many ways to Delete an element on the arrays.
length Change length to desired number.
Conditional Statements
ELSE STATEMENT Uses the ELSE keyword and {} it is used in combination with IF statement.
ELSE run when the IF comparison is false.
ELSE IF Uses the ELSE IF keyword and {} it is used in combination with the IF keyword if
STATEMENT you want additional specific conditions.
LOGICAL Are used in combination with conditional statement to create more complex
OPERATOR conditions. It Allow programmer to put 2 or more conditions in one expression.
&& AND
|| OR
! NOT
SWITCH Are used to execute code depending on a case. It acts like Conditional Statement
STATEMENT but can only check equality.
let level = 1;
switch(level){
case 1:
[Link]("Easy");
break;
case 2:
[Link]("Medium");
break;
case 3:
[Link]("Hard");
break;
}
//Output: Medium
BREAK KEYWORD break; is necessary after a case since it will let the program break out of the
switch statement. Without it the switch statement will continue running all code
blocks.
COMMON CASE You can specify two or more cases in a code block;
WHILE LOOP Is used to execute a block of code, while the condition is met/true.
let i = 0;
while(i < 5){
[Link]("Hello");
i++;
}//Output: Hello Hello Hello Hello Hello
ITERATE ARRAY You can use while loop to read through all the array elements.
BREAK KEYWORD You can use the break keyword to break out of a loop earlier than expected.
DO-WHILE LOOP Always runs the code once before checking the condition.
let w = 0;
do{
[Link]("Hello");
w++;
}while(w > 5); //Output: Hello
FOR LOOP Is used to execute a block of code, while the condition is met/true.
for(let i = 0;i < 5;i++){
[Link]("Hello");
}//Output: Hello Hello Hello Hello Hello
ITERATE ARRAY You can use while loop to read through all the array elements.
FOR LOOP & For loops are used when the number of iterations is known.
WHILE LOOP While loops are used when the number of iterations are unknown.
FOR / IN LOOP Are used for iterating over JSONs or Arrays. It returns the key or index pf each
item.
FOR / OF LOOP Are used for iterating over Arrays. It returns the value of each element.
let person ={
firstName: "Lesunter",
lastName: "KLter",
age: 21
};
JSON STRUCTURE A Json data should have a key | value pair and a colon ‘:’ in the middle.
Json should be surrounded by {}.
A Json can have multiple Json Data by using commas as separator.
A json can also have arrays as its value.
A json can also have JSON as its value.
let person = {
firstName: "Lesunter",
lastName: "KLter",
age: 21,
bloodType: "O",
sex: "M",
hobbies: ["Coding","Basketball","Sleeping"],
pets:{
1:{
name: "Shadow",
type: "Dog",
breed: "Shihtzu"
},
2:{
name: "Mocha",
type: "Cat",
breed: "Siamese"
}
}
};
JSON READ You can READ specific values of JSON by using the key surrounded by [].
You can READ specific values of JSON by using a period followed by the key. But
work only on a “String” key.
You can read array values in a JSON by using its key and accessing it normally by
index.
You can read JSON values in a JSON by using its key and accessing it normally by
key.
JSON WRITE You can UPDATE specific values of JSON by using its key surrounded by [] and
assigning a value to it. Or period followed by the key and assigning a value to it.
Assigning a value to a non-existent key will result into adding it.
person["firstName"] = "DarKLter";
[Link] = "KL";
[Link](person);
//Output: firstName: 'DarKLter' lastName: KL
person["middleName"] = "D";
[Link] ="Student";
[Link](person);
//Output: middleName: 'D' occupation: Student
JSON STRINGIFY You can convert JSON into string by using the [Link]() method.
JSON PARSING You can convert valid String into JSON by using the [Link]() method.
It a string is invalid it would throw an error at the console.
let a = `{"FirstName": "Lesunter", "LastName": "KLter",
"Age": 21, "BloodType": "O", "Sex": "M"}`;
let p = [Link](a);
[Link](p);
JSON ARRAY You can also create an Array of JSON. Which can be manipulated the same as any
other arrays.
JSON & FOR/IN We can use FOR/IN Loop to iterate over all the keys inside a JSON.
LOOP
let person = {
firstName: "DarKLter",
lastName: "KLter",
age: 21
}
for(let k in person){
[Link](`${k}: ${person[k]}`);
}
//Output: irstName: DarKLter lastName: KLter age: 21
index : HTML
<!DOCTYPE html>
<html>
<body>
<p id="text"></p>
</body>
<script src="[Link]"></script>
</html>
script : JavaScript
[Link]("Hello World");
//alert("Good Day");
//String
$name = "DarKLter";
[Link]("text").innerHTML = $name;
[Link]($name);
[Link]("Hi, " + $name);
//Concatenation
"Hello" + "World";
"Answer : " + 12;
"PI : " + 3.14;
//Number
let number = 5;
[Link](number);
number = 10;
[Link](number);
//Boolean
let isCoding = false;
//Undefined
let nickName;
//Null
let lastName = null;
//☠//
let name1 = "DarKLter";
let name2 = "Lesuna";
let w = "she";
let w1 = "coffee";
[Link](name2 + ", the friendly neighbor, waved at "+ name1 + "as " + w +
" walked by " + name1 + "'s house. " + name1 + " smiled back and invited " +
name2 + " in for a cup of " + w1 + "."); //Output: Lesuna, the friendly
neighbor, waved at DarKLter as she walked by DarKLter's house. DarKLter smiled
back and invited Lesuna in for a cup of coffee.
Number Operators
Example:
[Link](num1 + num2);
[Link](num2 + num3);
[Link](num1 + num1);
//Convertion
[Link](parseInt(num1) + num2);
num2 = 2.99;
num1 = "12.01";
num1 = parseFloat(num1);
[Link](num1 + num2);
//NaN
[Link](num2 + parseInt(num4));
//Arithmetic Operator
num2 = 5;
num3 = 2;
[Link](num2 + num3);
[Link](num2 - num3);
[Link](num2 * num3);
[Link](num2 / num3);
[Link](num2 ** num3);
[Link](num2 % num3);
//Prefix
let x = 0;
[Link](++x); //Output: 1
[Link](x); //Output: 1
//Postfix
let y = 0;
[Link](y++); //Output: 0
[Link](y); //Output: 1
//☠//
let math = 92;
let science = 91;
let computer = 89;
let mapeh = 92;
let english = 85;
//Shorthand
let name = " KLter ";
[Link]([Link]); //Output: 7
//.length
let word = "DarKLter";
let len = [Link];
[Link](len); //Output: 8
[Link](word[3]); //Output: K
[Link](word[[Link]-5]) //Output: K
word = [Link]();
[Link](word); //Output: DARKLTER
[Link]([Link]()); //Output: darklter
[Link]([Link]().length); //Output: 5
let num1 = 5;
let num2 = 3;
let sum = num1 + num2;
[Link](`${num1} + ${num2} = ${sum}`); //Output: 5 + 3 = 8
[Link](`${num1} + ${num2} = ${num1+num2}`); //Output: 5 + 3 = 8
//☠//
let name1 = "DarKLter";
let name2 = "Lesuna";
let w = "she";
let w1 = "coffee";
[Link](`${name2}, the friendly neighbor, waved at ${name1} as ${w} walked
by ${name1}'s house. ${name1} smiled back and invited ${name2} in for a cup of
${w1}.`); //Output: Lesuna, the friendly neighbor, waved at DarKLter as she
walked by DarKLter's house. DarKLter smiled back and invited Lesuna in for a
cup of coffee.
Array
Example:
//Array String
let names = ["DarKLter","KLter","Lesunter","DarkGwapo"];
//Array Number
let numbers = [1,2,3,4,5];
//Array Mixed Datatypes
var mixed =
["DarKLter","Dark",200,"Lesunter",50,"DarkGwapo",1000,"Kursoko",false,"Karl",2
5.50,"Lester"];
//Empty Array
let empty = [];
[Link]([Link]); //Output: 4
[Link](names[0]); //Output: DarKLter
[Link](names[[Link]-1]); //Output: DarkGwapo
names[0] = "Kursoko";
[Link](names[0]); //Output: Kursoko
//Adding DataTypes
numbers[5] = 6;
numbers[9] = 10;
names[[Link]] = "Karl";
[Link]("Lester");
[Link]("Dark");
//Deleting Array
[Link] = 7;
[Link](mixed); //Output: DarKLter,Dark,200,Lesunter,50,DarkGwapo,1000
[Link]();
[Link](mixed); //Output: DarKLter,Dark,200,Lesunter,50,DarkGwapo
[Link]();
[Link](mixed); //Output: Dark,200,Lesunter,50,DarkGwapo
//slice(start_index,end_index)
[Link](0,2);
[Link](mixed);
//☠//
let firstName = ["DarKLter","KLter","Lesunter"];
let codeName = ["A","B","C"];
let age = [18,19,20];
let index = 0;
[Link](`Index : ${index}`);
[Link](`First Name : ${firstName[index]}`);
[Link](`Code Name : ${codeName[index]}`);
[Link](`Age : ${age[index]}`);
Conditional Statement
Example;
//Comparison
let x = 5;
let y = 5;
[Link](x == y); //Output: true
[Link](x === y); //Output: true
[Link](x != y); //Output: false
[Link](x !== y ); //Output: false
//Conditional Statement
let age = 14;
if(age >= 18){
[Link]("Legal Age");
}else if(age <= 0){
[Link]("Invalid Age");
}else if(age > 0){
[Link]("Minor Age");
}else{
[Link]("Thank You!");
}//Output: Minor Age
//☠//
let math = 95;
let science = 91;
let computer = 95;
let mapeh = 98;
let english = 90;
if(!hasDegree){
[Link]("Good");
}else{
[Link]("Bad");
}
//Output: Bad
[Link]("You're Hired");
}
else [Link]("Need More Experience.");
if(isRegistered){
if(ages >= 18) [Link]("Valif Voter");
else [Link]("Invalid Voter");
}else{
if(ages >= 18) [Link]("Registered First");
else [Link]("Non Voter");
}
//Output: Non Voter
let level = 2;
switch(level){
case 1:
[Link]("Easy");
break;
case 2:
[Link]("Medium");
break;
case 3:
[Link]("Hard");
break;
default:
[Link]("Invalid");
break;
}//Output: Medium
switch(level){
case 1:
case 3:
[Link]("Easy");
break;
case 2:
case 4:
[Link]("Medium");
break;
case 3:
case 6:
[Link]("Hard");
break;
default:
[Link]("Invalid");
break;
}//Output: Medium && Medium
switch(letter){
case "a":
case "A":
[Link]("Apple");
break;
case "b":
case "B":
[Link]("Ball");
break;
default:
[Link]("Unknown");
break;
}//Output: Apple
//☠//
let day = 5;
switch(day){
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
default:
[Link]("Invalid");
break;
}//Output: Friday
While Do-While Loop Break
Keyword
Example;
let i = 0;
while(names[n]){
[Link](names[n]);
n++;
while(names[n]){
if(names[n] === s){
[Link](names[n]);
break;
}
n++;
}//Output: Lesunter
let w = 0;
do{
[Link]("Hello");
w++;
}while(w > 5); //Output: Hello
//☠//
let array = [5,5,5,5,5,];
let sum = 0;
let r = 0;
while(array[r]){
sum += array[r];
r++;
}
[Link](sum); //Output: 25
For Loop In Of Break Keyword
Example;
for(let i in names){
[Link](i);
}//Output: 0 1 2 3
for(let x in names){
[Link](`${parseInt(x)+1}. ${names[x]}`);
}//Output: 1. DarKLter 2. KLter 3. Lesunter 4. Dark
for(let i of names){
[Link](i);
}//Output: DarKLter KLter Lesunter Dark
let i = 1;
for(let x of names){
[Link](`${i}. ${x}`);
i++;
}//Output: 1. DarKLter 2. KLter 3. Lesunter 4. Dark
//☠//
let people = ["DarKLter","KLter","Lesunter","Dark"];
let s = "LesUnter";
let isFound = false;
for(let z in people){
if(people[z].toLowerCase() === [Link]()){
isFound = true;
[Link](`Found ${people[z]}`);
break;
}
}
if(!isFound) [Link]("Not Found");//Output: Found Lesunter
let person = {
firstName: "Lesunter",
lastName: "KLter",
age: 21,
bloodType: "O",
sex: "M",
hobbies: ["Coding","Basketball","Sleeping"],
pets:{
1:{
name: "Shadow",
type: "Dog",
breed: "Shihtzu"
},
2:{
name: "Mocha",
type: "Cat",
breed: "Siamese"
}
}
};
[Link](person);
[Link](person["firstName"]); //Output: Lesunter
[Link]([Link]); //Output: Lesunter
[Link](person["hobbies"][2]); //Output: Sleeping
let pet = [
{
name: "Shadow",
type: "Dog",
breed: "Shihtzu"
},{
name: "Mocha",
type: "Cat",
breed: "Siamese"
},{
name: "Dark",
type: "Bird",
breed: "Dragon"
}
];
[Link](pet[0].name); //Output: Shadow
[Link](`${pet[0].name} ${pet[0].breed}`); //Output: Shadow Shihtzu
//☠//
for(let i = 0; i < [Link];i++){
[Link]();
[Link](`Name : ${pet[i].name}`);
[Link](`Type : ${pet[i].type}`);
[Link](`Breed : ${pet[i].breed}`);
[Link]();
}
JSON For-In Loop
Example:
let person = {
firstName: "DarKLter",
lastName: "KLter",
age: 21
}
for(let k in person){
[Link](`${k}: ${person[k]}`); //Output: irstName: DarKLter lastName:
KLter age: 21
}
let a = [Link](person);
[Link](a); //Output: [ 'firstName', 'lastName', 'age' ]
let b = [Link](person).length;
[Link](b); //Output: 3
[Link]();
//☠//
let grades = {
math: 92,
science: 91,
computer: 89,
mapeh: 92,
english: 85
}
let average = 0;
for(let k in grades){
[Link](`${k} : ${grades[k]}`);
average += grades[k];
}
average /= [Link](grades).length;
[Link]();
[Link](`Average : ${average}`);