Summary

This document provides a JavaScript review for the INFO-3168 course at Fanshawe. It covers fundamental concepts such as data types, variables, operators, and basic JavaScript syntax. This review is designed for students with some prior Javascript experience.

Full Transcript

JavaScript Review INFO-3168 Case Sensitivity The first concept to understand is that everything is case-sensitive; variables, function names, and operators are all case-sensitive, meaning that a variable named test is different from a variable named Test Identifier...

JavaScript Review INFO-3168 Case Sensitivity The first concept to understand is that everything is case-sensitive; variables, function names, and operators are all case-sensitive, meaning that a variable named test is different from a variable named Test Identifiers An identifier is the name of a variable, function, property, or function argument. Identifiers may be one or more characters in the following format: The first character must be a letter, an underscore (_), or a dollar sign ($) All other characters may be letters, underscores, dollar signs, or numbers By convention, JavaScript identifiers use camel case, meaning that the first letter is lowercase and each additional word is offset by a capital letter, like this: firstSecond myCar doSomethingImportant Comments JavaScript uses C-style comments for both single-line and block comments. A single-line comment begins with two forward-slash characters, such as this: //single line comment A block comment begins with a forward slash and asterisk (), as in this example: Input and Output alert("Some Text"); var myName = prompt("Enter your name: "); document.write("Some Text Output"); Statements… Statements in JavaScript are terminated by a semicolon, though omitting the semicolon makes the parser determine where the end of a statement occurs, as in the following examples: var sum = a + b //valid even without a semicolon – //not recommended var diff = a - b; //valid - preferred Statements… Multiple statements can be combined into a code block by using C- style syntax, beginning with a left curly brace ({) and ending with a right curly brace (}): if (test){ test = false; alert(test); } Statements Control statements, such as if, require code blocks only when executing multiple statements However, it is considered a best practice to always use code blocks with control statements, even if there’s only one statement to be executed, as in the following examples: if (test) alert(test); //valid, but error-prone and should be //avoided if (test){ //preferred alert(test); } Variables… JavaScript variables are loosely typed, meaning that a variable can hold any type of data. Every variable is simply a named placeholder for a value. To define a variable, use the var operator (note that var is a keyword) followed by the variable name (an identifier, as described earlier), like this: var message; // value is undefined Variables… var message = "hi"; Here, message is defined to hold a string value of "hi". Doing this initialization doesn’t mark the variable as being a string type; it is simply the assignment of a value to the variable. It is still possible to not only change the value stored in the variable but also change the type of value, such as this: var message = "hi"; message = 100; //legal, but not recommended Variables… Global variables are any variable defined outside a JavaScript function: var globalName = "Jimbo"; function myFunc(){ alert("Hi " + globalName); } Variables… It’s important to note that using the var operator to define a variable makes it local to the scope in which it was defined. For example, defining a variable inside of a function using var means that the variable is destroyed as soon as the function exits, as shown here: function test(){ var message = "hi"; //local variable } test(); alert(message); //error! Variables If you need to define more than one variable, you can do it using a single statement, separating each variable (and optional initialization) with a comma like this: var message = "hi", found = false, age = 29; Data Types There are five simple data types (also called primitive types) in JavaScript: Undefined, Null, Boolean, Number, String There is also one complex data type called Object, which is an unordered list of name-value pairs typeof Operator Because JavaScript is loosely typed, there needs to be a way to determine the data type of a given variable. The typeof operator provides that information. Using the typeof operator on a value returns one of the following strings: "undefined" if the value is undefined "boolean" if the value is a boolean "string" if the value is a string "number" if the value is a number "object" if the value is an object (other than a function) or null "function" if the value is a function typeof Examples var message = "some string"; var myNum = 5; var myFlag = false; alert(typeof message); //"string" alert(typeof(message)); //"string" alert(typeof myNum); // "number" alert(typeof 95); // "number" alert(typeof myFlag) // "boolean" Boolean Type The Boolean type is one of the most frequently used types in JavaScript and has only two literal values: true and false. These values are distinct from numeric values, so true is not equal to 1, and false is not equal to 0. Assignment of Boolean values to variables is as follows: var found = true; var lost = false; Note that the Boolean literals true and false are case-sensitive, so True and False (and other mixings of uppercase and lowercase) are valid as identifiers but not as Boolean values. Number Type… Perhaps the most interesting data type in JavaScript is Number, which uses the IEEE-754 format to represent both integers and floating- point values (also called double-precision values in some languages). To support the various types of numbers, there are several different number literal formats. The most basic number literal format is that of a decimal integer, which can be entered directly as shown here: var intNum = 55; //integer Number Type Floating-Point Values To define a floating-point value, you must include a decimal point and at least one number after the decimal point. Although an integer is not necessary before a decimal point, it is recommended var floatNum1 = 1.1; var floatNum2 = 0.1; var floatNum3 =.1; //valid, but not //recommended NaN (Not A Number) There is a special numeric value called NaN, short for Not a Number, which is used to indicate when an operation intended to return a number has failed (as opposed to throwing an error) For example, dividing any number by 0 typically causes an error in other programming languages, halting code execution In JavaScript, dividing a number by 0 returns NaN, which allows other processing to continue isNaN function The isNaN function accepts a single argument, which can be of any data type, to determine if the value is "not a number." alert(isNaN(NaN)); //true alert(isNaN(10)); //false - 10 is a number alert(isNaN("10")); //false - can be //converted to number 10 alert(isNaN("blue")); //true - cannot be //converted to a number alert(isNaN(true)); //false - can be //converted to number 1 Converting Strings to Integers The parseInt() function examines a string to see if it matches a number pattern var num1 = parseInt("1234blue"); //1234 var num2 = parseInt(""); //NaN var num3 = parseInt("0xA"); //10 - hexadecimal var num4 = parseInt(22.5); //22 var num5 = parseInt("70"); //70 - decimal var num6 = parseInt("0xf"); //15 - hexadecimal Converting Strings to Floats The parseFloat() function works in a similar way to parseInt(), looking at each character starting in position 0 var num1 = parseFloat("1234blue"); //1234 - //integer var num2 = parseFloat("0xA"); //0 var num3 = parseFloat("22.5"); //22.5 var num4 = parseFloat("22.34.5"); //22.34 var num5 = parseFloat("0908.5"); //908.5 var num6 = parseFloat("3.125e7"); //31250000 String Type… The String data type represents a sequence of zero or more 16-bit Unicode characters. Strings can be delineated by either double quotes (") or single quotes (‘), so both of the following are legal: var firstName = "Nicholas"; var lastName = 'Zakas'; String Type… The length of any string can be returned by using the length property as follows: var text = "The quick brown fox"; alert(text.length); //outputs 19 String Type… Strings are immutable in JavaScript, meaning that once they are created, their values cannot change. To change the string held by a variable, the original string must be destroyed and the variable filled with another string containing a new value, like this: var lang = "Java"; lang = lang + "Script"; Converting Numbers to Strings Use the toString() method to convert a number to a string: var num = 10; alert(num.toString()); //"10" alert(num.toString(2)); //"1010" alert(num.toString(10)); //"10" alert(num.toString(16)); //"a" Operators Unary Operators Increment/Decrement The increment and decrement operators are taken directly from C and come in two versions: prefix and postfix The prefix versions of the operators are placed before the variable they work on; the postfix ones are placed after the variable var age = 29; ++age; age++; Operators (Unary) var fullName = "Sherlock "; var myLast = "Holmes"; fullName += myLast; Operators (Boolean) Boolean operators are what make a programming language work. Without the capability to test relationships between two values, statements such as if...else and loops wouldn’t be useful. There are three Boolean operators: NOT, AND, and OR. var test = false; if (!test){ // NOT operator // code here } Operators (Boolean) var test = false; var test1 = true; if (test && test1){ // AND operator // code here } if (test || test1){ // OR operator // code here } Operators (Multiplicative) There are three multiplicative operators in JavaScript: multiply, divide, and modulus If either of the operands for a multiplication operation isn’t a number, it is converted to a number behind the scenes using the Number() casting function var result = 34 * 56; var result = 66 / 11; var result = 26 % 5; //equal to 1 Operators (Additive) The additive operators, add and subtract, are typically the simplest mathematical operators in programming languages As with the multiplicative operators, conversions occur behind the scenes for different data types If both operands are strings, the second string is concatenated to the first If only one operand is a string, the other operand is converted to a string and the result is the concatenation of the two strings Operators (Additive) var result = 1 + 2; var result1 = 5 + 5; //two numbers alert(result1); //10 var result2 = 5 + "5"; //a number and a string alert(result2); //"55" Operators (Additive) Subtraction If either operand is a string, a Boolean, null, or undefined, it is converted to a number (using Number() behind the scenes) and the arithmetic is calculated If the conversion results in NaN, then the result of the subtraction is NaN var result1 = 5 - true; //4 because true is converted to 1 var result2 = NaN - 1; //NaN var result3 = 5 - 3; //2 var result4 = 5 - ""; //5 because "" is converted to 0 var result5 = 5 - "2"; //3 because "2" is converted to 2 var result6 = 5 - null; //5 because null is converted to 0 Relational Operators The less-than (), less-than-or-equal-to (=) relational operators perform comparisons between values in the same way that you learned in math class Each of these operators returns a Boolean value, as in this example if (5 > 3){ // do some stuff here } Relational Operators var result = "Brick" < "alphabet"; //true var result = "Brick".toLowerCase() < "alphabet".toLowerCase(); //false var result = "23" < "3"; //true var result = "23" < 3; //false var result = "a" < 3; //false because "a" becomes NaN Equality Operators The equal operator in JavaScript is the double equal sign (==), and it returns true if the operands are equal The not-equal operator is the exclamation point followed by an equal sign (!=), and it returns true if two operands are not equal Both operators do conversions to determine if two operands are equal (often called type coercion) Equality Operators Identically Equal and Not Identically Equal The identically equal and not identically equal operators do the same thing as equal and not equal, except that they do not convert operands before testing for equality The identically equal operator is represented by three equal signs (===) and returns true only if the operands are equal without conversion The not identically equal operator is represented by an exclamation point followed by two equal signs (!==) and returns true only if the operands are not equal without conversion Equality Operators var result1 = ("55" == 55); //true - equal because of // conversion var result2 = ("55" === 55); //false - not equal because // different data types var result1 = ("55" != 55); //false - equal because of // conversion var result2 = ("55" !== 55); //true - not equal because // different data types Assignment Operator Simple assignment is done with the equal sign (=) and simply assigns the value on the right to the variable on the left, as shown in the following examples: var num = 10; num = num + 10; var num = 10; num += 10; Comma Operator The comma operator allows execution of more than one operation in a single statement, as illustrated here: var num1=1, num2=2, num3=3; Statements (switch…) Example: switch ("hello world") { case "hello" + " world": alert("Greeting was found."); break; case "goodbye": alert("Closing was found."); break; default: alert("Unexpected message was found."); } Functions Functions are the core of any language, because they allow the encapsulation of statements that can be run anywhere and at any time. Functions in JavaScript are declared using the function keyword, followed by a set of arguments and then the body of the function. The basic syntax is as follows: function functionName(arg0, arg1,...,argN) { statements } Functions Example: function sayHi(name, message) { alert("Hello " + name + ", " + message); } This function can then be called by using the function name, followed by the function arguments enclosed in parentheses (and separated by commas, if there are multiple arguments) The code to call the sayHi() function looks like this: sayHi("Nicholas", "how are you today?"); Functions Functions in JavaScript need not specify whether they return a value Any function can return a value at any time by using the return statement followed by the value to return Consider this example: function sum(num1, num2) { return num1 + num2; } The sum() function adds two values together and returns the result. Note that aside from the return statement, there is no special declaration indicating that the function returns a value This function can be called using the following: var result = sum(5, 5); Functions (arguments) Function arguments in JavaScript don’t behave in the same way as function arguments in most other languages A JavaScript function doesn’t care how many arguments are passed in, nor does it care about the data types of those arguments Just because you define a function to accept two arguments doesn’t mean you can pass in only two arguments Functions (arguments) Arguments in JavaScript are represented as an array internally The array is always passed to the function in a function call There is an arguments object that can be accessed while inside a function to retrieve the values of each argument that was passed in Functions (arguments) Example: function sayHi() { alert("Hello " + arguments + ", " + arguments); } In this rewritten version of the function, there are no named arguments. The name and message arguments have been removed, yet the function will behave appropriately JavaScript Objects… There are two ways to explicitly create an instance of an Object The first is to use the new operator with the Object constructor like this: var person = new Object(); person.name = "Nicholas"; person.age = 29; JavaScript Objects… The other way is to use object literal notation var person = { name : "Nicholas", age : 29 }; var person = {}; person.name = "Nicholas"; person.age = 29; JavaScript Objects… JavaScript object properties can also be functions – These are called JavaScript methods var person = { name: "Nicholas", age: 29, job: "Software Engineer", sayName: function(){ alert(this.name); } }; var ret = myFunc(person); var myName = person.name; person.sayName(); JavaScript Arrays… Arrays can be created in two basic ways: – The first is to use the Array constructor, as in this line: var colors = new Array(); var colors = new Array(20); var colors = new Array("red", "blue", "green"); JavaScript Arrays… The second way to create an array is by using array literal notation: var colors = ["red", "blue", "green"]; //creates an array with three strings var names = []; //creates an empty array alert(colors.length); //3 alert(names.length); //0 alert(colors.length); Exception Handling Like other C family languages, JavaScript uses the try-catch block to handle exceptions: var num = 10; try { var result = num / num1; } catch (e){ alert(e); } JavaScript String Methods JavaScript has most of the string methods available in other C family languages JavaScript String Methods string.charAt(pos) var name = 'Curly'; var initial = name.charAt(0); // 'C' string.charCodeAt(pos) var name = 'Curly'; var initial = name.charCodeAt(0); //'67' JavaScript String Methods string.indexOf(searchString, position) var text = 'Mississippi'; var p = text.indexOf('ss'); // 2 p = text.indexOf('ss', 3); // 5 p = text.indexOf('ss', 6); // -1 // search from the end of the string p = text.lastIndexOf('ss'); // 5 JavaScript String Methods string.replace(searchvalue, replaceValue) var result = "mother_in_law".replace('_', '-'); // produces mother-in_law… while (result.indexOf('_') != -1) result = "mother_in_law".replace('_', '-'); JavaScript String Methods string.split(separator, limit) var resultArray = "mother_in_law".split('_'); var digits = '0123456789'; var a = digits.split('', 5); // a is ['0','1','2','3', '456789] var ip = '192.168.1.0'; var b = ip.split('.'); // b is ['192','168','1','0'] JavaScript String Methods string.substr(start, length); var result = "mother_in_law".substr(0, 6); // result is 'mother' var myWord = "Hello World"; result = myWord.substr(6, 5); INFO-3168 JavaScript 2 Instructor Information Dr. Ahmed Eltahawi PhD in System Design Engineering, University of Waterloo Current: Senior Data Scientist @ Cosm Medical Inc. Previous: 15+ years experience university level teaching Contact : [email protected] (Answering Emails during 48 hours maximum) Course Framework 2 hours In class: Tuesday: 8:00pm – 10:00pm – Section 2 Thrusday 8:00pm – 10:00pm – Section 1 1 hour asynchronous online: Recording once per week normally a combination of lecture/demonstration Class Regulation I am expecting you: Attend the class No use of cell phone No side talking during class (Not discussion) Be professional in discussion Use appropriate wording Complete any in-class exercises/assignments And - talk to me if you have any unanswered questions Participate in discussion Submit work on-time Contact in advance if an extension needed Assumptions Each student has some experience with basic JavaScript programming concepts: Creating variables Sequence, selection and iteration Basic HTML controls and using JavaScript to handle control events Basic CSS Basic JSON Course Content Review HTML/CSS/JavaScript/Controls/Event handling JavaScript Objects and Methods Arrays and String handling Working with JSON on the web ES6 JavaScript Collections (Sets), Maps, Classes, Arrow Functions Node.js Resources JavaScript textbook (optional) Mark Meyers (from semester 1) Resources JavaScript textbook (optional) https://eloquentjavascript.net Marijn Haverbeke Free (PDF) Software Visual studio code https://code.visualstudio.com/download Notepad++ Chrome browser Jetbrains.com / Visual Studio Resources https://www.w3schools.com https://stackoverflow.com/ https://insights.stackoverflow.com/survey/2021 Evaluation Midterm Test (Quiz) – 20% - Online on class time Final Test (Quiz) – 20% Projects – 40% 2 Projects (see drop box list for due dates) Labs – 20% 5 labs, each worth 4% Evaluation Tests will be done during weekly scheduled class times Dates will be posted on FOL Projects are made available as PDF project descriptions and will be due as specified Labs are intended to develop specific skill sets Each lab will be made available: Fridays Each lab will be due: Tuesday At 11:59 pm Content Delivery Framework Published content “artifacts” will be uploaded to the following FOL folders as required each week: – Slides – Examples – Labs – Projects – Schedule – Recordings Content Delivery Framework In addition, all content artifacts for a given week will be published in a weekly folder on FOL – For Example: – Week 1 – Week 2 – … INFO-3168 JavaScript Objects (Introduction) Basic Concepts The simple types of JavaScript are numbers, strings, booleans, null and undefined All other values are objects including functions, arrays and regular expressions An object is a container of properties, where a property has a name and a value Objects in languages like Java or C# are normally derived from classes however in pre-ES6 JavaScript, objects are class-free Object Literals var emptyObject = {}; var stooge = { firstName: "Joe", lastName: "Howard" }; Object Literals (continued) var flight = { airline: “Oceanic”, number: 815, departure: { IATA: “SYD”, time: “2004-09-22 14:55”, city: “Sydney” }, arrival: { IATA: “LAX”, time: “2004-09-23 10:42”, city: “Los Angeles” Retrieval var myTest = stooge.firstName; // "Joe" myTest = flight.departure.IATA; // "SYD" myTest = stooge.middleName; // undefined myTest = flight.status; // undefined myTest = stooge.FIRSTNAME; // undefined myTest = flight.equipment; // undefined Update A value in an object can be updated by assignment stooge.firstName = 'Jerome'; If the object does not already have the property name, the property name is added to the object stooge.nickName = 'Curly'; Reference Objects are passed around by reference, they are never copied var x = stooge; x.nickname = 'Curly'; var nick = stooge.nickname; // nick is 'Curly' because x and stooge // are references to the same object. JavaScript Methods  JavaScript object properties can also be functions  These are called JavaScript methods var person = { name: “Nicholas”, age: 29, job: “Software Engineer”, sayName: function(){ alert(this.name); } }; var myName = person.name; person.sayName(); Constructor Pattern Constructors are a special kind of JavaScript function used to create objects function PersonType(name, age, job){ this.name = name; this.age = age; this.job = job; } var person1 = new PersonType(“Jimbo”, 29, “Teacher”); var person2 = new PersonType(“Greg”, 27, “Doctor”); Function Declaration vs Function Expression function sum(a, b) { return a + b; } var sum = function(a, b) { return a + b; } INFO-3168 UI Control and Animation JavaScript UI Event Model As we’ve seen, working with JavaScript within the browser, involves setting up functions as event handlers to be called when the corresponding events happen This generally works well, but what happens if our JavaScript code needs to do a lot of processing as part of handling an event Unfortunately, JavaScript will prioritize your processing at the expense of updating the UI or handling keystrokes and mouse clicks JavaScript UI Event Model The result of prioritizing code execution over UI, is that in some cases, your page will appear to freeze until the processing is complete In order to see what this problem leads to, download and run: UIDemo1.html UIDemo1.html UIDemo1.html Run the page using the browser of your choice and notice that when you click the “Start Processing” button, everything on the page freezes Even though the code on lines 24 and 25 should be updating the data in the two top text boxes, this isn’t happening In addition, it’s impossible to enter anything into any of the text boxes setTimeout() In order to deal with the JavaScript situation where all the processing is being consumed by the execution of JavaScript, we have the setTimeout() “setTimeout” allows you to designate a function to execute at some point in the future Prior to the expiration of the specified time, all execution cycles will be allocated to the UI Example: setTimeout(myFunc, 1000); Wait 1 second (1000 milliseconds) and then call the function myFunc setTimeout() This might not seem that useful but if we use short time spans (like 5 milliseconds for example), we can set up “loops” using recursion where we can do our processing and at the same time allocate time for the UI to be updated; i.e. have the pending events get processed Recursion is the programming strategy of having a function call itself in order to simulate loop processing In order to demonstrate the use of setTimeout() download UIDemo2.html UIDemo2.html UIDemo2.html Notice on lines 34 and 35, we check the value of “done” and then use setTimeout(innerLoop, 5) to call itself (after waiting 5 milliseconds) 5 milliseconds may not sound like much but it’s long enough to allow the user interface to process any pending events such as assigning values to text boxes or processing keystrokes Animation with JavaScript setTimeout() can also be used to perform basic animations To illustrate this concept, see the BounceBall.html example BounceBall.html This page moves the image of a basketball around the inside of a container bouncing it off the walls The code is involved but generally follows practices just discussed including the use of setTimeout() to call a function recursively BounceBall.html INFO-3114 AJAX with JSON and Other Stuff URLs URL format http://www.mysite.com/specials/saw-blade.gif Protocol : http:// Internet address : www.mysite.com Name of resource : /specials/saw-blade.gif Basic HTTP HTTP commands are called methods GET Requests a representation of the specified resource Most requests on the web are HTTP GET requests POST Submits data to be processed to the identified resource The data is included in the body of the request PUT Uploads a representation of the specified resource DELETE Delete the named resource from a server JSON JavaScript Object Notation Easy way to store and transport JavaScript object data as strings Example: var stooge = { firstName: "Joe", lastName: "Howard", nickName: "Curly", weight: 220 }; // as JSON {"firstName":"Joe","lastName":"Howard","nickName":"Curly","weight":220} JSON (continued) Most firewalls on the Internet will allow by default HTTP GET and POST requests so long as the data is in string format JSON is the perfect option for sending or receiving data on the web, because it represents everything in string format As well, it’s really easy to convert JSON data to and from JavaScript objects Converting JSON and JavaScript Converting from JavaScript objects to JSON and JSON strings back to JavaScript objects JavaScript to JSON: var stoogeJSON = JSON.stringify(stooge); // assuming stooge is a JS object JSON to JavaScript: var stooge = JSON.parse(stoogeJSON); AJAX Asynchronous JavaScript And Xml Provides the ability to issue asynchronous calls from a client browser to code running on a web server and receive data in return through a callback to an event handler Not usually in XML format any more (almost always JSON format now) What is asynchronous? During the period of time between the sending of the request and the response being returned, the browser (and the user) are free to continue working; i.e. no wait Most AJAX calls take a couple of seconds or less It’s also possible to issue synchronous calls During a synchronous call, the JavaScript code will wait for the answer to come back Simple AJAX We can do simple AJAX calls from any browser using something called XMLHttpRequest Every browser supports this and it lets us issue an HTTP request (usually GET or POST) to a web site Despite the name, we’re rarely expecting to get XML data back from the request These days it’s usually JSON data Simple AJAX (synchronous) Send Request: Create a new XMLHttpRequest object Open a connection with the URL Send the request Listen for the response Simple AJAX (asynchronous) Response status: 404 failure 200 success Wikipedia Site Example The Wikipedia is a more involved (and more useful) example of utilizing raw JSON data from a website API Try out the attached web pages called WikiDemo1.html and WikiDemo2.html Step through the code with Google Chrome to see how they work Also see: https://www.mediawiki.org/wiki/API:Search Working with JSON Often the JSON returned from web servers is completely unformatted and therefore difficult to interpret visually This problem can be somewhat resolved by using the resources of a web site called JSON Lint https://jsonlint.com/ Unformatted JSON can be pasted into the site display window and then reformatted based on the structure of the JSON code being analyzed Working with JSON Working with JSON Working with JSON INFO-3168 ECMA 6 - Features Introduction ECMA – European Computer Manufacturer’s Association – Standards group ECMAScript is a trademarked scripting-language specification standardized by Ecma International in ECMA-262 and ISO/IEC 16262 – Used for client-side scripting on the World Wide Web – Also used for writing server applications and services using Node.js JavaScript Versions Version summary Managing browser differences for ECMA support – https://kangax.github.io/compat-table/es6/ – Using shims A “shim” is a software add-in that provides full support (to some level) for a particular software standard Example: Google’s Traceur – ECMAScript 5 The "use strict" Directive String.trim() Array.isArray() Array.forEach() Array.map() Array.filter() Array.reduce() Array.reduceRight() Array.every() Array.some() Array.indexOf() Array.lastIndexOf() JSON.parse() JSON.stringify() Date.now() Property Getters and Setters New Object Property Methods ECMAScript 6 Support for constants Block Scope Arrow Functions Extended Parameter Handling Template Literals Extended Literals Enhanced Object Properties De-structuring Assignment Modules Classes Iterators Generators Collections New built in methods for various classes Promises Github Reference Block Scope using let and const "use strict" if (true){ let i = "testing let"; alert(i); } if (typeof i !== "undefined") { alert(i); } else { alert("Undefined"); } Block Scope using let and const const key = 'abc123'; let points = 50; let winner = false; if(points > 40) { let winner = true } Block Scope using let and const const key = 'abc123'; let points = 50; let winner = false; key = 'abc1234'; // error Block Scope using let and const const person = { name: 'Jimbo', age: 28 } // error person = { name: 'Sherlock' } person.name = 'Sherlock'; // OK Set Collections Sets are ordered lists of values that contain no duplicates. Instead of being indexed like arrays, sets are accessed using keys Sets exist in most other languages – Java, C#, Python One difference between ES6 Sets and those in other languages is that the order matters in ES6 (not so in many other languages) Maps The Map object holds key-value pairs Any value (both objects and primitive values) may be used as either a key or a value Classes Historically, developers used constructor functions to mimic an object-oriented design pattern in JavaScript Classes in JavaScript (introduced with ES6) do not actually offer additional functionality, and are often described as providing "syntactical sugar" over prototypes and inheritance in that they offer a cleaner and more elegant syntax Because other programming languages use classes, the class syntax in JavaScript makes it more straightforward for developers to move between languages Getters and Setters Properties are nouns Methods are verbs What if we could have something that’s a combination of a property and a method? – Use the property in our code as though it was a noun: let x = obj.type; obj.type = “action”; – Implement the property in the class as though it was a verb (method): get type() { return this._type; } set type(newType) { this._type = newType; } Inheritance Concepts at higher levels are more general Concepts at lower levels are more specific (inherit properties of concepts at higher levels) Vehicle Wheeled vehicle Boat Car Bicycle 2-door 4-door Inheritance Book is the “base” class (highest level) TypedBook is the “derived” class (lower level) VersionBook is also a derived class Book TypedBook VersionBook VersionTypedBook Arrow Functions Shorter way of creating simple functions Called Lambdas in other languages such as C# Using this syntax removes some of the features you would be used to having when using a function expression Arrow functions are not named; they can be assigned to a variable but are always anonymous Basic syntax has a set of parentheses that will hold all the parameters like a function expression Next the arrow Then curly braces ({}) that will have the body of the function inside Parentheses are optional only when one parameter is being passed If no parameters are being passed, parentheses are required var myObj = () => ({name:'Jimbo’}); console.log(myObj()); let count = () => ({counter++; console.log(counter)}); count();

Use Quizgecko on...
Browser
Browser