Pop-up Windows
var userAge = prompt("What's your age, user?");
var ageIsCorrect = confirm( "You entered "+userAge+". Is this correct?");
Functional Expression
var runAway= function() {
var toAlert = "";
for (var i = 0; i < 5; i++) {
toAlert = toAlert + "Lions, Tigers, and Bears, Oh My!!\n";
}
alert(toAlert);
};
Using Map With Arrays
Over at Maple Mountain, the dev team has received some name data from the customer terminal that they want to use to customize greetings for each of their passengers. But the data consists of an array with many subarrays where the first and last names of each passenger are split up.
They want to take the
They want to take the
passengers
array and convert those subarrays into strings that contain the first and last name for each passenger.- Create a
modifiedNames
variable to store our new data. - Assign
passengers.map()
to themodifiedNames
variable. This will allow us to pass in a function to be used on every element in the array. - Pass an anonymous function to
map()
. - The anonymous function should take in
arrayCell
as a parameter and use that toreturn
a string with the first and last name for a passenger. In other words, if you were to pass in a["Jason", "Millhouse"]
array, the function should return a"Jason Millhouse"
string.
["Gregg", "Pollack"],
["Christine", "Wong"],
["Dan", "McGaw"] ];
var modifiedNames = passengers.map(function(arrayCell){
return arrayCell[0]+' '+arrayCell[1];
});
var modifiedNames = [ "Thomas Meeks",
"Gregg Pollack",
"Christine Wong",
"Dan McGaw" ];
modifiedNames.map(function(name){
alert("Yo, " + name + "!");
});
Function Array
var puzzlers = [function(input){return 3 * input - 8},
function(input){return (input + 2)*(input + 2)*(input + 2)},
function(input){return input*input - 9},
function(input){return input%4}
]
function adventureSelector(userChoice){ if (userChoice == 1) { return function() { alert("You selected the Vines of Doom!"); }; } else if (userChoice == 2) { return function() { alert("Looks like you want the Lake of Despair!"); }; } else { return function() { alert("The Caves of Catastrophe!"); }; } }
The devs at Poplar Puzzles would like you to treat an array of functions like a Queue, passing the result of each function into the next until the Queue is empty. They’ve sent you the
puzzlers
Queue of functions, and the following instructions:- Build a function and assign it to a variable named
applyAndEmpty
. - The function should take in an
input
number and aqueue
of functions as parameters. - Using a
for
loop, call the functions in thequeue
in order with theinput
number, where the results of each function becomes the next function’s input. - Once done this loop, return from
applyAndEmpty
the final function’s result. Additionally, thequeue
should be empty at this point. - Lastly, call the
applyAndEmpty
function using the providedstart
variable and thepuzzlers
Queue as arguments, andalert
the result.
var puzzlers = [ function(a) { return 8 * a - 10; }, function(a) { return (a - 3) * (a - 3) * (a - 3); }, function(a) { return a * a + 4; }, function(a) { return a % 5; } ]; var start = 2;
... var applyAndEmpty = function (input, queue){ var length = queue.length; for(var i=0; i
var puzzlers = [
function(a) { return 8 * a - 10; },
function(a) { return (a - 3) * (a - 3) * (a - 3); },
function(a) { return a * a + 4; },
function(a) { return a % 5; }
];
alert(puzzlers[puzzler[2](3)](puzzlers[3](9))
Closures
Moar tricky. Moar tough! Again, calculate the final value of the
result
variable and alert
the value as a number using one line of code. Hehe, good luck with this one!
First call:
var hidden = mystery(3)
In here, the variable is assigned the following function:
var hidden = function mystery2 ( multiplier ) {
multiplier = multiplier * 5;
return 4 * multiplier;
}
From now on, when using 'hidden', you keep this version of the mystery2 function in mind.
Second call:
var jumble = mystery3(hidden);
In here, the variable is assigned the following function:
var jumble = function mystery4( bonus ){
return hidden(6) + bonus;
}
Again, when you see 'jumble', just imagine this function.
The fun begins with third line of code:
var result = jumble(2);
What happens now?
'jumble' (our version of mystery4 function) is run with 2 as an argument, so jumble becomes:
var jumble = function mystery4 ( 2 ){
return hidden(6) + 2;
}
You probably still remember that 'hidden' was nothing else, but our version of the mystery2 function, which is run here with 6 as an argument. In this case, hidden becomes:
var hidden = function mystery2 ( 6 ){
return 6 * 5 * 4;
}
So, back to 'jumble'
var jumble = function mystery4 ( 2 ){
return 120 + 2;
}
And that's how 'result' became 122. I hope I wrote it in an understandable
Understanding functions
function warningMaker(obstacle) {
var count = 0;
var zones = [];
return function(number, location) {
count++;
var list = "";
// push an array with location and number
zones.push(/*//array//*/);
for (var i = 0; i < zones.length; i++) {
// replace location and number with appropriate code
list += /*//location//*/ + " (" + /*//number//*/ + ")" + "\n";
}
alert("Beware! There have been " + obstacle +
" sightings in the Cove today!\n" +
number + " have been spotted at the " +
location + "!\n" +
"This is alert #" + count +
" today for " + obstacle + " danger.\n" +
"Current danger zones are:\n" +
list);
};
}
Hoisting
Arrays
Object Creation
Another Example
var vehicle1 = {type: "Motorboat", capacity: 6, storedAt: "Ammunition Depot"}; var vehicle2 = {type: "Jet Ski", capacity: 1, storedAt: "Reef Dock"}; var vehicle3 = {type: "Submarine", capacity: 8, storedAt: "Underwater Outpost"}; // create vehicles array var vehicles = [vehicle1, vehicle2, vehicle3]; // build findVehicle function expression var findVehicle = function(name, list) { for (var i = 0; i < list.length; i++) { if (list[i].type == name) { return list[i].storedAt; } } }; // call findVehicle findVehicle("Submarine", vehicles);
-----------------------------------------------
var superBlinders = [ ["Firelight", 4000], ["Solar Death Ray", 6000], ["Supernova", 12000] ]; var lighthouseRock = { gateClosed: true, bulbs: [200, 500, 750], capacity: 30, secretPassageTo: "Underwater Outpost" }; // remove bulbs property from lighthouseRock delete lighthouseRock.bulbs; // add weaponBulbs property to lighthouseRock lighthouseRock.weaponBulbs = superBlinders; // log the correct weaponBulbs array value to the console console.log(lighthouseRock.weaponBulbs[2][0]);
--------------------------------------------------
var superBlinders = [ ["Firestorm", 4000], ["Solar Death Ray", 6000], ["Supernova", 12000] ]; var lighthouseRock = { gateClosed: true, weaponBulbs: superBlinders, capacity: 30, secretPassageTo: "Underwater Outpost", numRangers: 0 }; function addRanger(location, name, skillz, station) { location.numRangers++; location["ranger" + location.numRangers] = { name: name, skillz: skillz, station: station }; } addRanger(lighthouseRock, "Nick Walsh", "magnification burn", 2);
addRanger(lighthouseRock, "Drew Barontini", "uppercut launch", 3); addRanger(lighthouseRock, "Christine Wong", "bomb defusing", 1);
------------------------------------------------------------------------------------
Blinders On!
The ranger-devs want to upgrade Lighthouse Rock with new super-blinding light bulbs and remove the old existing bulbs.
The new
The new
superBlinders
array and lighthouseRock
object are provided. Each index of the superBlinders
array contains a bulb name and its wattage within a sub-array.- Completely remove the existing
bulbs
property from thelighthouseRock
object. - Add a
weaponBulbs
property tolighthouseRock
and assign thesuperBlinders
array as a value. - Log the name value of the bulb with the highest wattage to the
console
. Use the correct index from theweaponBulbs
property of thelighthouseRock
object to access the correct name value.
superBlinders
array or the lighthouseRock
object.var superBlinders = [ ["Firestorm", 4000], ["Solar Death Ray", 6000], ["Supernova", 12000] ];
var lighthouseRock = {
gateClosed: true,
weaponBulbs: superBlinders,
capacity: 30,
secretPassageTo: "Underwater Outpost",
numRangers: 3,
ranger1: {name: "Nick Walsh", skillz: "magnification burn", station: 2},
ranger2: {name: "Drew Barontini", skillz: "uppercut launch", station: 3},
ranger3: {name: "Christine Wong", skillz: "bomb defusing", station: 1}
};
function dontPanic(location) {
var list = "Avast, me hearties!\n" +
"There be Pirates nearby! Stations!\n";
for (var i = 1; i <= location.numRangers; i++) {
var ranger = location["ranger"+i];
var name = ranger.name;
var superblinder = location.weaponBulbs[ranger.station-1][0];
list += name + ", man the " + superblinder + "!\n";
}
alert(list);
}
dontPanic(lighthouseRock);
--------------------------------------------------
To the Lighthouse, Quick!
PIRATES AHOY! It’s time for the ranger-devs to get over to the Lighthouse and throw down! Our
Your goal is to complete the
lighthouseRock
object now has a new numRangers
property to track how many rangers are fighting at the Lighthouse.Your goal is to complete the
addRanger
function that takes in location
, name
, skillz
, and station
as parameters. Then we can pass in our lighthouseRock
object as the location
and start to add rangers.- As rangers are added, increment the number of rangers at the
location
using itsnumRangers
property. - Add a property to the
location
using bracket notation that will be used to hold a ranger object. Specifically, each property will be namedranger1
,ranger2
,ranger3
, etc. This will require string concatenation and the current value of thenumRangers
property. - Now that you have your
ranger
property, assign an object literal to it that contains properties forname
,skillz
, andstation
. Then assign values to those properties using the parameters that we pass in. - Call your
addRanger
function three times with the appropriate arguments to add the following rangers, in order, to thelocation
:
name: "Nick Walsh", skillz: "magnification burn", station: 2 name: "Drew Barontini", skillz: "uppercut launch", station: 3 name: "Christine Wong", skillz: "bomb defusing", station: 1
var superBlinders = [ ["Firestorm", 4000], ["Solar Death Ray", 6000], ["Supernova", 12000] ];
var lighthouseRock = {
gateClosed: true,
weaponBulbs: superBlinders,
capacity: 30,
secretPassageTo: "Underwater Outpost",
numRangers: 0
};
function addRanger(location, name, skillz, station) {
location.numRangers++;
location["ranger" + location.numRangers] = {
name: name,
skillz: skillz,
station: station
};
}
addRanger(lighthouseRock, "Nick Walsh", "magnification burn", 2);
addRanger(lighthouseRock, "Drew Barontini", "uppercut launch", 3);
addRanger(lighthouseRock, "Christine Wong", "bomb defusing", 1);
-------------------------------------------------
250
Man your Bulb Stations!
We need to assign each of the ranger-devs to a super-blinding light bulb based on their
var superBlinders = [ ["Firestorm", 4000], ["Solar Death Ray", 6000], ["Supernova", 12000] ];
var lighthouseRock = {
gateClosed: true,
weaponBulbs: superBlinders,
capacity: 30,
secretPassageTo: "Underwater Outpost",
numRangers: 3,
ranger1: {name: "Nick Walsh", skillz: "magnification burn", station: 2},
ranger2: {name: "Drew Barontini", skillz: "uppercut launch", station: 3},
ranger3: {name: "Christine Wong", skillz: "bomb defusing", station: 1}
};
function dontPanic(location) {
var list = "Avast, me hearties!\n" +
"There be Pirates nearby! Stations!\n";
for (var i = 1; i <= location.numRangers; i++) {
var ranger = location["ranger"+i];
var name = ranger.name;
var superblinder = location.weaponBulbs[ranger.station-1][0];
list += name + ", man the " + superblinder + "!\n";
}
alert(list);
}
station
number. So we’re building a function that creates an alert
message for the ranger-devs in the following format:Avast, me hearties! There be Pirates nearby! Stations!We’ve created a, man the ! , man the ! , man the !
dontPanic
function for you that already contains the alert
message. Your job is to finish building the list
string:- Create a
for
loop to loop through all of the rangers at thelocation
, using thenumRangers
property to keep track. - Inside the loop, begin by using the correct property to append the
name
of the current ranger to thelist
. - Also, concatenate the text between the ranger
name
and the superblinder so that it matches the format above. - Lastly, add the name of the correct super-blinding light bulb from the
weaponBulbs
array to thelist
. In order to retrieve the name of the correct bulb, you’ll need to use the ranger’sstation
number.
var superBlinders = [ ["Firestorm", 4000], ["Solar Death Ray", 6000], ["Supernova", 12000] ]; var lighthouseRock = { gateClosed: true, weaponBulbs: superBlinders, capacity: 30, secretPassageTo: "Underwater Outpost", numRangers: 3, ranger1: {name: "Nick Walsh", skillz: "magnification burn", station: 2}, ranger2: {name: "Drew Barontini", skillz: "uppercut launch", station: 3}, ranger3: {name: "Christine Wong", skillz: "bomb defusing", station: 1}, addRanger: function( name, skillz, station) { this.numRangers++; this["ranger" + this.numRangers] = { name: name, skillz: skillz, station: station }; } };
// create addBulb function property here lighthouseRock.addBulb = function(name, wattage) { this.weaponBulbs.push([name, wattage]); };
-------------------------------------------------------------------------------------
PrototypesDeclarations
Functions
Arrays, maps And Set
Classes And Modules
Promises, Iterators, And Generator
Variable Declaration
Hoisting
Declaration with let
JavaScript moves var declarations all the way up to the top of the scope. This is known as hoisting.
Declaration with const
const MAX_USERS = 3;
- cant be redeclared
- must assign initial value
- Are block scoped & not hoisted to the top of the functions
------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------
Programming styles that javascript support:
As a multi-paradigm language, JavaScript supports
- event-driven,
- functional, and
- imperative (including object-oriented and prototype-based) programming styles.
What it caters to
- text,
- arrays,
- dates,
- regular expressions,
What it doesn't cater to ?
Does not include any I/O, such as networking, storage, or graphics facilities, relying for these upon the host environment in which it is embedded.
What is ECMAScript ? What is ECMAScript engine ?
ECMAScript is a standard script language, developed with the cooperation of Netscape and Microsoft and mainly derived from Netscape's JavaScript, the widely-used scripting language that is used in Web pages to affect how they look or behave for the user.
An ECMAScript engine is a program that executes source code written in a version of the ECMAScript language standard, for example, JavaScript.
Eg.
- Tamarin: An ActionScript and ECMAScript engine used in Adobe Flash.
- V8: A JavaScript engine used in Google Chrome, Node.js, and V8.N
- Nashorn: A JavaScript engine used in Oracle Java Development Kit (JDK) since version 8.
Browser, Headless Browser, or Runtime | JavaScript Engine |
---|---|
Mozilla | Spidermonkey |
Chrome | V8 |
Safari** | JavaScriptCore* |
IE and Edge | Chakra |
PhantomJS | JavaScriptCore |
HTMLUnit | Rhino |
TrifleJS | V8 |
Node.js*** | V8 |
Io.js*** | V8 |
Key ingredients:
- Arrays
- Objects
- Date,String,Maps
- Events
- Document
- Regular Expressions
- Promised/Async /await
References:
https://developer.telerik.com/featured/a-guide-to-javascript-engines-for-idiots/
No comments:
Post a Comment