Data Types
-
JavaScript Strings
A string (or a text string) is a series of characters like "Ahmed mohamed".
EX:
let answer1 = "It's alright"; // Single quote inside double quotes let answer2 = "He is called 'Ahmed'"; // Single quotes inside double quotes let answer3 = 'He is called "Ahmed"'; // Double quotes inside single quotes -
JavaScript Numbers
JavaScript has only one type of numbers,Numbers can be written with, or without decimals.
EX:
let x1 = 34.00; // Written with decimals let x2 = 34; // Written without decimals -
JavaScript Booleans
Booleans can only have two values: true or false.
EX:
let x = 5; let y = 5; let z = 6; (x == y) // Returns true (x == z) // Returns false -
JavaScript Arrays
JavaScript arrays are written with square brackets. Array items are separated by commas.
EX:
const cars = ["Saab", "Volvo", "BMW"]; -
JavaScript Objects
JavaScript objects are written with curly braces {}. Object properties are written as name:value pairs, separated by commas.
EX:
const person = {firstName:"Ahmed", lastName:"mohamed", age:50, eyeColor:"blue"}; -
The typeof Operator
The typeof operator returns the type of a variable or an expression
EX:
typeof "" // Returns "string" typeof 314 // Returns "number" typeof 3.14 // Returns "number" -
Undefined
a variable without a value, has the value undefined. The type is also undefined
EX:
car = undefined; // Value is undefined, type is undefined -
Empty Values
An empty value has nothing to do with undefined. An empty string has both a legal value and a type.
EX:
let car = ""; // The value is "", the typeof is "string" -
JavaScript Types are Dynamic
means that the same variable can be used to hold different data types
EX:
let x; // Now x is undefined x = 5; // Now x is a Number x = "Ahmed"; // Now x is a String
Js Strings
- A JavaScript string is zero or more characters written inside quotes.
-
String Length
To find the length of a string
EX:
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; text.length; // Will return 26 -
Escape Character
The backslash (\) escape character turns special characters into string characters
Code Result Description Example (\') ' Single quote let text= 'It\'s alright.';
result : It's alright.(\") " Double quote let text = "We are the so-called \"Vikings\" from the north.";
result : We are the so-called "Vikings" from the north.(\\) \ Backslash let text = "The character \\ is called backslash.";
result : The character \ is called backslash -
Six other escape sequences are valid in JavaScript:
Code Result (\b) Backspace (\f) Form Feed (\n) New Line (\r) Carriage Return (\t) Horizontal Tabulator (\v) Vertical Tabulator
String Methods and Properties
-
String Length
EX:let txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; txt.length // Returns 26 -
Property Access
EX:// allows property access [ ] on strings let text = "HELLO WORLD"; text[0] // returns H -
The slice(start, end) Method
EX:let str = "Apple, Banana, Kiwi"; str.slice(7, 13) // Returns Banana let str = "Apple, Banana, Kiwi"; str.slice(-12, -6) // Returns Banana -
The substring(start, end or length of word) Method
EX:let str = "Apple, Banana, Kiwi"; substring(7, 13) // Returns Banana //cannot accept negative indexes.
If the first parameter is negative,
the position counts from the end of the string. -
the replace() Method
EX:let text = "Please visit Microsoft!"; let newText = text.replace("Microsoft", "W3Schools"); //replaces only the first match. //this method is case sensitive. let newText = text.replace(/MICROSOFT/i, "W3Schools"); //use a regular expression with an /i flag (insensitive) -
toUpperCase() Method
EX:let text1 = "Hello World!"; // String let text2 = text1.toUpperCase(); // text2 is text1 converted to upper -
toLowerCase() Method
EX:let text1 = "Hello World!"; // String let text2 = text1.toLowerCase(); // text2 is text1 converted to lower -
The concat() Method
EX:let text1 = "Hello"; let text2 = "World"; let text3 = text1.concat(" ", text2); -
String.trim()
EX:let text = " Hello World! "; text.trim() // Returns "Hello World!"; //removes whitespace from both sides of a string. -
padStart() and padEnd()
EX://support padding at the beginning and at the end of a string let text = "5"; text.padStart(4,0) // Returns 0005 let text = "5"; text.padEnd(4,0) // Returns 5000 -
charAt(position)
EX:// returns the character at a specified index (position) in a string let text = "HELLO WORLD"; text.charAt(0) // Returns H -
The charCodeAt() Method
EX:// returns the unicode of the character at a specified index in a string let text = "HELLO WORLD"; text.charCodeAt(0) // Returns 72 -
Converting a String to an Array "split()"
EX:text.split(",") // Split on commas text.split(" ") // Split on spaces text.split("|") // Split on pipe
JavaScript String Search
-
String.indexOf()
EX:// returns the index of (the position of) the first occurrence of a specified text in a string
let str = "Please locate where 'locate' occurs!"; str.indexOf("locate") // Returns 7 -
String.lastIndexOf()
EX://returns the index of the last occurrence of a specified text in a string
let str = "Please locate where 'locate' occurs!"; str.lastIndexOf("locate") // Returns 21 -
String.startsWith()
EX:// returns true if a string begins with a specified value, otherwise false let text = "Hello world, welcome to the universe."; text.startsWith("Hello") // Returns true -
String.endsWith()
EX:// returns true if a string ends with a specified value, otherwise false var text = "Ahmed mohamed"; text.endsWith("mohamed") // Returns true -
String.search()
EX://searches a string for a specified value and returns the position of the matc //This method is not equal to indexOf() let str = "Please locate where 'locate' occurs!"; str.search("locate") // Returns 7 -
String.match()
EX:// searches a string for a match against a regular expression, and returns the matches, as an Array object let text = "The rain in SPAIN stays mainly in the plain"; text.match(/ain/g) // Returns an array [ain,ain,ain] -
String.includes()
EX:// returns true if a string contains a specified value. let text = "Hello world, welcome to the universe."; text.includes("world") // Returns true string.includes(searchvalue, start) let text = "Hello world, welcome to the universe."; text.includes("world", 12) // Returns false
JavaScript Template Literals
-
Back-Tics Syntax
EX://back-ticks (``) rather than the quotes ("") to define a string let text = `Hello World!`;- Quotes Inside Strings EX:
//single and double qoutes can use for string let text = `He's often called "Ahmed"`; - Multiline Strings EX:
let text =
`The quick
brown fox
jumps over
the lazy dog`;
EX:
//Template literals provide an easy way
to interpolate variables and expressions into strings.
${...}
-
Variable Substitutions
EX://allow variables in strings let firstName = "Ahmed"; let lastName = "mohamed"; let text = `Welcome ${firstName}, ${lastName}!`; -
Expression Substitution
EX://allow expressions in strings let price = 10; let VAT = 0.25; let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`;
Js Arrays
- JavaScript arrays are used to store multiple values in a single variable
-
Examples:
const array_name = [item1, item2, ...]; const cars = ["Saab", "Volvo", "BMW"]; const cars = [ "Saab", "Volvo", "BMW" ]; const cars = new Array("Saab", "Volvo", "BMW"); -
Accessing Array Elements
access an array element by referring to the index number
EX:const cars = ["Saab", "Volvo", "BMW"]; let x = cars[0]; // x = "Saab" -
Changing an Array Element
EX:const cars = ["Saab", "Volvo", "BMW"]; cars[0] = "Opel"; -
Access the Full Array
the full array can be accessed by referring to the array name
EX:const cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars; -
Arrays are Objects
Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays
EX:const person = ["Ahmed", "mohamed", 46]; // array const person = {firstName:"Ahmed", lastName:"mohamed", age:46}; // object
Array Properties and Methods
-
The length Property
The length property of an array returns the length of an array (the number of array elements)
EX:const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.length; // Returns 4 -
Accessing the First Array Element
EX:const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[0]; // Returns "Banana" -
Accessing the Last Array Element
EX:const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[fruits.length - 1]; // Returns "Mango" -
Looping Array Elements
EX:// using for loop const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fLen = fruits.length; text = "<ul>"; for (let i = 0; i < fLen; i++) { text += "<li>" + fruits[i] + "</li>"; } text += "</ul>"; //using forEach loop const fruits = ["Banana", "Orange", "Apple", "Mango"]; let text = "<ul>"; fruits.forEach(myFunction); text += "</ul>"; function myFunction(value) { text += "<li>" + value + "</li>"; } -
Adding Array Elements
add a new element to an array is using the push() method
EX:const fruits = ["Banana", "Orange", "Apple"]; fruits.push("Lemon"); // Adds a new element (Lemon) to fruits -
Associative Arrays
arrays with named indexes.
EX:const person = []; person[0] = "Ahmed"; person[1] = "mohamed"; person[2] = 46; person.length; // Will return 3 person[0]; // Will return "Ahmed" -
How to Recognize an Array (isArray())
EX:const fruits = ["Banana", "Orange", "Apple"]; Array.isArray(fruits); // returns true fruits instanceof Array; // returns true
JavaScript Array Methods
-
Converting Arrays to Strings
-
tostring()The JavaScript method toString() converts an array to a string of (comma separated) array values.
EX:const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.toString(); -
join()The join() method also joins all array elements into a string and specify the separator
EX:const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.join(" * ");
-
-
Popping and Pushing
-
Popping
The pop() method removes the last element from an array
EX:const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.pop(); // Removes "Mango" from fruits -
Pushing
The push() method adds a new element to an array (at the end)
EX:const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Kiwi"); // Adds "Kiwi" to fruits
-
-
Shifting Elements
-
shift()The shift() method removes the first array element and "shifts" all other elements to a lower index
EX:const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.shift(); // Removes "Banana" from fruits -
unshift()The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements
EX:const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.unshift("Lemon"); // Adds "Lemon" to fruits
-
-
Changing Elements
Array elements are accessed using their index number
EX:const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[0] = "Kiwi"; // Changes the first element of fruits to "Kiwi" -
Deleting Elements
elements can be deleted by using the JavaScript operator delete
EX:const fruits = ["Banana", "Orange", "Apple", "Mango"]; delete fruits[0]; // Changes the first element in fruits to undefined -
Splicing an Array
The splice() method can be used to add new items to an array
EX:const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2, 0, "Lemon", "Kiwi"); -
splice() to Remove Elements
splice() to remove elements without leaving "holes" in the array
EX:const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(0, 1); // Removes the first element -
Merging (Concatenating) Arrays
The concat() method creates a new array by merging (concatenating) existing arrays
EX:const myGirls = ["Cecilie", "Lone"]; const myBoys = ["Emil", "Tobias", "Linus"]; // Concatenate (join) myGirls and myBoys const myChildren = myGirls.concat(myBoys); -
Slicing an Array
The slice() method creates a new array. It mohameds not remove any elements from the source array
EX:const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; const citrus = fruits.slice(1);
JavaScript Sorting Arrays
-
Sorting an Array
The sort() method sorts an array alphabetically
EX:const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); // Sorts the elements of fruits -
Reversing an Array
The reverse() method reverses the elements in an array.
EX:const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); // First sort the elements of fruits fruits.reverse(); // Then reverse the order of the elements -
Numeric Sort
the sort() function sorts values as strings
EX:const points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a - b}); -
The Compare Function
The purpose of the compare function is to define an alternative sort order. The compare function should return a negative, zero, or positive value, depending on the arguments
EX:function(a, b){return a - b} -
Sorting an Array in Random Order
add a new element to an array is using the push() method
EX:const points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return 0.5 - Math.random()}); -
Find the Highest (or Lowest) Array Value
EX:// Ascending const points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a - b}); // now points[0] contains the lowest value // and points[points.length-1] contains the highest value -
Math.max() on an Array
Math.max.apply to find the highest number in an array
EX:function myArrayMax(arr) { return Math.max.apply(null, arr); } -
Math.min() on an Array
Math.max.apply to find the highest number in an array
EX:function myArrayMin(arr) { return Math.min.apply(null, arr); } -
Sorting Object Arrays
EX:const cars = [ {type:"Volvo", year:2016}, {type:"Saab", year:2001}, {type:"BMW", year:2010} ]; cars.sort(function(a, b){return a.year - b.year});
JavaScript Array Iteration
-
Array.forEach()
The forEach() method calls a function (a callback function) once for each array element
EX:const numbers = [45, 4, 9, 16, 25]; let txt = ""; numbers.forEach(myFunction); function myFunction(value) { txt += value + "<br>"; } -
Array.map()
The map() method creates a new array by performing a function on each array element.
EX:
The map() method mohameds not execute the function for array elements without values.
The map() method mohameds not change the original arrayconst numbers1 = [45, 4, 9, 16, 25]; const numbers2 = numbers1.map(myFunction); function myFunction(value, index, array) { return value * 2; } -
Array.filter()
The filter() method creates a new array with array elements that passes a test
EX:fconst numbers = [45, 4, 9, 16, 25]; const over18 = numbers.filter(myFunction); function myFunction(value) { return value > 18; } -
Array.reduce()
The reduce() method runs a function on each array element to produce (reduce it to) a single value.
EX:
The reduce() method works from left-to-right in the array. See also reduceRight()const numbers = [45, 4, 9, 16, 25]; let sum = numbers.reduce(myFunction); function myFunction(total, value) { return total + value; } -
Array.reduceRight()
EX:const numbers = [45, 4, 9, 16, 25]; let sum = numbers1.reduceRight(myFunction); function myFunction(total, value) { return total + value; } -
Array.every()
The every() method check if all array values pass a test.
EX:const numbers = [45, 4, 9, 16, 25]; let allOver18 = numbers.every(myFunction); function myFunction(value, index, array) { return value > 18; } -
Array.some()
The some() method check if some array values pass a test.
EX:const numbers = [45, 4, 9, 16, 25]; let someOver18 = numbers.some(myFunction); function myFunction(value, index, array) { return value > 18; } -
Array.find()
The find() method returns the value of the first array element that passes a test function
EX:const numbers = [4, 9, 16, 25, 29]; let first = numbers.find(myFunction); function myFunction(value, index, array) { return value > 18; } -
Array.findIndex()
The findIndex() method returns the index of the first array element that passes a test function.
EX:const numbers = [4, 9, 16, 25, 29]; let first = numbers.findIndex(myFunction); function myFunction(value, index, array) { return value > 18; } -
Array.from()
The Array.from() method returns an Array object from any object with a length property or any iterable object.
EX:Array.from("ABCDEFG") // Returns [A,B,C,D,E,F,G] -
Array.Keys()
The Array.keys() method returns an Array Iterator object with the keys of an array.
EX:const fruits = ["Banana", "Orange", "Apple", "Mango"]; const keys = fruits.keys(); for (let x of keys) { text += x + "
"; }
JavaScript Array Const
-
An array declared with const cannot be reassigned
EX:const cars = ["Saab", "Volvo", "BMW"]; cars = ["Toyota", "Volvo", "Audi"]; // ERROR Arrays are Not Constants
-
Elements Can be Reassigned
EX:// You can create a constant array: const cars = ["Saab", "Volvo", "BMW"]; // You can change an element: cars[0] = "Toyota"; // You can add an element: cars.push("Audi"); -
Assigned when Declared
EX:const cars; cars = ["Saab", "Volvo", "BMW"]; -
An array declared with const has Block Scope
EX:const cars; cars = ["Saab", "Volvo", "BMW"]; -
Redeclaring an array declared with var is allowed anywhere in a program
EX:var cars = ["Volvo", "BMW"]; // Allowed var cars = ["Toyota", "BMW"]; // Allowed cars = ["Volvo", "Saab"]; // Allowed
Creating Date Objects
-
new Date()
new Date() creates a new date object with the current date and time
EX:const d = new Date(); -
new Date(year, month, ...)
new Date(year, month, ...) creates a new date object with a specified date and time
EX:const d = new Date(2018, 11, 24, 10, 33, 30, 0); -
Previous Century
One and two digit years will be interpreted as 19xx
EX:const d = new Date(99, 11, 24); -
new Date(dateString)
new Date(dateString) creates a new date object from a date string
EX:const d = new Date("October 13, 2014 11:13:00"); -
new Date(milliseconds)
new Date(milliseconds) creates a new date object as zero time plus milliseconds
EX:const d = new Date(0);
Date Methods
-
Displaying Dates
JavaScript will (by default) output dates in full text string format
EX:Wed Mar 25 2015 02:00:00 GMT+0200 (Eastern European Standard Time) -
toString()
EX:const d = new Date(); document.getElementById("demo").innerHTML = d.toString(); -
toUTCString()
The toUTCString() method converts a date to a UTC string (a date display standard)
EX:const d = new Date(); document.getElementById("demo").innerHTML = d.toUTCString(); -
toDateString()
The toDateString() method converts a date to a more readable format
EX:const d = new Date(); document.getElementById("demo").innerHTML = d.toDateString(); -
toISOString()
The toISOString() method converts a Date object to a string, using the ISO standard format
EX:const d = new Date(); document.getElementById("demo").innerHTML = d.toISOString();
JavaScript Get Date Methods
| Method | Description | Example |
|---|---|---|
| getFullYear() | Get the year as a four digit number (yyyy) |
|
| getMonth() | Get the month as a number (0-11) |
|
| getDate() | Get the day as a number (1-31) |
|
| getHours() | Get the hour (0-23) |
|
| getMinutes() | Get the minute (0-59) |
|
| getSeconds() | returns the seconds of a date as a number (0-59) |
|
| getMilliseconds() | Get the millisecond (0-999) |
|
| getTime() | Get the time (milliseconds since January 1, 1970) |
|
| getDay() | Get the weekday as a number (0-6) |
|
| Date.now() | Get the time. |
|
JavaScript Set Date Methods
| Method | Description | EX |
|---|---|---|
| setFullYear() | set the year as a four digit number (yyyy) |
|
| setMonth() | set the month as a number (0-11) |
|
| setDate() | set the day as a number (1-31) |
|
| setHours() | set the hour (0-23) |
|
| setMinutes() | set the minute (0-59) |
|
| setSeconds() | set the seconds of a date as a number (0-59) |
|
| setMilliseconds() | set the millisecond (0-999) |
|
| setTime() | set the time (milliseconds since January 1, 1970) |
|
| setDay() | set the weekday as a number (0-6) |
|