Friday, December 8, 2017

ES2015



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 passengers array and convert those subarrays into strings that contain the first and last name for each passenger.
  1. Create a modifiedNames variable to store our new data.
  2. Assign passengers.map() to the modifiedNames variable. This will allow us to pass in a function to be used on every element in the array.
  3. Pass an anonymous function to map().
  4. The anonymous function should take in arrayCell as a parameter and use that to return 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.
var passengers = [ ["Thomas", "Meeks"],
                   ["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:
  1. Build a function and assign it to a variable named applyAndEmpty.
  2. The function should take in an input number and a queue of functions as parameters.
  3. Using a for loop, call the functions in the queue in order with the inputnumber, where the results of each function becomes the next function’s input.
  4. Once done this loop, return from applyAndEmpty the final function’s result. Additionally, the queue should be empty at this point.
  5. Lastly, call the applyAndEmpty function using the provided startvariable and the puzzlers Queue as arguments, and alert 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; ipuzzlers));



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



function mystery(input) {
  var secret = 5;
  function mystery2(multiplier) {
    multiplier *= input;
    return secret * multiplier;
  }
  return mystery2;
}

var hidden = mystery(4);
var result = hidden(2);



Moar tricky. Moar tough! Again, calculate the final value of the resultvariable and alert the value as a number using one line of code. Hehe, good luck with this one!





function mystery(input) {
  var secret = 4;
  input += 2;
  function mystery2(multiplier) {
    multiplier *= input;
    return secret * multiplier;
  }
  return mystery2;
}

function mystery3(param) {
  function mystery4(bonus) {
    return param(6) + bonus;
  }
  return mystery4;
}

var hidden = mystery(3);
var jumble = mystery3(hidden);
var result = jumble(2);


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 superBlinders array and lighthouseRock object are provided. Each index of the superBlinders array contains a bulb name and its wattage within a sub-array.
  1. Completely remove the existing bulbs property from the lighthouseRock object.
  2. Add a weaponBulbs property to lighthouseRock and assign the superBlinders array as a value.
  3. Log the name value of the bulb with the highest wattage to the console. Use the correct index from the weaponBulbs property of the lighthouseRock object to access the correct name value.
Note: You do not need to change the provided code for the superBlindersarray 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 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 locationnameskillz, and station as parameters. Then we can pass in our lighthouseRock object as the location and start to add rangers.
  1. As rangers are added, increment the number of rangers at the location using its numRangers property.
  2. Add a property to the location using bracket notation that will be used to hold a ranger object. Specifically, each property will be named ranger1ranger2ranger3, etc. This will require string concatenation and the current value of the numRangers property.
  3. Now that you have your ranger property, assign an object literal to it that contains properties for nameskillz, and station. Then assign values to those properties using the parameters that we pass in.
  4. Call your addRanger function three times with the appropriate arguments to add the following rangers, in order, to the location:
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 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!
, man the !
, man the !
, man the !
We’ve created a dontPanic function for you that already contains the alert message. Your job is to finish building the list string:
  1. Create a for loop to loop through all of the rangers at the location, using the numRangers property to keep track.
  2. Inside the loop, begin by using the correct property to append the nameof the current ranger to the list.
  3. Also, concatenate the text between the ranger name and the superblinder so that it matches the format above.
  4. Lastly, add the name of the correct super-blinding light bulb from the weaponBulbs array to the list. In order to retrieve the name of the correct bulb, you’ll need to use the ranger’s station 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} }; 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); }







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]); };













-------------------------------------------------------------------------------------
Prototypes



Declarations

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; 
  1. cant be redeclared
  2. must assign initial value
  3. Are block scoped & not hoisted to the top of the functions


if(userNames.length > MAX_USERS){
------------------------------------------------------------------------------------------------------













------------------------------------------------------------------------------------------------------







Programming styles that javascript support:

As a multi-paradigm language, JavaScript supports
What it caters to 

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.




    Browser, Headless Browser, or RuntimeJavaScript Engine
    MozillaSpidermonkey
    ChromeV8
    Safari**JavaScriptCore*
    IE and EdgeChakra
    PhantomJSJavaScriptCore
    HTMLUnitRhino
    TrifleJSV8
    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