- Any function may not belongs to any object. But in JavaScript there is always a default global object. This global object is
window
object. Any global myFunction()
and window.myFunction()
is the same function.
- == vs ===
== compares only value but === compares value and type.
- () operator:
() operator is used to invoke the function. For example, myFunction()
returns the result but myFunction
returns the function definition.
- A variable declared without a value will have a value
undefined
. A variable without declaration will have a value undefined
. And a variable can be emptied by setting the value to undefined
.car = undefined
Here, typeof car
will be undefined
. typeof undefined
will be undefined
. Unfortunately, data type of null
is an object
. It should be null
. undefined
and null
are equal in value but different in type.
null === undefined //false
null == undefined //true
- When adding number and string, JavaScript will treat the number as a string. ie.
x = 2+3+"5" //x contains 55 as string.
x = x + 2 //x contains 552
JavaScript evaluates expression from left to right. That is
x = 16+4+"Volvo" //x contains 20Volvo as string
x = "Volvo"+16+4 //x contains Volvo164 as string
But JS converts string to number in other arithmetic operations(-, /, *). During comparison operators (<, >, ==) at least one operand should be number (Other can be number in string format)
x = "100"/10 //x contains 10 as number
NaN = not a number
x = 10/"Apple" //x contains NaN
typeof NaN //will be number
typeof Infinity //will be number
Case
|
Value
|
2 < 12
|
true
|
2 < "12"
|
true
|
2 < "John"
|
false
|
2 > "John"
|
false
|
2 == "John"
|
false
|
"2" < "12"
|
false
|
"2" > "12"
|
true
|
"2" == "12"
|
false
|
Switch statement: If you omit the break statement, the next case will be executed even if the evaluation does not match the case. The default keyword specifies the code to run if there is no case match. The default case does not have to be the last case in a switch block. If no match, default will be executed even if it is at the top. Top default should be finished with a break. If multiple cases matches a case value, the first case is selected.
In for loop, initialization, condition, increment - all three statement are optional. If the condition is omitted, then the condition is always true. This does not mean null or empty in condition means true.
Unary + operator for casting:
let y = "5"; let x = + y;
- Automatic Type conversion: link
5 + null "5" + null "5" + 2 "5" - 2 "5" * "2" - If a variable inside a function is not declared with
var
it will be treated as a global variable. It you re-declare (as many times as you want) a JavaScript variable it will not lose its value. Parameter to a function is similar to the local function of that function.myFunction(5);
function myFunction(x) {
var x, y;
y = x; //y contains 5
}
In JavaScript functions parameter does not have a fixed limit. If any parameter is not passed during invocation, it will be undefined. If the parameter is over than definition then it will be passed into the function.
Hoisting (Hoist = উত্তোলন করা): Hoisting JavaScript’s default behavior of moving all declaration to the top of the current scope.
<script>
var carname = 1;
console.log(carname); //1
change(); //2
console.log(carname); //1
function change() {
var carname;
carname = 2;
console.log(carname);
}
</script>
<script>
var carname = 1;
console.log(carname); //1
change(); //2
console.log(carname); //1
function change() {
carname = 2;
console.log(carname);
var carname;
}
</script>
<script>
var carname = 1;
console.log(carname); //1
change(); //undefined
console.log(carname); //1
function change() {
console.log(carname);
var carname = 2;
}
</script>
- let: Variable defined with
let
cannot be redeclared and must be declared before using. Variable defined with let
, are also hoisted but not initialized meaning program is aware of their declaration but generates error if used before declaration. - const: Variable defined with
const
cannot be redeclared and must be declared before using. Variable defined with const
, must be assigned a value during declaration. The keyword const
is a little misleading. It does not define a constant value. It defines a constant reference to a value. Because of that you cannot reassign value, object, array but you can change index of array and property of object. - The
delete
operator is designed to be used on object properties. It has no effect on variables or functions.
- All JavaScript objects inherit properties and methods from a
prototype
.The Object.prototype is on the top of the prototype inheritance chain:Date objects, Array objects, and Person objects inherit from Object.prototype. The delete
keyword does not delete inherited properties, but if you delete a prototype property, it will affect all objects inherited from the prototype.
- In property declaration
this
refers to “this object”. In a function definition, this refers to the “owner” of the function.
- In a method, this refers to the owner object.
- Alone, this refers to the global object.
- In a function, this refers to the global object.
- In a function, in strict mode, this is undefined.
- In an event, this refers to the element that received the event.
- Methods like call(), and apply() can refer this to any object.
LinkIn regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever.
With arrow functions, the this keyword always represents the object that defined the arrow function.
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
[] can be used to access any index of string.
- It makes strings look like arrays (but they are not)
- If no character is found, [ ] returns undefined, while charAt() returns an empty string.
- It is read only. str[0] = "A" gives no error (but does not work!)
Comparing two JavaScript objects always returns false. "Hi" is a string but new String("Hi") is a object.
- A function defined as the property of an object, is called a method to the object.
A function designed to create new objects, is called an object constructor.
- Two way to create function:
- {} parameter
- Object constructor function: A function will behave as object when we instantiate this function with a new keyword.
- Object constructor function: The following types definition is called object constructor function (Blueprints) (Classes):
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Basically, object constructor function and function are same until we do not create instance with a new
keyword. this
keyword will be available when we create object with new
keyword.
- Objects and Arrays are passed by reference:
In JavaScript, Objects and Arrays are passed by reference (Outside object এর সাথে লিংক আছে): typeof arrayVar shows object but this object contains array properties and methods. If a function changes an object property, it changes the original value.Changes to object properties are visible (reflected) outside the function. Other data (Primitive) are passed by value. This topic will be explained later in this tutorial.
- Did You Know?
As you can see above, JavaScript has object versions of the primitive data types String, Number, and Boolean. But there is no reason to create complex objects. Primitive values are much faster.ALSO:
- Use object literals {} instead of new Object().
- Use string literals “” instead of new String().
- Use number literals 12345 instead of new Number().
- Use boolean literals true / false instead of new Boolean().
- Use array literals [] instead of new Array().
- Use pattern literals /()/ instead of new RegExp().
- Use function expressions () {} instead of new Function().
- If you use named indexes (ie. myArr["index"]), JavaScript will redefine the array to an object. This object will not contain array properties. In JavaScript, arrays use numbered indexes and objects use named indexes.
- JavaScript does not support associative arrays.
- You should use objects when you want the element names to be strings (text).
- You should use arrays when you want the element names to be numbers.
- JavaScript functions:
- General form:
function myFunction(a, b) {
return a * b;
}
- Anonymous function (a function without a name):
var x = function (a, b) {return a * b};
- Self-Invoking function:
Function expressions will execute automatically if the expression is followed by ().You cannot self-invoke a function declaration.You have to add parentheses around the function to indicate that it is a function expression. Example:
(function () {
var x = "Hello!!"; // I will invoke myself
})();
The function above is actually an anonymous self-invoking function (function without name).
(function (x) {
delete x; //no effect
var x, y;
y = x; //y contains 1
})(1);
- Arrow function:
Arrow functions allows a short syntax for writing function expressions.
const x = (x, y) => x * y;
const x = (x, y) => { return x * y };
They are not well suited for defining object methods.Arrow functions are not hoisted. They must be defined before they are used.Using const is safer than using var, because a function expression is always constant value.You can only omit the return keyword and the curly brackets if the function is a single statement. Because of this, it might be a good habit to always keep them
- Closure function:
A closure is a function having access to the parent scope, even after the parent function has closed. ভেরিয়েবলের লাইফটাইম ঐ ফাংশনের মধ্যে সীমাবদ্ধ থাকে। কিন্তু ক্লোজার এর ক্ষেত্রে লাইফটাইম শেষ হয় না।
Closure is best suitable for counter function:
var add = (function () {
var counter = 0;
return function () {counter += 1; return counter}
})();
add();
add();
add();
// the counter is now 3
Math.random()
returns a random number between 0 (inclusive), and 1 (exclusive). Following program (Both inclusive):
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}- Arrow function:
- hello = function() {
return "Hello World!";
} - hello = () => {
return "Hello World!";
} - hello = () => "Hello World!"; // Arrow function returns value by default; without bracket > only one statement
- hello = (val) => "Hello " + val;
- hello = val => "Hello " + val; //for parameter
Passed by Reference vs Passed by value
- Passed by Reference > Changes outside.
- Passed by Value > Do not change outside.
- When we pass an argument to a JavaScript function by reference, any change inside function will reflect to the outside. That means, outside variable will be changed.
- When we pass an argument to a JavaScript function by value, any change inside function will not reflect to the outside. That means, outside variable will be changed.
There is a controversy of JavaScript parameter passing.
- Always passed by value
- Always passed by reference
- Primitive variables are passed by value but objects ( and array ) are passed by Reference.
Maybe, all of the controversy depends on their thinking. Remember:
When we assign data to a variable or property, this variable or property get created newly with a new address.
Example-1:
let a = 1;function change(x) { x=2; return x;}console.log(change(a));
Outputs: 2
Example-2:
let a = {name:"Rejaul"};function change(x) { x.name = "Karim"; return x;}console.log(change(a));
Outputs: {name: "Karim"}
Example-3:
let a = {name:"Rejaul"};function change(x) { x = {}; /* Fully assigned. New object within this scope.*/ return x;}console.log(change(a));
Outputs: {}
In case of property, It gets created newly under the parent object but the parent object will not be created newly. Parent object will have the Same address. Parent object will contain new address, when a new object is assigned to it.
HTML DOM
DOM = Document Object Model
The DOM defines a standard for accessing documents. DOM is the programming interface. Here, we will learn HTML DOM.
document.getElementById("demo").innerHTML = "Hello World!";
document
is the obejct, getElementById
is a method, while innerHTML
is a property.
document
is a global object under window. document contains the HTML code as object. This code is HTML DOM. The HTML DOM document
object is the owner of all other objects in your web page.
- timer function:
var id = setInterval(frame, 5);
clearInterval(id); //You call it with a condition
element.addEventListener("click", function(){ alert("Hello World!"); });
Bubble up & Capturing
e.target>>Bubble up (Innter most element)
e.currentTarget>>Capturing (outer which contains the class, id selector)
JavaScript template literals ${}: (notice ` not ')
Example:
let a = 5;
let b = 10;
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);
// "Fifteen is 15 and
// not 20.
When you place ${ }
inside quotation, code inside curly brace will be treated as javascript.
Few Array functions
-
filter():Used for deleting an item but cannot modify an item(ie. 1 to 8)
delteTask(id) {
this.tasks = this.tasks.filter((task) => task.id !== id);
}
-
map():Used to modify items but cannot delete an item
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
To change the reminder
property of task object:
toggleReminder(id) {
this.tasks = this.tasks.map(task=>task.id===id?{...task, reminder: !task.reminder}:task)})
}
-
Add/Remove
- pop(): Remove an item from the end of an array.
- push(): Add items to the end of an array.
- shift(): Remove an item from the beginning of an array.
- unshift(): Add items to the beginning of an array.
- [...x, 1]: Add 1 to the end of array x.
- Example 1:
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b}); //[1,5,10,25,40,100]
Example 2:
const cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}
];
cars.sort(function(a, b){return a.year - b.year});
Note: You can find the highest and lowest value from this sorted array easily. - Use of forEach method:
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value, index, array) {
txt += value + "<br>";
} - Reduce method: The
reduce()
method runs a function on each array element to produce (reduce it to) a single value. If the initial value is not defined then here total will automatically be initialized by 0.
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction);
function myFunction(total, value) {
return total + value;
} - The
find()
method returns the value of the first array element that passes a test function. (See findIndex() too)
const numbers = [4, 9, 16, 25, 29];
let first = numbers.find(myFunction);
function myFunction(value, index, array) {
return value > 18;
} - Modules: 1. w3schools 2. javascript.info
-
function deleteTask(task) {
let index = state.todos.indexOf(task);
state.todos.splice(index, 1); //Removes 1 element at the specified index.
}
Promise
A Promise is a JavaScript object that links producing code and consuming code. Syntax:
let myPromise = new Promise(function(myResolve, myReject) {
setTimeout(function() { myResolve("I love You !!"); }, 3000); //Producing code
});
myPromise.then(function(value) { //this then contains myResolve function as parameter
document.getElementById("demo").innerHTML = value; //Consuming code
});
- The two arguments (resolve and reject) are pre-defined by JavaScript.
- Very often we will not need a reject function like:
promise.then();
- Instead of reject function developers sometimes uses catch like:
promise.then().catch();
async/await
You cannot use await
without an async
function. The await
keyword is used to pause the execution of an asynchronous function until a promise is resolved or rejected. await
allows you to write asynchronous code in a more synchronous and readable manner.
function wait(t) {
return new Promise(resolve => {
setTimeout(()=> {resolve(); console.log("Happy Birthday");}, t); //You must call resolve method
});
}
async function halt(t) {
console.log("Before");
await wait(t); //Halt execution here
console.log("No time");
}
wait(3000); //Does not halt execution
halt(2000);
Intersection Observer
Executes a function when an element is visible on scroll. Look at the function below:
public observeElementOnce(element: HTMLElement, callback: () => void) {
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
callback();
observer.unobserve(entry.target);
}
});
});
observer.observe(element);
}
Now execute it
this.observeElementOnce(element, () => {
//Element is visible
});
Fetch
fetch("/wp-json/wp/v2/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-WP-Nonnce": myData.nonce
},
body: JSON.stringify({
title: "Post title",
content: "Sample content",
status: "publish"
})
));
height vs scrollHeight
height represents the height of an element's content area. The scrollHeight property represents the total height of an element's content, including content that is not visible due to overflow. If a parent element has a height of 0, but its child element has a non-zero height (let's call it x), then the scrollHeight property of the parent element will indeed be equal to x.
Next tick in JS
setTimeout(() => {
// some code
}, 0);
Labels: JavaScript, Web development