Skip to content

Instantly share code, notes, and snippets.

@disooqi
Last active February 20, 2021 10:16
Show Gist options
  • Save disooqi/6d60dffb1fe20d4b51cab222e4734248 to your computer and use it in GitHub Desktop.
Save disooqi/6d60dffb1fe20d4b51cab222e4734248 to your computer and use it in GitHub Desktop.
Learn JavaScript

Arrays

  • JavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have variables of different types in the same Array. You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array
  • The new keyword only complicates the code. It can also produce some unexpected results:
var points = new Array();     // Bad
var points = [];              // Good 

var points = new Array(40, 100, 1, 5, 25, 10); // Bad
var points = [40, 100, 1, 5, 25, 10];          // Good 

var points = new Array(40, 100);  // Creates an array with two elements (40 and 100)
var points = new Array(40);  // Creates an array with 40 undefined elements !!!!!
  • Looping using foreach:
var fruits, text;
fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.forEach(myFunction);

function myFunction(value, index, array) {
  text += "<li>" + value + "</li>";
}
 
// using Arrow Function 
fruits.forEach((value, index, array) => {
    console.log(value, index, array);
});
  • Apending to the array
var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.push("Lemon");    // adds a new element (Lemon) to fruits 
fruits[fruits.length] = "Lemon";    // adds a new element (Lemon) to fruits
  • Adding elements with high indexes can create undefined "holes" in an array.
  • If you use named indexes, JavaScript will redefine the array to a standard object. After that, some array methods and properties will produce incorrect results.
  • Arrays are a special kind of objects, with numbered indexes.
  • 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.
  • How to Recognize an Array if typeof returns object
    • To solve this problem ECMAScript 5 defines a new method Array.isArray(): Array.isArray(fruits); // returns true
    • For older browser, you can create your own isArray() function as follow:
    function isArray(x) {
    return x.constructor.toString().indexOf("Array") > -1;
    } 
    • The instanceof operator returns true if an object is created by a given constructor: fruits instanceof Array; // returns true .
  • Methods: toString(), join(), pop(), push(), shift(), unshift(), delete fruits[0];, splice(), concat(), slice(), sort(), reverse(), Math.max.apply(), Math.min.apply,
  • Using delete may leave undefined holes in the array. Use pop() or shift() instead.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi"); //in-place change.
fruits.splice(0, 1);        // Removes the first element of fruits 
  • The concat() method can take any number of array arguments: var newarray = arr1.concat(arr2, arr3);
  • The concat() method can also take strings as arguments: var newarray = arr1.concat("Mariam");
  • Sorting Array of objects:
var cars = [
  {type:"Volvo", year:2016},
  {type:"Saab", year:2001},
  {type:"BMW", year:2010}
];
cars.sort(function(a, b){return a.year - b.year}); // sort cars based on year

cars.sort(function(a, b){
  var x = a.type.toLowerCase();
  var y = b.type.toLowerCase();
  if (x < y) {return -1;}
  if (x > y) {return 1;}
  return 0;
}); 

Datatypes

  • JavaScript variables can hold many data types: numbers, strings, objects and more.
  • JavaScript has only one type of numbers.
  • Extra large or extra small numbers can be written with scientific (exponential) notation: var y = 123e5;
  • Booleans can only have two values: true or false.
  • JavaScript arrays are written with square brackets: var cars = ["Saab", "Volvo", "BMW"];
  • The typeof operator returns object for arrays because in JavaScript arrays are objects.
  • JavaScript objects are written with curly braces: var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
  • You can use the JavaScript typeof operator to find the type of a JavaScript variable: typeof "John Doe"
  • In JavaScript, a variable without a value, has the value undefined. The type is also undefined. Any variable can be emptied, by setting the value to undefined: car = undefined;
  • In JavaScript null is "nothing". It is supposed to be something that doesn't exist. in JavaScript, the data type of null is an object.
  • You can empty an object by setting it to null. You can also empty an object by setting it to undefined.
  • undefined and null are equal in value but different in type:
null === undefined      // false
null == undefined       // true
  • Primitive types are string, number, boolean, undefined.
  • The typeof operator can return one of two complex types: function or object.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Tutorial for UC</title>
</head>
<body>
<p id="tryreplace">Mr. Blie has 45 blie Horses. He works for BBC, CNN and Fox news. He is 52 years old.</p>
<button onclick="myReplaceFunc();">Try Replace</button>
<button onclick='arrayToString(["Apple", "Orange", "Banana"]);'>Try arrayToString function</button>
<button onclick="getDigits(getMrBlueSen());">Try getDigits()</button>
<button onclick='getCurrentDate();'>Try getCurrentDate()</button>
<p id="myfruits"></p>
<p id="myformat"></p>
<p id="intlformat"></p>
<script>
function myReplaceFunc() {
var str = document.getElementById("tryreplace").innerHTML;
var str2 = str.replace(/i/g, "u");
alert(str2);
}
function arrayToString(arr) {
//document.getElementById("myfruits").innerHTML = arr;
//document.getElementById("myfruits").innerHTML = arr.join(" and ");
document.getElementById("myfruits").innerHTML = arr.concat();
// alert(arr);
}
function getMrBlueSen(){
return document.getElementById("tryreplace").innerHTML;
}
function getDigits(myStr) {
var matches = myStr.match(/\d/g);
var num = matches.join("");
alert(num);
}
function getCurrentDate() {
var date = new Date();
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
document.getElementById("myformat").innerHTML =
days[date.getDay()] + ", " + months[date.getMonth()] + " " + date.getDate()+ ", "+ date.getFullYear();
// For advanced users (not required in the course)
// check https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date?page=1&tab=votes#tab-top
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat#examples
var options = {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'};
var date_formated = new Intl.DateTimeFormat('en-CA', options).format(date);
document.getElementById("intlformat").innerHTML = date_formated;
}
</script>
</body>
</html>

Functions

  • Function parameters are listed inside the parentheses () in the function definition. Function arguments are the values received by the function when it is invoked.
  • funcName refers to the function object, and funcName() refers to the function result. Accessing a function without () will return the function object instead of the function result.
  • The name:values pairs in JavaScript objects are called properties.
  • You can access object properties in two ways: objectName.propertyName or objectName["propertyName"]
  • A method is a function stored as a property: fullName : function() { return this.firstName + " " + this.lastName; }.
  • In a function definition, this refers to the "owner" of the function.
  • When a JavaScript variable is declared with the keyword new, the variable is created as an object:
var x = new String();        // Declares x as a String object
var y = new Number();        // Declares y as a Number object
var z = new Boolean();       // Declares z as a Boolean object
  • Avoid String, Number, and Boolean objects. They complicate your code and slow down execution speed.

Hoisting

  • Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).
  • JavaScript only hoists declarations, not initializations.
  • In JavaScript, a variable can be declared after it has been used. In other words; a variable can be used before it has been declared. That does not mean it gives a value when use it. It only gives you undefined. but you can assign some value to it.
  • Variables defined with let and const are hoisted to the top of the block, but not initialized. Meaning: The block of code is aware of the variable, but it cannot be used until it has been declared. Using a let variable before it is declared will result in a ReferenceError.
    • Variables defined with var are hoisted to the top and can be initialized at any time (i.e. You can use the variable before it is declared). Variables defined with let are hoisted to the top of the block, but can't not be initialized (i.e. The block of code is aware of the variable, but it cannot be used until it has been declared).
  • To avoid bugs, always declare all variables at the beginning of every scope. OR, use strict mode. JavaScript in strict mode does not allow variables to be used if they are not declared.
  • use strict; Defines that JavaScript code should be executed in "strict mode". Strict mode is declared by adding use strict; to the beginning of a script or a function.
  • Declared inside a function, it has local scope (only the code inside the function is in strict mode). Declared at the beginning of a script, it has global scope (all code in the script will execute in strict mode).
  • One good benefit for using strict mode is that, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.
  • Deleting a variable (or object) is not allowed in strict mode.

Looping Methods

  • Array.forEach(<a callback function>)
  • Array.map(<a callback function>)
  • Array.filter(<a callback function>)
  • Array.reduce(<a callback function>, [<initial value>]) method runs a function on each array element to produce (reduce it to) a single value.
  • reduceRight() vs reduce()
  • Array.every(<a callback function>), check if all array values pass a test.
  • Array.some(<a callback function>), check if some array values pass a test.
var numbers = [45, 4, 9, 16, 25];
var allOver18 = numbers.every(myFunction);

function myFunction(value, index, array) {
  return value > 18;
}

// using Arrow Function
var allOver18 = numbers.every((value => value > 18));
  • Array.indexOf()
  • Array.lastIndexOf()
  • Array.find()
  • Array.findIndex()

learn-JS

  • Datatypes
  • Numbers
  • Strings
  • Date
  • Events
  • Functions
  • Arrays
  • Looping Methods
  • Hoisting
  • Placing scripts at the bottom of the element improves the display speed, because script interpretation slows down the display.

  • The script will behave as if it was located exactly where the <script> tag is located.

  • If you re-declare a JavaScript variable, it will not lose its value.

  • If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated.

  • JavaScript evaluates expressions from left to right. Different sequences can produce different results: var x = 16 + 4 + "Volvo"; versus var x = "Volvo" + 16 + 4;

  • Using the dollar sign is not very common in JavaScript, but professional programmers often use it as an alias for the main function in a JavaScript library.

  • Using the underscore is not very common in JavaScript, but a convention among professional programmers is to use it as an alias for "private (hidden)" variables.

  • Before 2015, using the var keyword was the only way to declare a JavaScript variable.

  • The 2015 version of JavaScript (ES6) allows the use of the const keyword to define a variable that cannot be reassigned, and the let keyword to define a variable with restricted scope.

  • Before ES2015, JavaScript had only two types of scope: Global Scope and Function Scope.

  • Variables declared with the var keyword cannot have Block Scope. Variables declared inside a block {} can be accessed from outside the block. Before ES2015 JavaScript did not have Block Scope. Variables declared with the let keyword can have Block Scope.

  • Redeclaring a variable using var inside a block will also redeclare the variable outside the block.

  • When let is used to declare the i variable in a loop, the i variable will only be visible within the loop.

  • Variables declared with var and let are quite similar when declared inside a function (i.e. function scope).

  • Variables declared with var and let are quite similar when declared outside a block (i.e. global scope). However, using let will not attach the variable the window object.

  • With JavaScript, the global scope is the JavaScript environment. In HTML, the global scope is the window object.

  • Global variables defined with the var keyword belong to the window object. Global variables defined with the let keyword do not belong to the window object.

Numbers

  • JavaScript Numbers are Always 64-bit Floating Point.
  • JavaScript will try to convert strings to numbers in all numeric operations. Except for + operator, it will be used for concatination.
  • NaN is a JavaScript reserved word indicating that a number is not a legal number.
  • You can use the global JavaScript function isNaN() to find out if a value is a number.
  • If you use NaN in a mathematical operation, the result will also be NaN. (Or the result might be a concatenation NaN5).
  • NaN is a number i.e. typeof NaN returns number.
  • Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number.
  • Division by 0 (zero) also generates Infinity.
  • Infinity is a number i.e. typeof Infinity returns number.
  • JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x.
  • Never write a number with a leading zero (like 07). Some JavaScript versions interpret numbers as octal if they are written with a leading zero.
  • you can use the toString() method to output numbers from base 2 to base 36.

Redeclaring

variable Redeclaring with let Redeclaring with var Redeclaring to const
var x = 5; not allowed in the same scope allowed anywhere not allowed in the same scope
let x = 5; not allowed in the same scope not allowed in the same scope not allowed in the same scope
const x = 5; not allowed in the same scope not allowed in the same scope not allowed in the same scope
  • Variables defined with var are hoisted to the top and can be initialized at any time (i.e. You can use the variable before it is declared). Variables defined with let are hoisted to the top of the block, but not initialized. Variables defined with let are hoisted to the top of the block, but not initialized (i.e. The block of code is aware of the variable, but it cannot be used until it has been declared).
  • Variables defined with const behave like let variables, except they cannot be reassigned.
  • JavaScript const variables must be assigned a value when they are declared.
let name = 'Mohame Eldesouki';
console.log(`My name is ${name}`);
// it preserve the indentation level and line feed character
let sentence = `Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean
massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis,
ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel,
aliquet nec, vulputate`;
console.log(sentence);
let mount = 3;
console.log(`Give me ${(mount===1)? 'one good reason': 'few good reasons' } to try this.`);

Strings

  • You can use single or double quotes to define string literals.
  • If a JavaScript statement does not fit on one line, the best place to break it is after an operator. You can also break up a code line within a text string with a single backslash. The \ method is not the preferred method. It might not have universal support. Some browsers do not allow spaces behind the \ character. A safer way to break up a string, is to use string addition (i.e. concatenation).
  • Note the difference between (x==y) and (x===y). Comparing two JavaScript objects will always return false.
  • Primitive values, like "hello world", cannot have properties or methods (because they are not objects). But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
var str = "Mohamed Eldesouki; 38 years   "; 
str.length;
str.indexOf("desouki"); //  return -1 if the text is not found.
str.lastIndexOf("o"); // returns the index of the last occurrence of a specified text
str.search("\d+") // returns the position of the match, return -1 if the text is not found.
// to return the indices of all occurences use regExPattern.exec(str), beware that flag `g` is required to preserve the state of the last index, see (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec)
function returnAllIndices(str) {
  var regExPattern = /ELDESOUKI/ig, result, indices = [];
  while ( (result = regExPattern.exec(str)) ) {
     indices.push(result.index);
  } 
  return indices;  
}


var new_str = str.slice(10, 19); // returns the extracted part in a new string (end not included). work exactly as Python slicing
new_str = str.substring(7, 13); // substring() is similar to slice(). The difference is that substring() cannot accept negative indexes.
new_str = str.substr(7, 13);    // substr()    is similar to slice(). The difference is that the second parameter specifies the length of the extracted part.
new_str = str.replace("Eldesouki", "Ibrahim"); // does not change the string it is called on. It returns a new string. replaces only the first match, and is case sensitive
new_str = str.replace(/ELDESOUKI/i, "Ibrahim"); // To replace case insensitive, use a regular expression with an /i flag (insensitive). Note that regular expressions are written without quotes.
// To replace all matches, use a regular expression with a /g flag (global match)

new_str = str.concat(" ", text2);
console.log(text.repeat(2));
console.log(text.endsWith('. '));
console.log(text.startsWith('The'));
console.log(text.includes('fox'));
  • All string methods return a new string. They don't modify the original string. Formally said: Strings are immutable: Strings cannot be changed, only replaced.
  • You can also use the replace solution above to add a trim function to the JavaScript String.prototype
if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}
var str = "       Hello World!        ";
alert(str.trim())
// Inside object literal, this keyword refers to the object itself
let disooqi = {
fullname: 'Mohamed Eldesouki',
occupation: 'Research Associate acting as Software Engineer',
define: function () {
return this.fullname + ' is a ' + this.occupation;
}
};
console.log(disooqi.define());
// Inside a function, this keyword is based on how you call the function
function tryThis(){
return this;
}
console.log(tryThis()===global);
console.log(this===global);
function tryThisUsingStrict() {
'use strict';
return this;
}
console.log(tryThisUsingStrict()===global);
console.log(tryThisUsingStrict()===undefined);
global.fullname= 'Moha Moha';
function checkValue(place, affiliation) {
// this keyword refer to global object
return this.fullname+' is in '+place+' and works for '+affiliation;
}
let checkValueInGlobal = checkValue;
console.log(checkValueInGlobal('Doha', 'QF'));
let checkValueInDisooqiObj = checkValue;
console.log(checkValueInDisooqiObj.call(disooqi, 'Doha', 'QF'));
console.log(checkValueInDisooqiObj.apply(disooqi, ['Doha', 'QF']));
disooqi.print = checkValue;
console.log(disooqi.print('Doha', 'QF')); // it is equivalent to use .call or .apply
/*####### Very Important note #####
In all the former ways, the property that comes after this keyword "i.e. this.property" must be in the object "this"
represent. so, for example disooqi obj has a property named fullname and global object also has a property named
fullname.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment