JavaScript

Part 3
JavaScript - Part 3
-
Functions
-
Arrays
Variable Scope
Location where you declare a variable will affect where it can be used.
Local Variable:
A variable declared inside a function can only be used in that function
Global Variable:
A variable declared outside of a function can be used anywhere within the script.
Variable Scope
Location where you declare a variable will affect where it can be used.
Local Variable:
A variable declared inside a function can only be used in that function
function printArea(width,height)
{
var area = width * height;
console.log("Area is: " + area);
}
Variable Scope
Location where you declare a variable will affect where it can be used.
Local Variable:
A variable declared inside a function can only be used in that function
function getArea(width,height)
{
var area = width * height;
return area;
}
var size = getArea(10,3);
console.log("Area is: " + size);
Global Variable:
A variable declared outside of a function can be used anywhere in within the script.
Variable Scope
Location where you declare a variable will affect where it can be used.
Local Variable:
A variable declared inside a function can only be used in that function
function getArea(width,height)
{
var area = width * height;
return area;
}
var size = getArea(10,3);
console.log("Area is: " + size);
console.log("Area is: " + area);
Global Variable:
A variable declared outside of a function can be used anywhere in within the script.
Full Script
getArea()
var size
var area
Variable Scope
Location where you declare a variable will affect where it can be used.
Local Variable:
A variable declared inside a function can only be used in that function
function getArea(width,height)
{
var area = width * height;
return area;
}
var size = getArea(10,3);
console.log("Area is: " + size);
console.log("Area is: " + area);
Global Variable:
A variable declared outside of a function can be used anywhere in within the script.
Arrays
Stores a List of Values
var colour1 = "red";
var colour2 = "green";
var colour3 = "blue";
Arrays
Stores a List of Values
var colours = ['red','green','blue'];
Each Item is automatically given an Index (Index starts at 0)
'red' | 'green' | 'blue' |
---|
0
1
2
Arrays
Index used to access specific items
var colours = ['red','green','blue']; var thirdItem = colours[2]; //'blue'
'red' | 'green' | 'blue' |
---|
0
1
2
Arrays
Index also used to change items in array
var colours = ['red','green','blue']; var thirdItem = colours[2]; //'blue' colours[1] = 'purple'
'red' | 'purple' | 'blue' |
---|
0
1
2
Arrays
New data can be added to the array
var colours = ['red','green','blue']; colours[3] = 'pink';
'red' | 'purple' | 'blue' |
---|
0
1
2
'pink' |
---|
3
Arrays
Getting the length of the array
var colours = ['red','green','blue']; var myColoursLength = colours.length;//3
Arrays Excercise
- Create an array of 3 movie names. Order the list like a top 3 chart with index 0 being top of the charts.
- Create a variable called number2 and assign it the value of the movie in second place in the chart.
- The chart has changed and the movie in second place has now taken top spot.
- Assign the value currently in top spot to the second position in the chart
- Then set the top spot equal to the the number2 variable
- A new entry has appeared in the charts at number 4. Add a new movie to the list at number 4.
In Chrome JavaScript Console do the following (Ctrl+Shift+J to open console)
Arrays - Built in Functions
-
Push & Pop
-
Shift & Unshift
-
indexOf
-
slice
Arrays have some built in functions which we can use.
Push & Pop
var fruits = ["Banana", "Orange", "Apple", "Mango"];
//to add a new fruit we can do this...
fruits[4] = "Pear";
fruits[5] = "Grapes";
//However we need to always keep track of the size to do this
var fruits = ["Banana", "Orange", "Apple", "Mango"];
//a better way to add is to use push
fruits.push("Pear");
fruits.push("Grapes");
//We can just keep adding without keeping track of the length
Adding Values to an Array (Method 1 - Index)
Adding Values to an Array (Method 2 - Push)
Push & Pop
var fruits = ["Banana", "Orange", "Apple", "Mango"];
//remove the last element "Mango"
var lastFruit = fruits.pop();
//lastFruit is now "Mango"
Use Pop to remove the last element item in an array
'Banana' | 'Orange' | 'Apple' |
---|
'Mango' |
---|
fruits =
lastFruit =
'Mango' |
---|
Shift & Unshift
var fruits = ["Banana", "Orange", "Apple", "Mango"];
//add "Pineapple" to the start of the array
fruits.unshift("Pineapple");
//["Pineapple","Banana", "Orange", "Apple", "Mango"]
Use Unshift to add to the front/start of an array
var fruits = ["Banana", "Orange", "Apple", "Mango"];
//remove the first element "Banana"
var firstFruit = fruits.shift();
Use Shift to remove from the front/start of an array
IndexOf
var fruits = ["Pineapple","Banana", "Orange", "Apple", "Mango"]; //find the index of "Orange" in the array var indexOfOrange = fruits.indexOf("Orange"); //2 //find the index of "Pineapple" in the array var indexOfPineapple = fruits.indexOf("Pineapple"); //0 //find the index item that doesnt exist returns a -1 var indexOfNotThere = fruits.indexOf("Kiwi"); //-1
var fruits = ["Pineapple","Banana", "Orange", "Apple", "Mango"]; //find the index of "Orange" in the array var indexOfOrange = fruits.indexOf("Orange"); //2 //find the index of "Pineapple" in the array var indexOfPineapple = fruits.indexOf("Pineapple"); //0 //find the index item that doesnt exist returns a -1 var indexOfNotThere = fruits.indexOf("Kiwi"); //-1
var fruits = ["Pineapple","Banana", "Orange", "Apple", "Mango"]; //find the index of "Orange" in the array var indexOfOrange = fruits.indexOf("Orange"); //2 //find the index of "Pineapple" in the array var indexOfPineapple = fruits.indexOf("Pineapple"); //0 //find the index item that doesnt exist returns a -1 var indexOfNotThere = fruits.indexOf("Kiwi"); //-1
var fruits = ["Pineapple","Banana", "Orange", "Apple", "Mango"]; //find the index of "Orange" in the array var indexOfOrange = fruits.indexOf("Orange"); //2 //find the index of "Pineapple" in the array var indexOfPineapple = fruits.indexOf("Pineapple"); //0 //find the index item that doesnt exist returns a -1 var indexOfNotThere = fruits.indexOf("Kiwi"); //-1
Find the index of a specific item in an array
Slice
var fruits = ["Pineapple","Banana", "Orange", "Apple", "Mango"]; //copy the 3rd and 4th fruits //slice words by accepting the start and end index of the subset var subset = fruits.slice(2,4);// ["Orange","Apple"]
var fruits = ["Pineapple","Banana", "Orange", "Apple", "Mango"]; //copy the 3rd and 4th fruits //slice words by accepting the start and end index of the subset var subset = fruits.slice(2,4);// ["Orange","Apple"]
Copy subset of an array
Arrays
2 Dimensional Arrays
var groups = [[1,2,3],[4,5,6],[7,8,9]];
var thirdGroup = groups[2]; //[7,8,9]
var thirdGroup_secondItem = thirdGroup[1];//8
[1,2,3] | [4,5,6] | [7,8,9] |
---|
0
1
2
var thirdGroup_secondItem = groups[2][1];//8
Exercise
var cars = ["Ford","Nissan","Honda","VW"];
console.log(cars[cars.length]);
Exercise
var cars = [
["Ford","Cadillac","Chrysler"],
["Audi","BMW","VW"],
["Toyota","Honda","Nissan"],
];
console.log(cars[2][0]);
Exercise
var cars = [
["Ford","Cadillac","Chrysler"],
["Audi","BMW","VW"],
["Toyota","Honda","Nissan"],
];
console.log(cars[0][1]);
Exercise
var cars = [
["Ford","Cadillac","Chrysler"],
["Audi","BMW","VW"],
["Toyota","Honda","Nissan"],
];
console.log(cars[1]);
Arrays and Loops
var fruits = ["Banana", "Orange", "Apple", "Mango"];
//print all values in the array
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
console.log(fruits[3]);
//not good...what if array had 100 elements..or 1000
Arrays and Loops
var fruits = ["Banana", "Orange", "Apple", "Mango"];
for(var i=0; i < fruits.length; i++)
{
console.log(fruits[i]);
}
Loop over an array to to something to/with all items in an array
For Loop:
Arrays and Loops
var fruits = ["Banana", "Orange", "Apple", "Mango"];
function consolePrint(color){
console.log(color);
}
//pass function name as argument
fruits.forEach(consolePrint);
ForEach Loop:
arrayVariable.forEach(someFunction);
Exercise 5
var x = [1,2,3,4,5,6,7,8,9,10];
function myFunction(number)
{
if(number % 2 === 0)
{
console.log(number * number);
}
}
x.forEach(myFunction);
Exercise
printReverse()
Write a function printReverse() which takes an array as argument and prints out the elements in the array in reverse order.
Exercise
getProduct()
Write a function getProduct() which takes an array as argument and returns a number which is the product of all number is the array.
Asssume that an array of numbers will be input
e.g:
[1,3,5,4] = 1 x 3 x 5 x 4 = 60
Exercise
getMax()
Write a function getMax() which takes an array as argument and returns a number which is the maximum of all number is the array.
Asssume that an array of numbers will be input
e.g:
[1,3,5,4] = Max is 5
Exercise
isPassed()
Write a function isPassed() which takes a single numeric arguement and returns true if the number is greater than 40 and false otherwise
Exercise
factorial()
Write a function factorial() which takes a single numeric argument and returns the factorial of that number.
N! : factorial of N is multiplication of all positive numbers less than or equal to N
4! = 4 x 3 x 2 x 1
6! = 6 x 5 x 4 x 3 x 2 x 1
Exercise
isValidEmail()
Write a function isValidEmail() which takes a single string argument and returns a true if the string represents a valid email address. Otherwise, false is returned
Hint: use to check each character to find "@" and "."
Additional Checks could look at position of "@" and "."
Exercise
isValidPassword()
Write a function isValidPassword() which takes a single string argument and returns a true if the string represents a valid password. Otherwise, false is returned
A valid password is defined as:
- It should be at least 8 characters long
- It should be no more that 16 characters
-
Should contain at least one of the following symbols :
- "£", "$", "%" or "#"
Exercise
isValidAge()
Write a function isValidAge() which takes a single string argument and returns a true if the number entered is a valid age. Otherwise, false is returned
A valid age is defined as:
- Users must be over 18. Ages under 18 is not valid
- An actual number must be entered
- Values over 110 are not valid
Hint: parseInt() to convert from string to number (see here)
Exercise
- Prompt the user to enter their email address
- Using isValidEmail(), check if the entered email is valid
- If the email is valid, continue to step 2,
- Otherwise, repeat the prompt to enter a valid email (use a while loop)
-
Prompt the user to enter their password
- Using isValidPassword(), check if the entered password is valid
- If the password is valid, continue to step 3,
- Otherwise, repeat the prompt to enter a valid password (use a while loop)
-
Prompt the user to enter their age
- Using isValidAge(), check if the entered age is valid
- If the age is valid, display an alert stating success!
- Otherwise, repeat the prompt to enter a valid age (use a while loop
javascript3
By D.Kelly
javascript3
- 753