The official name for JavaScript is ECMAScript, often abbreviated "ES"
As with CSS, actually providing specified features depends on the browser.
ES 6 is now supported by most major browsers, and introduces some key language features that are commonly used in React. In particular:
Syntactic Sugar causes cancer of the semicolon
A
shortcut syntax for declaring functions using
=>
//normal function declaration
const foo = function(params) {
return 'foo '+params;
}
//arrow function declaration (block body)
const foo = (params) => {
return 'foo '+params;
}
//arrow function declaration (concise body)
const foo = (params) => 'foo '+params;
single expression implies return
//arrow function declaration (concise, no params)
const sayHello = () => console.log('Hello world!');
anonymous function assigned to a variable
Arrow functions are particularly nice for anonymous callback functions (literals), and in fact should always be used.
const array = [1,2,3]; //an array to work with
//normal function
array.map(function(num) {
return num*2; //multiply each item by 2
});
//arrow syntax
array.map((num) => {
return num*2; //multiply each item by 2
});
//concise body - ONLY FOR TINY EXPRESSIONS
//(better to avoid entirely)
array.map((num) => num*2);
const doggy = {
name: "Fido",
bark: () => console.log("woof")
}
/* function declaration */
function myFunction(param1, param2) {
return param1 + param2;
}
/* function literal */
const myFunction = function(param1, param2) {
return param1 + param2;
}
/* arrow function */
const myFunction = (param1, param2) => {
return param1 + param2;
}
/* arrow function (concise body) */
const myFunction = (param1, param2) => param1 + param2;
We now have 4 different ways to write functions. They all have different syntax, but do the same work.
Recommendation: don't use concise body syntax. Always include the explicit block.
/* Do this */
const exclaimed = stringArray.map((aString) => {
return aString + "!!" //add exclamation points
})
/* Do not do this */
const exclaimed = stringArray.map((aString) => aString + "!!")
Destructuring assignment lets you assign (unpack) each value of an array or object into into separate variables in a single operation.
//destructuring arrays
const myArray = [1, 2, 3];
const [x, y, z] = myArray; //myArray elements to `x`, `y`, `z`
console.log(x); //=> 1;
console.log(y); //=> 2;
console.log(z); //=> 3;
//destructuring objects
const myObject = {a: 1, b: 2, c: 3};
const {a, b, c} = myObject; //myObject.a to a, etc.
console.log(a); //=> 1
console.log(b); //=> 2;
console.log(c); //=> 3;
It's possible to destructure function parameters. This is commonly used in React (with object params)... but can make code maintenance harder.
//an example person object
const person = {name: 'Ada', height: 64, weight: 135}
//a function that expects a person object
function getBMI(personObj) {
const height = person.height;
const weight = person.weight;
return 703*weight/(height*height);
}
const adaBMI = getBMI(person);
//implicit
const personObj = {
name: 'Ada', height: 64, weight: 135
}
//implicit - destructured
const {height, weight} = {
name: 'Ada', height: 64, weight: 135
}
//an example person object
const person = {name: 'Ada', height: 64, weight: 135}
//a function that expects a person object
function getBMI({height, weight}) {
return 703*weight/(height*height);
}
const adaBMI = getBMI(person);
/* standard argument */
function getFullName(personObj) {
return personObj.first + " " + personObj.last;
}
/* destructured argument */
function getFullName({first, last}) {
return first + " " + last;
}
We now have 2 different ways to write function arguments. They all have different syntax, but do the same work.
const originalArray = ['a', 'b', 'c', 'd'];
const newArray = [...originalArray, 'e', 'f'];
console.log(newArray) //['a', 'b', 'c', 'd', 'e', 'f']
The spread operator ...
lets you reference "the elements of" an array or object when declaring a new value. This is particularly useful for duplicating arrays or objects.
const person = {name: 'Ada', height: 64, weight: 135}
const copyOfPerson = {...person}; //clone an object!
console.log(person === copyOfPerson); //false! different objects!
//all off the properties are "spread" into the new object
const personWithHat = {hat: 'bowler', ...person}
console.log(person); //has name, height, weight
console.log(personWithHat); //has name, height, weight, hat
think: "the elements of original array"
Modules are self-contained, isolated scripts that are able to run in their own namespace (without polluting the global environment). Modules can export values that may be imported and used by other modules.
Web pages load modules by including a script
tag with the type="module"
attribute.
<!-- load a script as a module -->
<script type="module" src="path/to/module.js"></script>
cd path/to/project
npx live-server .
where index.html is!
dot to serve entire folder
When an HTML page is opened with the file:// protocol, JavaScript cannot access system files. You need to run a local web server instead to use the http:// protocol.
You can do this with the live-server package
Access the webpage at http://localhost:8080/index.html
Stop the server by using ctrl+c in the command shell.
It is "possible" to import external libraries and make them available in your script from JavaScript (not HTML)
const util = require('util');
node version of "import"
global to refer
to the library
module library name
import { ArrayList } from 'util'; //named import
module library name
import java.util.ArrayList;
module name
variable to import
variable to import
export
variables, functions, and classes to be available for other modules to
import
.
/*** my-module.js ***/
export function foo() { return 'foo'; } //named export
export const bar = "bar"; //export a variable
//will not be available (a "private" function)
function baz() { return 'baz'; }
/*** index.js ***/
//example of named imports:
import {foo} from './my-module.js'; //single named import
import {foo, bar} from './my-module.js'; //multiple named import
foo() //=> 'foo'
console.log(bar) //=> 'bar'
relative path to file (start with ./)
.js extension will be implied by default in Node
Use the as keyword to "alias" a value.
Use import * syntax to import all values from a module.
/*** my-module.js ***/
export function foo() { return 'foo'; } //"named" export
//provide an "alias" (consumer name) for value
export { bar as yourBar };
/*** index.js ***/
import { yourBar } from './my-module.js'; //import value by name
yourBar() //=> 'bar'
import { bar } from './my-module.js'; //error, no value `bar` exported
//provide "alias" for value when importing!
import {foo as myFoo} from './my-module.js';
myFoo(); //=> 'foo'
//import everything that was exported
//loads as a single object with values as properties
import * as theModule from './my-module.js';
theModule.foo(); //=> 'foo'
theModule.yourBar(); //=> 'bar'
Each module can have a single default export, which provides a shortcut when importing.
/*** my-module.js ***/
export default function sayHello() {
return 'Hello world!';
}
/*** index.js ***/
//default import can assign own alias without needing name!
//think: "import {default as greet} from './mymodule.js'"
import greet from './my-module.js';
greet(); //=> "Hello world!"
Be careful about whether an export is named or default!
External libraries especially are not consistent.
Complete task list for Week 6 (items 1-6)
May need to catch up with videos)
Read: Chapter 15: Introduction to React
Problem Set 06 due Friday
This one is bigger and challenging (problem-c especially)!
Will also want to start Problem Set 07 this week
Next: React!
/*** module.js ***/
export function foo() { console.log('foo') }
export function bar() { console.log('bar') }
export default function baz() { console.log('baz') }
/*** index.js ***/
/* A */
import bar from './module.js';
/* B */
import { bar } from './module.js';
/* C */
import * as bar from './module.js';
/* D */
import { * as bar } from './module.js';
//call bar to print "bar"
bar();