0% found this document useful (0 votes)
22 views47 pages

DevX JS - W5C13 - Modern Syntax.pptx

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views47 pages

DevX JS - W5C13 - Modern Syntax.pptx

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Javascript

Modern Syntax
Review
Review
● jQuery ● jQuery
○ Libraries ○ setters/getters & set/get in CSS
○ Importing jQuery ○ Display and Fade
○ jQuery, jQuery vs Vanilla JS ○ Event Listeners
○ jQuery syntax and $(selector) ○ AJAX
○ method chains ○ Refactoring
○ html/text/val methods
Modern Syntax
Modern Syntax
There are many ways to write code.

As a beginner I recommend that you learn one way to do things, and learn it well. Once you
understand one way to write code, you can start looking into different or better ways to do it.

This lesson will cover some of those other ways of writing code. You don’t need to master
them now! You should be familiar with these before working professionally, as you may see
code written in many different ways..

For the remainder of the course, feel free to use them. If you are comfortable with one way of
writing your code, try using this other styles.
ES2020
ES2020
ES stands for Ecma Script. This is a name given to a Javascript standard. JS is used by many
browsers and other environments, and they must be kept to ES standard. This allows for JS to
be consistent everywhere.

Standards change in small ways every year or two years. Some of those changes are small but
insignificant, others are small but significant. It is wise to pay attention to these changes.

Sometimes new operators and operations are added.

More often new core functions are added for data types.
Var?
const arr = [1, 2, 3, 4, 5];

Var?
const arr2 = [6, 7, 8, 9, 10];
const bothArr = [...arr, ...arr2];

We have not yet talked about TWO other


ways to declare variables. (You may have let obj = {
seen them online. name: "Zintis",
role: "Teacher"
Let and Const }
let obj2 = {
location: "USA",
students: ["Bob", "Kim", "Sam"]
}
let bothObj = {
...obj,
...obj2
}
const arr = [1, 2, 3, 4, 5];

Const
const arr2 = [6, 7, 8, 9, 10];
const bothArr = [...arr, ...arr2];

Const is like var. Use it to declare a variable.


const obj = {
1. It MUST be set (cannot be empty) name: "Zintis",
2. And that value cannot change. role: "Teacher"
}
This means ‘const’ prevents any (accidental) const obj2 = {
variable changes. location: "USA",
students: ["Bob", "Kim", "Sam"]
}
const bothObj = {
...obj,
...obj2
}
for(var x = 0; x < 3; x++){

Let setTimeout(() => {


console.log(x)
‘Let’ is even more like ‘var’. Modern web }, 1000);
developers usually use ‘let’ when a variable }
value should allow updates.

‘Let’ differs from ‘var’ in a very subtle way: for(let y = 0; y < 3; y++){
‘Let’s declaration is “block scoped”. setTimeout(() => {
console.log(y)
In the above example, “var” x gets read 1
second later, and each timeout see’s the }, 2000);
LAST value of x… 3. }

In the “let”, y is declared and scoped to that


block, so each timeout uses only that copy
of y. This is very subtle! Don’t worry if it’s confusing!
Spread …
var arr = [1, 2, 3, 4, 5];

Spread …
var arr2 = [6, 7, 8, 9, 10];
var bothArr = [...arr, ...arr2];

The Spread Operator looks like three dots


(...) var obj = {
name: "Zintis",
It means: “Put these in there” role: "Teacher"
}
It works for arrays, objects, and function var obj2 = {
arguments. location: "USA",
students: ["Bob", "Kim", "Sam"]
Notice how we can use it to combine two
}
arrays, or two objects. (You could combine
var bothObj = {
more!)
...obj,
...obj2
}
Spread Operator
var fruits = ["apple", "orange"];

Spread Operator
var berries = ["grape", "cherry",
"raspberry"];

1. Copy the code on the right.


var fruitJuiceFlavors;
2. Make the undefined variables have
console.log(fruitJuiceFlavors);
matching names.
3. Use the spread operator to assign
“fruitJuiceFlavors” and var vegetables = ["celery", "potato",
“ingredientsForDinner”. "onion"];
var meat = ["chicken", "pork", "beef"];
var spices = ["garlic", "cumin",
"pepper"];

var ingredientsForDinner;
console.log(ingredientsForDinner);
Spread with
Functions
Spread With Functions
Functions can also use the spread (...)
operator. function manyArgs(...args) {
console.log(args);
Spread operators can go in function }
parameters. But they only work as the last
parameter. manyArgs(1, 2, 3, 1, 2, 3);

When used, all arguments after the defined function makeClass(teacher, ...students) {
ones will be placed in that parameter, as an console.log(`${teacher} says hi to
array. ${students.join(" and ")}`);
}

makeClass("Zintis", "Sam", "Kat", "Bill");


Shorthand
Shorthand
So far we have learned one way to write in Javascript.

There are many ways to write the same code. JS has multiple ways of expressing the same ideas.

var a = 5; var a = 5, b = 6;
var b = 6; if(a < b) console.log("banana");
if(a < b){
console.log("banana")
}
Shorthand Logic
Here we see two things: variable declaration with commas, and logical operation without curly
braces.

You can declare multiple variables with comma-separation.

And provided your IF-statement has only one line of code to run, you don’t need curly braces.
(But you do need a line break.)

var a = 5; var a = 5, b = 6;
var b = 6; if(a < b) console.log("banana");
if(a < b){
console.log("banana")
}
Arrow Functions
Arrow Functions
There are 5 (!) ways to write a function in JS.
function double(x){
When we first studied functions we learned return x*2
one way. Now we are more familiar with
}
functions. So we’ll learn the other ways.
var double = function(x){

Each of these functions (named “double”) run return x * 2


the same code… }
var double = (x) => {return x * 2}
var double = x => {return x * 2}
var double = x => x * 2
function anonymous
expression function

Arrow Functions var double = function(x){


return x * 2
Function shorthand includes:
}
1. You can declare an anonymous function arguments arrow body
with an arrow, instead of:
function name(){} var double = (x) => {return x * 2}
2. If you have one argument, you can skip
one argument? no parenthesis
the parenthesis.
3. If you have one return (and no other
var double = x => {return x * 2}
code), you can skip {} and “return”.
4. If you have zero arguments, you still need one return? no braces, no “return” keyword
parenthesis when using arrow functions.
var double = x => x * 2
no argument? still need parenthesis
var get5 = () => 5
Arrow Examples
Arrow functions are often good for anonymous functions. Especially simple ones.

I would recommend writing out a full function when writing functions with a complex purpose,
or more than 3 lines of code.

var names = ["Robert Wilson", "Henry McGill", "Alex Heinz"];


var lastNames = names.map((n) => n.split(" ").pop());
console.log(lastNames);

var testScores = [12, 15, 30, 55, 60, 76, 88, 90, 100, 95, 45, 76, 82];
var passingScores = testScores.filter((s) => s > 50);
console.log(passingScores);
Function Details
Declaration Expression
function double(x){return x*2} var double = function(x){return x * 2}

1. Makes a function. 1. Makes a function.


2. Benefits from “hoisting”. 2. Does NOT use “hoisting”.
a. JS code is read top->bottom. Hoisting a. You must use the function only after
breaks that rule. the expression.
b. You can declare your functions at the
bottom. You can use them earlier in
the code.
Function =>
function double(x){return x*2} var double = (x) => {return x * 2}

1. Binds to scope. 1. Does NOT bind to scope.


2. Can be used as object method. 2. Not good for object method.
3. Can be used as class method. 3. Not good for class method.

Some of these details may be unclear now. Don’t worry, it will become clear later, once you get
more familiar with the internal logic of JS.

Basically, “function” and “=>” are mostly similar, but have slight different operations. There are
a few scenarios where you cannot use “=>” instead of “function”.
And / Or
And / Or
These operators: “&&” and “||” are
known as “and” and “or”. true && “A” = “A”
They are used in logical operations,
such as if-statements.
false && “A” = false
(But technically something else is
happening behind the scenes. The
operator looks at the prior value, and true || “A” = true
then either evaluates TO that value, or
to the NEXT value.)

false || “A” = “A”


And / Or
&& wants to find false, so it skips
true and gives you A
true && “A” = “A”

&& wants to find false, so it gives


you the first false false && “A” = false

|| wants to find truth, so it gives you


the first true
true || “A” = true

|| wants to find truth, so it skips


false and gives you A false || “A” = “A”
Or
With the OR operator “||” it will use the
next value if the prior value is “false”. var n = null;
var zero = 0;
var x = false || null || “banana” var one = 1;
var f = false;
x is “banana” in this example. var t = true;
var noString = "";

OR is very useful for making sure that var string = "banana"


var noArray = [];
variables are always set to a useful data
type. Especially when using things that
var something = zero || false || noArray;
are uncertain, like API calls or user input.
var somethingElse = string || one || zero;
var nothing = zero || noString || false || n;
And
The AND operator is the opposite of OR.
It uses the next value when the prior var n = null;
value is true. var zero = 0;
var one = 1;
So for: var f = false;
var x = true && 1 && “apple”; var t = true;
● x is equal to “apple” in this example. var noString = "";
var string = "banana"
var noArray = [];
var y = “cat” && false && “tree”
● y is equal to false. Since “false” is
var something = one && true && noArray;
false, the && operator stops.
var somethingElse = zero && false && noString;
var nothing = one && string && n;
And/Or Summary
The way I think about this is:

&& wants to fail!


It will give you false when it finds it.

|| wants to succeed!
It will give you true when it finds it.
Object Property
Assignment
Object Property Assignment
There’s also a shorthand for object property
assignment. If you want to assign a variable to var name = "Zintis";
a property that has the same name, you can var location = "USA";
just write the variable name. See (1). var role = "teacher";

This one is pretty good, saves a couple 1 var person = {


name,
keystrokes.
location,
role,
The old way of assigning object properties is };
shown in (2). It may look redundant, but the
first “name” is the property, and the 2nd 2 var person = {

“name” is the variable (value). name: name,


location: location,
role: role,
};
Destructuring
Destructuring Objects
Destructuring is a way to extract and assign
multiple variables from an array or object. // Old way
var name = person.name;
This is just the basics. There is syntax to var location = person.location;
assign default values, or change the name, var role = person.role;
etc… But you’ll need to google that.
// Destructuring
var { name, location, role } = person;
var person = {
name: "Zintis", // Rename, default value
location: "USA", var { name: firstName, location = "none" }
role: "teacher", = person;
};
Destructuring Arrays
Destructuring arrays works like
destructuring objects. var arr = ["Jared", "Derrick", "Sandy"];

Main difference is that you can pick // Old way


any names, and the var firstPlace = arr[0];
first/second/third… values in the var secondPlace = arr[1];
array are assigned to those names. var thirdPlace = arr[2];

You don’t need to assign names to all // Destructuring


values in the array. But you do need var [ firstPlace, secondPlace, thirdPlace ] = arr;
to assign them in order.
Optional Chaining
Operator
Optional Chaining Operator
This operator is only available in
newer version of JS. var person = {
name: {
(It seems to not work on older first: "Zintis",
versions of Node.js) last: "May",
},
It’s used to shorten the syntax status: {

when you are working with role: "teacher",


school: {
unknown data (from API, from file,
name: "DevX",
etc…).
boss: "Askar",
},
},
};
console.log(person?.status?.school?.name);
Switch
Switch
A switch is a fundamental JS
statement. (I don’t like it.) I find var x = 1;
very few cases where it’s the best switch (1) {
choice. case 1:
console.log("ONE");
Basically how it works is …it tests
break;
the switch (argument) against the
case 2:
“cases”.
console.log("TWO");
If the test evaluates as true, it will break;
perform any statements inside the default:
true case. Note: Switch cases console.log("default");
requires a “break” after each case }
operation.
Switch
In this example I took OUT the
break statements. If you var x = 1;
copy/paste this code in your switch (1) {
browser, you will notice that it case 1:
says:
console.log("ONE");
case 2:
console.log("TWO");
default:
The switch statement will run ALL console.log("default");
the code in the cases after the }
match, unless you add break.

Keep that in mind.


Dictionary Objects
Dictionary Objects
In this example, instead of using a
switch to figure out what to do, we var x = 1;
use an object. var dictionary = {
1: "ONE",
Objects can store numbers and
2: "TWO"
strings as keys. So dictionary[x]
}
tries to access the key that is “1”.
console.log(dictionary[x] || "default")
When it does, it finds the value
“ONE” and logs it.

We use an OR operator to handle


the default. But there are other
ways.
Objects In Algorithms
Using objects this way is very important for solving algorithmic problems.

You can study this more later. For now, this brief overview is enough.

Why are objects so good for algorithms:

1. You can only have one of a key.


2. If you try to access a key that doesn’t exist, you get “undefined’.
3. You can overwrite a key with a new value.
4. Checking for an object key is very easy… just obj[key]
Q&A

You might also like