Javascript
Javascript
let variable_name;
Constant
User Input
With window.prompt
Type Conversion
String number to number
let A = '112';
let B = Number(A);
// B = 112
A = "";
B = Number(A);
// B = 0;
1
String to number
let a = "hello";
let b = Number(a);
// b = NaN
String to boolean
let A = "hello";
let b = Boolean(A);
// b = true
A = "";
b = Boolean(A);
// b = false
Functions
Define a function
1 Conditions
1.1 IF ELSE
if(condition)
{
actions
}
else
{
actions
}
2
1.2 Ternary operator
switch(variable)
{
case value:
actions
break
...
default:
actions
}
2 Strings
2.1 .length
get the length of string
2.2 .charAt(index)
get character in spesific index
2.3 .indexOf(”string”)
get index of first occurance of string
2.4 .lastIndexOf(”string”)
get index of last occurance of string
2.5 .trim()
remove white space from begening and end of string
2.6 .repeat(n)
repeat the string n times
3
2.7 syattsWith(”str”) — endsWith(”str”)
check if string ends pr starts with str
2.8 includes(str)
check if string includes the str
Arrays
Add value
2.10.1 At the end
array.push(value);
// or
array = [...array, value];
array.unshift(value);
Remove a value
2.10.3 From the ending
array.pop();
array.shift();
4
2.10.5 by index:
array.splice(index, number_of_elements_to_remove);
Map function
array.map(callback);
Filter function
array.filter(callback);
2.11 sort
we use it to sort array elements in alphabet lixicographic order (ex: 1,2,10 will
sorted as 1,10,2)
array.sort();
2.14 Descending
array.sort((a,b)=>{
return b.localeCompare(a);
});
array.sort((a,b)=>a-b);
5
2.17 Descending
array.sort((a,b)=>b-a);
3 slice(start, end)
take a substring or subarray of string or array if start or end are undefined, that
means we slice to the start or th end (like [0:] in python) we can use negative
indexes
4 Spread operator
The spread operator (...) allows an iterable (array or object pr string) to be
expanded in places where zero or more arguments or elements are expected.
In Arrays
Syntax:
function sum(a, b, c) {
return a + b + c;
}
let numbers = [1, 2, 3];
console.log(sum(...numbers)); // Output: 6
In Objects
Syntax:
6
let obj1 = {a: 1, b: 2};
let obj2 = {c: 3, d: 4};
let combined = {...obj1, ...obj2};
console.log(combined); // Output: {a: 1, b: 2, c: 3, d: 4}
function functionName(...restParameter) {
// function body
}
Example:
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
5 .forEach()
to iterate an array
a = [1,2,3,4]
a.forEach( (item)=>{
console.log(item);
});
// => 1,2,3,4
6 .filter()
to filter an array
7
a = [1,2,3,4]
a.filter( (item)=>{
return item%2==0;
});
// => [2, 4]
7 .map()
Applies function (callback) to each element of an array (it return new array)
a = [1,2,3,4]
a.map( (item)=>{
return item%2==0;
});
8 .reduce()
Reduce the elements of an array to a single value
a = [1,2,3,4]
a.reduce( (accumulator, item)=>{
return accumulator +|-|*|/|... item;
});
9 Objects
A collection of related properties and/or methods
o = {
p1: <value1>
p2: <value2>
.
.
.
method1: function()
{
8
.....
}
method2()
{
....
}
}
to acces property:
o.p1;
o.method1();
10 this
It reference to the object where THIS is used
• Function Context: this refers to the object the method is called on.
const obj = {
name: 'Alice',
greet: function() {
console.log(this.name);
}
};
function Person(name) {
this.name = name;
}
9
• Arrow Functions: this inherits from the parent scope at the time they
are defined.
const obj = {
name: 'Alice',
greet: function() {
const innerGreet = () => {
console.log(this.name);
};
innerGreet();
}
};
• Explicit Binding: this can be explicitly set using call, apply, and
bind.
function greet() {
console.log(this.name);
}
const obj = {
name: 'Alice'
};
function greet() {
'use strict';
console.log(this);
}
11 class
10
class Product
{
constructor(name, price)
{
this.name = name;
this.price = price;
}
displayProduct()
{
console.log(name+' '+price);
}
}
11.1 Inheritance
we use keyword extends, we can inheit parameters and methods.S
class A
{
name = 'a';
}
class B extends A
{
new B().name;
// => a
class A
{
constructor(age)
{
this.age = age;
}
}
set age(newAge)
{
11
if(age>0)
this._age = newAge;
else
console.error("age must be positive integer");
}
get age()
{
return this._age;
}
the underscroll age is naming covention means that this propertie is private.
class A
{
constructor(name)
{
this.name = name
}
function init()
{
....
}
}
class B extends A
{
contructor(name)
{
super(name);
super.init();
}
}
new B().name;
// => a
12
12 Destructuring
extract values from arrays and objects then assign them to a variables
12.1 Arrays
a=1;
b=2;
[b,a] = [a,b];
//a=2 b=1
12.2 Objects
we can destruct an object and set default values to each variable.
const person ={
name:"madjid",
age:26
}
f(person);
13
13 setTimout and setInterval
// to remove timout
clearTimout(id);
14 Error handling
we use try / catch to handle errors (finally will always get executed after
try/catch, we used generaly to close file, connections or release resources)
try
{
....
}
catch(error)
{
//console.error(error);
...
}
finally
{
....
}
15 DOM
DOM means Document Object Model
14
array = Array.from(<html collection>)
• .lastElementChild
• .nextElementSibling
• .previousElementSibling
• .parentElement
• .children //HTML collection
EX:
newElement.id = "id"
15
const elemnt = document.getElementById('element');
const parent = document.getElementById('parent');
parent.insertBefore(element, newElement);
parent.removeChild(element);
element.style.backgroundColor = "white"
16 classList
css class of element
element.classList.add("<class>");
element.classList.remove("<class>")
16.3 toogle
Remove class if present, add it if not.
element.classList.toogle("<class>")
16
16.4 replace
to replace exisitng class
16.5 contains
check if classList contains a class.
17 Events
17.1 add event listener to elemnt
element.addEventListenner(<event>, (event)=>{...})
Target
It’s the node element of target which the event was dispatched (it can be the
child of the element that contains onClick).
CurrentTarget
It’s the node element of target which the event was dispatched that contains
the onClick.
18 Promises
They are objects that manage asu=yncronious opertions
if(<true>)
resolve(<value>);
17
else
reject(<value>);
}).then((<resolved value>)=>{
... code
}).catch( <rejected value> => {
...code
});
EX
19 async / await
async make a function like a promise
await makes async function wait for a promise.
18
const rt2 = task2();
resolve(rt2);
});
20 JSON
JSON (JavaScript Object Notation) is data-iterchange format, used for ex-
changing data from server and web application.
it can be an array or object
21 fetch
fetch(<url>, [<options>]).then(
(response)=>{
retrun resoponse.json()
}
).then((data)=>{
//json data
})
19