JavaScript arrays are used to store multiple values in a single variable. If you have a list of names, storing the names in single variables look like this.
var name1 = "Folau"; var name2 = "Kinga"; var name3 = "Laulau"; var name4 = "Tonga"; var name5 = "Isi";
However, what if you want to loop through the names and find a specific one? And what if you had 1000 names instead of 5 names?
The solution to this problem is arrays. An array can hold many values under a single name, and you can access the values by referring to an index number.
Array Declaration
You can use new Array or [].
let names = new Array('John','Peter','James'); let numbers = [1,2,3,4,5];
Access elements on Arrays
You access an array element by referring to the index number starting from 0.
let scores = new Array(12,34,56,100); let highScore = scores[3]; console.log("highScore: "+highScore);//100
Update element of an array
let scores = new Array(12,34,56,100); scores[3] = 505; let highScore = scores[3]; console.log("highScore: "+highScore);//505
Array size
The length property of an array returns the length of an array (the number of array elements).
let scores = new Array(12,34,56,100); console.log("scores.length: "+scores.length);//4
Add elements to an array
The easiest way to add a new element to an array is using the push() method. The push() method adds elements to the end of the array.
let names = ['John','Peter','James']; console.log("names"); console.log(names);["John", "Peter", "James"] names.push('Juan'); console.log("names"); console.log(names);["John", "Peter", "James","Juan"]
Use the unshift method to add elements to the beginning of the array.
let names = ['John','Peter','James']; console.log("names"); console.log(names);["John", "Peter", "James"] names.unshift('Juan'); console.log("names"); console.log(names);["Juan","John", "Peter", "James"]
Use the splice method can be used to add new items to an array.
let names = ['John','Peter','James']; console.log("names"); console.log(names);//['John','Peter','James'] names.splice(2, 0, "Folau"); console.log("names"); console.log(names);//['John','Peter','Folau','James']
Remove elements from an array
Use the pop() method which removes elements from the end of the array.
let names = ['John','Peter','James']; console.log("names"); console.log(names);//['John','Peter','James'] names.pop(); console.log("names"); console.log(names);//['John','Peter']
Use the shift() method to remove elements from the beginning of the array.
let names = ['John','Peter','James']; console.log("names"); console.log(names);//['John','Peter','James'] names.shift(); console.log("names"); console.log(names);//['Peter','James']
Note: methods push/pop
run fast, while shift/unshift
are slow.
Difference between Arrays and Objects.
Arrays use numbered indexes. Objects use named indexes.
let arr = ["Peter",25]; console.log("arr[0]: "+arr[0]);//Peter console.log("arr[1]: "+arr[1]);//25 let obj = {"name":"Peter","age":"25"}; console.log("obj.name: "+obj.name);//Peter
Sorting
By default, the sort() function sorts values as strings.
let names = ['John','Peter','James']; console.log("names"); console.log(names); names.sort(); console.log("names"); console.log(names);//["James", "John", "Peter"]
Sorting numbers using a comparator
var numbers = [40, 100, 1, 5, 25, 10]; numbers.sort(function(a, b){return a - b});// asc order - 1,5,10,25,40,100 numbers.sort(function(a, b){return b - a});// desc order - 100,40,25,10,5,1
Array Iteration
The foreach() method calls a function (a callback function) once for each array element.
/* * Array iteration */ console.log("Array Iteration with foreach"); var numbers = [2, 4, 6, 8 , 10]; // value numbers.forEach(function(number){ console.log("number: "+number); }); // value, index numbers.forEach(function(number,index){ console.log("number: "+number+", index: "+index); }); // value, index, array numbers.forEach(function(number,index, arr){ console.log("number: "+number+", index: "+index+", original array: "+arr); });
Using for loop to iterate through array elements.
/* * Array iteration */ var numbers = [2, 4, 6, 8 , 10]; console.log("Array Iteration with for loop"); for(let i=0;i<numbers.length;i++){ let number = numbers[i]; console.log("index: "+i+", number: "+number); }
Array map
The map() method creates a new array by performing a function on each array element. The map() method does not execute the function for array elements without values. The map() method does not change the original array.
console.log("Array map"); var numbers2 = numbers.map(function(number){ console.log("number: "+number); return number * 2; }); console.log(numbers); console.log("numbers2 * 2"); console.log(numbers2); var numbers3 = numbers.map(function(number, index){ console.log("number: "+number+", index: "+index); return number * 3; }); console.log(numbers); console.log("numbers3 * 3"); console.log(numbers3); var numbers4 = numbers.map(function(number, index, arr){ console.log("number: "+number+", index: "+index+", original array: "+arr); return number * 4; }); console.log(numbers); console.log("numbers4 * 4"); console.log(numbers4);
Output
number: 2 number: 4 number: 6 number: 8 number: 10 numbers - (5) [2, 4, 6, 8, 10] numbers2 * 2 numbers2 - (5) [4, 8, 12, 16, 20] number: 2, index: 0 number: 4, index: 1 number: 6, index: 2 number: 8, index: 3 number: 10, index: 4 numbers - (5) [2, 4, 6, 8, 10] numbers3 * 3 numbers3 - (5) [6, 12, 18, 24, 30] number: 2, index: 0, original array: 2,4,6,8,10 number: 4, index: 1, original array: 2,4,6,8,10 number: 6, index: 2, original array: 2,4,6,8,10 number: 8, index: 3, original array: 2,4,6,8,10 number: 10, index: 4, original array: 2,4,6,8,10 numbers - (5) [2, 4, 6, 8, 10] numbers4 * 4 numbers4 - (5) [8, 16, 24, 32, 40]
Array filter
The filter() method creates a new array with array elements that passes a condition.
console.log("Array filter"); var over8 = numbers.filter(function(number, index){ console.log("number: "+number+", index: "+index); return number >= 8; }); console.log("numbers: "+numbers); console.log("numbers greater than or equal 8"); console.log(over8);//[8, 10] var over4 = numbers.filter(function(number, index, arr){ console.log("number: "+number+", index: "+index+", original array: "+arr); return number >= 4; }); console.log("numbers: "+numbers); console.log("numbers greater than or equal 4"); console.log(over4);//[4, 6, 8, 10]
Array reduce
The reduce() method runs a function on each array element to produce (reduce it to) a single value. The reduce() method works from left-to-right in the array. Note that the reduce() method does not reduce the original array.
console.log("Array reduce"); var numbers = [2, 4, 6, 8 , 10]; var sum = numbers.reduce(function(total, number, index, arr){ console.log("total: "+total+", number: "+number+", index: "+index+", arr: "+arr); return total + number; }); console.log("numbers: "+numbers); console.log("sum of numbers: "+sum);// 30
Array every
The every() method check if all array values pass a condition.
console.log("Array every"); var numbers = [2, 4, 6, 8 , 10]; var allOver2 = numbers.every(function(number,index){ console.log("number: "+number+", index: "+index); return number >=2; }); console.log("allOver2: "+allOver2);// true var allOver4 = numbers.every(function(number,index,arr){ console.log("number: "+number+", index: "+index+", original array: "+arr); return number >=4; }); console.log("allOver4: "+allOver4);// false
Array some
The some() method check if some array values pass a condition.
console.log("Array some"); var numbers = [2, 4, 6, 8 , 10]; var someOver2 = numbers.some(function(number,index){ console.log("number: "+number+", index: "+index); return number >=2; }); console.log("someOver2: "+someOver2);// true var someOver4 = numbers.some(function(number,index,arr){ console.log("number: "+number+", index: "+index+", original array: "+arr); return number >=4; }); console.log("someOver4: "+someOver4);// true
Array indexOf
console.log("Array indexOf"); let names = ['John','James','Fika','Peter']; var peterIndex = names.indexOf("Peter"); console.log("peterIndex: "+peterIndex);// 3
Array find
The find() method returns the value of the first array element that passes a condition function.
console.log("Array find"); var numbers = [2, 4, 6, 8 , 10]; var first3 = numbers.find(function(number, index, arr){ return number > 3; }); console.log("first3: "+first3);// 4
JavaScript strings are primitive values. JavaScript strings are also immutable. It means that if you process a string, you will always get a new string. The original string doesn’t change. Strings are used for storing and manipulating text.
To create a string, you can use single quote or double quote.
let firstName = 'Folau'; let lastName = "Kaveinga";
String as objects
Don’t create strings as objects. It slows down execution speed and when it comes to comparison, it produces unexpected results.
let folau = new String("Folau"); let lisa = new String("Lisa"); let sameString = (folau=="Folau");// true let sameObject = (folau==="Folau");// false //When using the === operator, equal strings are not equal, because the === operator expects equality in both type and value. var kinga = new String("kinga"); var king = new String("kinga"); let samePerson = (kinga==king);// false, even though the value for both objects is "kinga"
To escape special characters, you use the backslash \ character.
if it’s a single quote string and you want to escape a single quote, you do this: \’
if it’s a double quote string and you want to escape a double quote, you do this: \”
if want to escape a backslash \, you do this: \\
let str = 'I\'m Folau Kaveinga.'; document.getElementById("userDesc").innerHTML = str; let str1 = "I\"m Folau Kaveinga."; let str2 = 'I\'m slash \\'; document.getElementById("userDesc").innerHTML += str1; document.getElementById("userDesc").innerHTML += str2; // output I'm Folau Kaveinga.I"m Folau Kaveinga.I'm slash \
To get length of a string, you use the length function
let str = 'I\'m Folau Kaveinga.'; let strLength = str.length; console.log("strLength: "+strLength); // strLength: 19
To access the characters in a string, you use the array-like []
notation with the zero-based index.
let name = "Folau Kaveinga"; let letter = name[4]; console.log("letter: "+letter);// u
To convert a non-string value to a string, use toString(), number + “”, or String(number)
let active = false; let activeStr = active.toString(); console.log("activeStr: "+activeStr);// "false"
let five = 5; let fiveStr = new String(five); console.log("fiveStr: "+fiveStr);// 5
String concatenate
The concat() method concatenates one or more strings to another and returns the result string. Note that the concat()
method does not modify the original string.
let firstName = 'Folau'; let fullName = firstName.concat(' ','Kaveinga', ' ', 'Jr'); console.log(fullName); // "Folau Kaveinga Jr"
You can also use the + operator to concatenate strings. In practice, the addition operator is used more often than the concate() method.
let firstName = 'Folau'; let fullName = firstName + ' '+ 'Kaveinga'+' '+'Jr'; console.log(fullName); // "Folau Kaveinga Jr"
To get a substring, use the substr or substring function
substr(startIndex,length);
The first argument startIndex the location at which the characters are being extracted, while the second argument length specifies the number of characters to extract.
substring(startIndex,endIndex)
Sometimes, you want to extract a substring from a string using starting and ending indexes.
let phrase = "I love coding"; console.log(phrase.substr(2, 4)); // "love" console.log(phrase.substr(7, 6)); // "coding" console.log(phrase.substring(7, 13)); // "coding"
To find position of a substring with a string, use the indexOf function
string.indexOf(substring,fromIndex);
You can also find the last index of a substring in a string by using the lastIndexOf function
string.lastIndexOf(substring,fromIndex)
let phrase = "I love coding so much"; console.log(phrase.indexOf("o")); // 3 console.log(phrase.indexOf('o', 3)); // 3 console.log(phrase.lastIndexOf('o')); // 15 console.log(phrase.indexOf('test'));// -1
The indexOf and lastIndexOf functions return -1 if substring is not found in the string.
There are more modern methods str.includes(substr, pos) returns true/false depending on whether str contains subtr within.
console.log( "Folau".includes("lau") ); // true console.log( "Folau".includes("ol", 4 )); // false, from position 4 there is no "ol" console.log( "Folau".startsWith("Fol") ); // true, "Folau" starts with "Fol" console.log( "Folau".endsWith("lau") ); // true, "Folau" ends with "lau"
Remove leading and trailing whitespace, use trim(), trimStart(), and trimEnd()
let name = ' Folau '; let strippedName= name.trim(); let leadingStrippedName= name.trimStart(); let trailingStrippedName= name.trimEnd(); console.log(strippedName); // "Folau" console.log(leadingStrippedName); // "Folau " console.log(trailingStrippedName); // " Folau"
Replace substring within a string, use replace function
string.replace(regularExpression, replaceText)
The first argument of the replace method could be a regular expression or a string. If it is a regular expression, the replace() method will find the matches and replace them with the second argument (replaceText). In case it is a string, the replace() method will perform an exact search and carry the replacement.
let phrase = "I love coding so much"; // replace "the" with "a" let newPhrase = phrase.replace(/so/g, "very"); console.log(newPhrase); // "I love coding very much" console.log(phrase); // "I love coding so much"
A callback function is a function passed into another function as an argument, which is then invoked inside that function at a later time. JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors. To prevent this, you can create a callback function.
Callback Function Synchronous
<h4 class="text-center">Callback function synchronous</h4> <div class="row"> <div class="col-3"> <button onclick="checkin()" type="button" class="btn btn-outline-primary">Check In Synchronous</button> </div> <div class="col-6"> <div class="text-center" id="welcomeNote"></div> </div> </div> <!-- Callback function synchronous --> <script> function checkin(){ console.log("checkin..."); checkUser(greeting); console.log("checkin done!"); } function greeting(name) { console.log("greeting..."); alert('Hey ' + name); document.getElementById("welcomeNote").innerHTML = "Welcome "+name+"!"; console.log("greeting done!"); } function checkUser(callback) { console.log("checkUser..."); var name = prompt('What is your name?'); callback(name); console.log("checkUser done!"); } </script>
Callback functions are often used to continue code execution after an asynchronous operation has completed. A good example is the callback functions executed inside a .then() block chained onto the end of a promise after that promise completes or rejects. This structure is used in many modern web APIs, such as fetch().
Callback Function Asynchronous
<h4 class="text-center">Callback function asynchronous</h4> <div class="row"> <div class="col-3"> <button onclick="checkApi()" type="button" class="btn btn-outline-primary">Check In Asynchronous</button> </div> <div class="col-6"> <div class="text-center" id="apiNote"></div> </div> </div> <!-- Callback function asynchronous --> <script> function checkApi(){ console.log("checkApi..."); getRandomNumber(showApiResult); console.log("checkApi done!"); } function getRandomNumber(showApiResult){ let apiEndpoint = "https://www.random.org/integers/?num=1&min=1&max=6&col=1&base=10&format=plain&rnd=new"; $.get(apiEndpoint, function(data, status){ console.log(status); console.log(data); showApiResult(data); }); } function showApiResult(randomNumber){ document.getElementById("apiNote").innerHTML = "Here is your random number "+randomNumber+"!"; } </script>
Callback Function jQuery
<h4 class="text-center">Callback function with jQuery</h4> <div class="row"> <div class="col-3"> <button onclick="checkjQuery()" type="button" class="btn btn-outline-primary">Check In jQuery</button> </div> <div class="col-6"> <div class="text-center" id="jqueryNote"></div> </div> </div> <!-- Callback function asynchronous with jquery --> <script> $(document).ready(function(){ /** Note: use this to reference variables and functions */ this.name = "Folau"; this.checkjQuery = function(){ console.log("checkjQuery..."); this.getJQueryRandomNumber(this.showJQueryApiResult); console.log("checkjQuery done!"); } this.getJQueryRandomNumber = function(showJQueryApiResult){ console.log("getJQueryRandomNumber..."); // reference this to outside function. var self = this; let apiEndpoint = "https://www.random.org/integers/?num=1&min=1&max=6&col=1&base=10&format=plain&rnd=new"; $.get(apiEndpoint, function(data, status){ console.log(status); console.log(data); self.showJQueryApiResult(data); }); console.log("getJQueryRandomNumber done!"); } this.showJQueryApiResult = function(randomNumber){ console.log("showJQueryApiResult..."); document.getElementById("jqueryNote").innerHTML = "Here is your random number "+randomNumber+"!"; console.log("showJQueryApiResult done!"); } // this function does not work as it does not use this function showJQueryApiResult(randomNumber){ console.log("showJQueryApiResult..."); document.getElementById("jqueryNote").innerHTML = "Here is your random number "+randomNumber+"!"; console.log("showJQueryApiResult done!"); } }); </script>
Javascript was created to make web pages responsive. With Javascript you’ll be able to create reponsive web pages, games, animated 2D and 3D graphics, comprehensive database-driven apps, and much more. Today, JavaScript can execute not only in the browser, but also on the server, or actually on any device that has a special program called the JavaScript engine. The browser has an embedded engine sometimes called a “JavaScript virtual machine”.
JavaScript virtual machine is complicated. But the basics are easy.
The engine applies optimizations at each step of the process. It even watches the compiled script as it runs, analyzes the data that flows through it, and further optimizes the machine code based on that knowledge.
There are at least three great things about JavaScript which is the only browser technology that combines these three things.
Modern JavaScript is a “safe” programming language. It does not provide low-level access to memory or CPU, because it was initially created for browsers which do not require it.
JavaScript’s capabilities greatly depend on the environment it’s running in. For instance, Node.js supports functions that allow JavaScript to read/write to disk, perform network requests, etc.
In-browser JavaScript can do everything related to webpage manipulation, interaction with the user, and the webserver.
For instance, in-browser JavaScript is able to:
JavaScript’s abilities in the browser are limited for the sake of the user’s safety. The aim is to prevent an evil webpage from accessing private information or harming the user’s data.
Examples of such restrictions include:
Pay very dose attention to any information in the problem description. You will need it all for an optimal solution. If you have documentation on the domain subject, read it. If you have technical documentation around the problem, read it. Your focus at this point is to get as much knowledge as possible around the problem.
Make sure to have examples of the problem so that you can verify that the problem exists. For example, let’s say your problem is that a payment amount is not calculated correctly based on some logic, make sure you have the fields and values that make the payment amount incorrectly. Check that case and other cases that you may see as a problem.
Get a brute-force solution as soon as possible. Don’t worry about developing an efficient algorithm yet. State a naive algorithm and its runtime, then optimize from there.
Walk through your brute-force solution and optimize areas that can be optimized. Look at time complexity. Make a time vs. space trade off if possible. Hash tables are very useful in this situation. Many times you can solve it manually on paper, then reverse engineer your thought process.
Now that you have your optimal solution, walk through your approach with details. Make sure you understand your optimal solution in your head.
Now that you have your solution on paper, it’s time to make it work in code. Modularize your code from the beginning and refactor to clean up anything that isn’t clear.
Write tests, write tests and write some more tests. You must write tests to support and verify your solution. Having tests that verify your solution will hold your solution stable and last long.
Walk through your code like you would for a detailed code review. Remember that small test cases are much faster and just as effective as big test cases.
Cover special cases and edge cases.