VS
</>
1. var variables can be updated and re-declared; let variables can be updated but not re-declared; const variables can neither be updated nor re-declared.
2. var and let can be declared without being initialized, const must be initialized during declaration.
3. var is function scoped, while let and const are block scoped.
function fun() {
if (true) {
var x = 0;
}
for (let i = 0; i < 10; i++) x++;
console.log(x); // 10
}
fun();
console.log(x); // Error: x is not defined
function fun() {
if (true) {
let x = 0;
}
for (let i = 0; i < 10; i++) x++;
console.log(x); // Error: Uncaught ReferenceError: x is not defined
}
fun();
`var`s and `function`s are hoisted.
console.log(x === undefined); // true
var x = 3;
let x = sum(1, 2);
function sum(a, b) {
return a + b;
}
console.log(x); // 3
var x;
console.log(x === undefined); // true
x = 3;
same as
let and const hoisting is a special case named the "temporal dead zone".
To keep it simple, let's consider them not hoistable.
For reliable and traceable code, avoid using var. Instead use let and const.
JavaScript has eight data types:
RegExp
Map
In JavaScript, functions are first-class objects, because they can be passed to other functions, returned from functions, and assigned to variables and properties. They can also have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called.
JavaScript also has some special object data types:
function sum() {
return sum.a + sum.b;
}
sum.a = 1;
sum.b = 2;
sum(); // returns 3
console.log(Boolean(true)); // true
console.log(Boolean(1)); // true
console.log(Boolean(' ')); // true
console.log(Boolean([])); // true
console.log(Boolean({})); // true
console.log(Boolean(function () {})); // true
Truthy:
console.log(!!false); // false
console.log(!!0); // false
console.log(!!''); // false
console.log(!!null); // false
console.log(!!undefined); // false
console.log(!!NaN); // false
False:
let a = 1,
b = '1';
console.log(a == b); // true
console.log(a === b); // false
const firstName = 'John',
lastName = 'Doe';
const plusConcat = 'Hi 👋🏽, My name is ' + firstName + ' ' + lastName + '.';
const templateLiteralConcat = `Hi 👋🏽, My name is ${firstName} ${lastName}.`;
const notANumber = 'Not a number';
console.log(Number.isNaN(notANumber)); // false
console.log(Number.isNaN(Number(notANumber))); // true
const num = 1_000_000;
console.log(Number.isNaN(+num)); // false
// Traditional function fxpression
function add1(a, b) {
return a + b;
}
// Arrow function
const add2 = (a, b) => {
return a + b;
};
// One-line arrow function
const add3 = (a, b) => a + b;
const arr = [1, 2, 3, 4, 5];
arr.length = 3;
console.log(arr); // [1, 2, 3]
arr.length = 0;
console.log(arr); // []
Use lenght to empty an array:
Filter array:
const arr = [0, 1, '', ' ', null, undefined, NaN, {}, []];
const filteredArr = arr.filter((val) => !!val);
Map:
const numbers = [1, 2, 3];
const squared = numbers.map((num) => num * num); // [1, 4, 9]
forEach:
const fruits = ['apple', 'banana', 'orange'];
fruits.forEach((fruit, index) => console.log(`fruit at "${index}": ${fruit}`));
let numbers = [1, 2, 3, 4, 5];
// slice
const slicedArr = numbers.slice(1, 4);
console.log(slicedArr); // [2, 3, 4]
console.log(numbers); // [1, 2, 3, 4, 5]
// splice
const splicedArr = numbers.splice(1, 3);
console.log(splicedArr); // [2, 3, 4]
console.log(numbers); // [1, 5]
numbers = [1, 2, 3, 4, 5];
const splicedArr2 = numbers.splice(1, 3, 6, 7, 8);
console.log(splicedArr2); // [2, 3, 4]
console.log(numbers); // [1, 6, 7, 8, 5]
Slice extracts a copy, while splice delete from the array, and event adds to it if you want to.
let list = [4, 5, 6];
const obj = { x: 1, y: 2, z: 3 };
for (let i in list) console.log(i); // "0", "1", "2",
for (let i in obj) console.log(i); // "x", "y", "z"
for (let i of list) console.log(i); // "4", "5", "6"
for (let i of obj) console.log(i); // TypeError: obj is not iterable
`for...in` iterates over all enumerable property keys of an object.
`for...of` iterates over the values of an iterable object.
const person = { name: 'John Doe', age: 30, gender: 'male' };
// Traditional way
const name = person.name,
age = person.age,
gender = person.gender;
// With destructuring
const { name, age, gender } = person;
Objects:
const fruits = ['Apple', 'Banana', 'Orange'];
// Traditional way
const firstFruit = fruits[0],
secondFruit = fruits[1],
thirdFruit = fruits[2];
// Destructing
const [firstFruit, secondFruit, thirdFruit] = fruits;
Arrays:
const person = { name: 'John Doe', gender: 'male' };
const { name, age = 18, gender } = person;
Objects:
const fruits = ['Apple', 'Banana'];
const [firstFruit, secondFruit, thirdFruit = 'Orange'] = fruits;
Arrays:
Destrucurting with default values works with undefined values only, null is not included.
const originalArray = [1, 2, 3];
const copiedArray = [...originalArray];
console.log(copiedArray); // [1, 2, 3]
const arr1 = [1, 2, 3],
arr2 = [4, 5, 6];
const mergedArr1 = arr1.concat(arr2),
mergedArr2 = [...arr1, ...arr2];
console.log(mergedArr2); // [1, 2, 3, 4, 5, 6]
console.log(mergedArr1); // [1, 2, 3, 4, 5, 6]
Merging arrays with spreading:
const originalObject = {
name: 'John',
isFootballFan: true,
club: 'Chelsea',
};
// clone with Object.assign()
const clonedObject1 = Object.assign({}, originalObject),
// clone with spread operator
clonedObject2 = { ...originalObject };
const originalObject = {
name: 'John',
isFootballFan: true,
club: 'Chelsea',
};
// Deep cloning with JSON.stringify() and JSON.parse()
const deepCloned1 = JSON.parse(JSON.stringify(originalObject)),
// You can also create a deep clone of an object with the `structuredClone()`.
// `structuredClone()` was added to the JavaScript language in ECMAScript 2019.
deepCloned2 = structuredClone(originalObject);
const user = { name: { first: 'John' } };
user.address.house; // TypeError: Cannot read property 'house' of undefined
user.address?.house; // undefined
const getFee = (isMember) => isMember ? '1 EGP' : '10 EGP';
getFee(true); // "1 EGP"
getFee(false); // "10 EGP"
getFee(null); // "10 EGP"
let x = 2,
b = '2';
console.log(x + b); // "22"
console.log(x - b); // 0
console.log(x * b); // 4
console.log(x / b); // 1
console.log(typeof 1); // "number"
console.log(typeof '1'); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object"
console.log(typeof []); // "object"
console.log(typeof {}); // "object"
console.log(typeof function () {}); // "function"
console.log(typeof (() => {})); // "function"
console.log(typeof NaN); // "number"
console.log(typeof Symbol()); // "symbol"
[1, 2, 3] + '4'; // '1,2,34'
0.1 * 0.2; // 0.020000000000000004
5.3 / 0.1; // 52.99999999999999
</>
</>
1. By tag name ex: <p>
myElements = $("p");
JQuery
JavaScript
myElements = document.getElementsByTagName("p");
2. By class name ex: class="intro"
myElements = $(".intro");
JQuery
JavaScript
myElements = document.getElementsByClassName("intro");
Ways to query an element in JQuery Vs JS
3. By id ex: id="id01"
myElement = $("#id01");
JQuery
JavaScript
myElement = document.getElementById("id01");
4. By CSS Selectors ex: class="intro"
myElements = $("p.intro");
//Adjecent sibling selector
myElements = $("p + .intro");
//Direct child selector
myElements = $("p > .intro");
JQuery
JavaScript
myElements = document.querySelectorAll("p.intro");
//Adjecent sibling selector
myElements = document.querySelectorAll("p + .intro");
//Direct child selector
myElements = document.querySelectorAll("p > .intro");
Ways to query an element in JQuery Vs JS
5. Select a Single element
N/A
JQuery
JavaScript
myElement = document.querySelector(".intro");
1. Create an element
const txt2 = $("<p></p>").text("Text"); // Create with jQuery
JQuery
JavaScript
const txt3 = document.createElement("p");
txt3.innerHTML = "Text";
2. Add an element to the DOM
//Inserts content AT THE END of
//the selected HTML elements.
$("p").append("Some appended text.");
// Does the same job but in reverse
$("<div />").appendTo("body");
JQuery
JavaScript
const txt3 = document.createElement("p");
txt3.innerHTML = "Text";
//Doesn't return the appended node
Element.append(txt3);
// Returns the appended node,
// Can only append 1 node
const child = Element.appendChild(txt3);
Elmement.insertAdjacentElement("beforeend", txt3);
Element.inserAdjacentHTML("beforeend", string to be parsed);
2. Add an element to the DOM
//Inserts content AT THE START of
//the selected HTML elements.
$("p").prepend("Some appended text.");
JQuery
JavaScript
const txt3 = document.createElement("p");
txt3.innerHTML = "Text";
//Doesn't return the appended node
Element.prepend(txt3);
Elmement.insertAdjacentElement("afterbegin", txt3);
Element.inserAdjacentHTML("afterbegin", string to be parsed);
2. Add an element to the DOM
//Inserts content BEFORE of
//the selected HTML elements.
$("img").before("Some text after");
JQuery
JavaScript
Elmement.insertAdjacentElement("beforebegin", txt3);
Element.inserAdjacentHTML("beforebegin", string to be parsed);
2. Add an element to the DOM
//Inserts content AFTER of
//the selected HTML elements.
$("img").after("Some text after");
JQuery
JavaScript
Elmement.insertAdjacentElement("afterend", txt3);
Element.inserAdjacentHTML("afterend", string to be parsed);
3. Replace an element in the DOM
//Accepts multiply Strings, nodes
$("div.second").replaceWith("<h2>New heading</h2>");
JQuery
JavaScript
//Accepts multiply strings or nodes
p.replaceWith(span);
4. remove an element from the DOM
$("#div1").remove();
JQuery
JavaScript
document.querySelector("#div1").remove();
1. Add a class name to an element
//Adds one or more class names
$("p").addClass("intro");
JQuery
JavaScript
//Adds one or more class names
div.classList.add("intro");
2. Remove class name from an element
//Removes one or more class names
$("p").removeClass("intro");
JQuery
JavaScript
//Removes one or more class names
div.classList.remove("intro");
3. Replace a class name in an element
//replace one class name
$('.blue').removeClass('oldClass').addClass('newClass');
JQuery
JavaScript
//replaces one class name with another one
//returns a boolean
div.classList.replace("oldClass", "newClass");
4. Toggle a class name in an element
//toggle one or more classes
$("p").toggleClass("main");
JQuery
JavaScript
//adds or removes a class
//returns a boolean
div.classList.toggle("main");
1. requestAnimationFrame
N/A
JQuery
JavaScript
const requestID = window.requestAnimationFrame(callback);
//Request Cancelation
window.cancelAnimationFrame(requestID);
2. Animate
//By default, all HTML elements have a static position, and cannot be moved.
//To manipulate the position, remember to first set the CSS position property of the element
//to relative, fixed, or absolute!
$("div").animate({left: '250px'}, 1000, callback);
JQuery
JavaScript
Element.animate(keyframes, options)
// keyframes: Either an array of keyframe objects,
// or a keyframe object whose properties are arrays of values to iterate over.
//
// options: Either an integer representing the animation's duration (in milliseconds),
// or an Object containing one or more timing properties and/or options
Example: W3Schools Tryit Editor
1. add Events listeners
$("div").event(callback);
$("div").on("event", callback);
//example:
$("p").click(function(){
//code
});
$( "#bind" ).on( "click", function() {
//code
});
JQuery
JavaScript
Element.addEventListener(type, listener, options)
//example:
document.addEventListener("click",(e)=>{
//code
})
document.onClick = (e)=>{
//code
};
2. Remove Events listeners
//Removes all event handlers from the element
$( "p" ).off()
//Removes a click listener
//foo needs to be the same function that was passed to .on() function
$("body").off( "click", "p", foo );
JQuery
JavaScript
Element.removeEventListener(type, listener, options)
//example: foo needs to be the same function
//that was passed to addEventListener
document.removeEventListener("click", foo)
//Remove all listeners
elem.replaceWith(elem.cloneNode(true));
This type of validation involves checking all the mandatory fields and making sure they're properly filled in.
This type of validation actually looks at the values in the form and verifies that they are correct.
Validating email addresses is notoriously difficult – there are a vast number of legitimate email addresses and hosts, and it's impossible to guess all the valid combinations of characters.
That said, there are a few key factors that are common in all valid email addresses: