Uploaded by nanyu.ding2000

js notes

advertisement
let, const, var diff in javascript
scope:

var: global

let, const: block
Reassign value:

var, let: allowed

const: not allowed. But its properties can be changed.
If accessed before declare:

let, const: Ref error

var: undefined
let str = "Hello";
let str2 = 'Single quotes are ok too';
let phrase = `can embed another ${str}`;
In JavaScript, there are 3 types of quotes.
1. Double quotes: "Hello".
2. Single quotes: 'Hello'.
3. Backticks: `Hello`.
alert
shows a message.
alert("Hello");
prompt
shows a message asking the user to input text. It returns the text or, if
Cancel button or Esc is clicked, null.
let age = prompt('How old are you?', 100);
alert(`You are ${age} years old!`); // You are 100 years
old!
confirm
shows a message and waits for the user to press “OK” or “Cancel”. It
returns true for OK and false for Cancel/ Esc .
let isBoss = confirm("Are you the boss?");
alert( isBoss ); // true if OK is pressed
Conditional operator ‘?’
let result = condition ? value1 : value2;
if condition = true, result = value1, if false, result = value2
Nullish coalescing operator '??'
The result of a ?? b is:

if a is defined, then a,

if a isn’t defined, then b.
Javascript functions
Functions are regular values in javascript
Eg:
function showMessage(from, text) { // parameters: from, text
alert(from + ': ' + text);
}
Setting default values:
Text = no text given when parameter text was not specified.
But always make ur default param come the last. Or js would not know which one is
missing.
function showMessage(from, text = "no text given") {
alert( from + ": " + text );
}
showMessage("Ann"); // Ann: no text given
Function is a value and can be printed out with alert.
function sayHi() {
alert( "Hello" );
}
alert( sayHi ); // shows the function code
We can copy a function to another variable:
function sayHi() {
alert( "Hello" );
}
// (1) create
let func = sayHi;
// (2) copy
func(); // Hello
sayHi(); // Hello
it)
// (3) run the copy (it works)!
//
this still works too (why wouldn't
anonymous function
Anonymous Function is a function that does not have any name
associated with it.
eg:
function(parameter) {
// Function Body
}
Function properties
1. name
is the name of the function
function sayHi() {
alert("Hi");
}
alert(sayHi.name); // returns sayHi
2. length
The number of function parameters
function f2(a, b) {}
function many(a, b, ...more) {}
alert(f2.length); // 2
alert(many.length); // 2
3. Custom properties
We can also add properties of our own.
Here we add the counter property to track the total calls count:
function sayHi() {
alert("Hi");
// let's count how many times we run
sayHi.counter++;
}
sayHi.counter = 0; // initial value
sayHi(); // Hi
sayHi(); // Hi
alert( `Called ${sayHi.counter} times` ); // Called 2 times
Callback functions
Functions can be used as parameters!!!!!
question
Text of the question
yes
Function to run if the answer is “Yes”
no
Function to run if the answer is “No”
The function should ask the question and, depending on the user’s answer,
call yes() or no():
function ask(question, yes, no) {
if (confirm(question)) {
yes();
}
else {
no();
}
}
function showOk() {
alert( "You agreed." );
}
function showCancel() {
alert( "You canceled the execution." );
}
// usage: functions showOk, showCancel are passed as arguments
to ask
ask("Do you agree?", showOk, showCancel);
Function declaration vs function
expression

Function Declaration: a function, declared as a separate statement, in
the main code flow.




// Function Declaration
function sum(a, b) {
return a + b;
}
Function Expression: a function, created inside an expression or inside
another syntax construct. Here, the function is created at the right side
of the “assignment expression” =:

A Function Expression is created when the execution reaches it and is usable
only from that moment.

// Function Expression
let sum = function(a, b) {
return a + b;
};


Strict mode stuff:
https://javascript.info/functionexpressions#:~:text=In%20strict%20mode%2C%20when%20a%20Function%20Declarat
ion%20is%20within%20a%20code%20block%2C%20it%E2%80%99s%20visible%20eve
rywhere%20inside%20that%20block.%20But%20not%20outside%20of%20it.
Arrow functions
Arrow functions are handy for one-liners. They come in two flavors:
1. Without curly braces: (...args) => expression – the right side is an
expression: the function evaluates it and returns the result.
2. With curly braces: (...args) => { body } – brackets allow us to
write multiple statements inside the function, but we need an
explicit return to return something.
Type 1:
let double = n => n * 2;
// roughly the same as: let double = function(n) { return n *
2 }
Type 2: multiple lines
let sum = (a, b) => { // the curly brace opens a multiline
function
let result = a + b;
return result; // if we use curly braces, then we need an
explicit "return"
};
“this” in arrow functions vs in regular functions
In regular functions the this keyword represented the object that
called the function, which could be the window, the document, a
button or whatever.
With arrow functions the this keyword always represents the
object(the scope!) that defined the arrow function. Eg, if “this” defined
in a property of an object, in a arrow function, and is called from
object.function(), “this” will be the window, not the object.
So, don’t use ‘this’ in arrow functions.
Javascript object
Basic eg:
let user = {
name: "John",
age: 30,
"likes birds": true
quoted
};
// multiword property name must be
Alert(user.name); //John
Add new properties:
user.isAdmin = true;
remove a property:
delete user.age;
Square brakets:
alert(user[“likes birds”]);
Square brackets also provide a way to obtain the property name as the result
of any expression – as opposed to a literal string – like from a variable as
follows:
let key = "likes birds";
// same as user["likes birds"] = true;
user[key] = true;
Computed properties
We can use square brackets in an object literal, when creating an object. That’s
called computed properties.
For instance:
let fruit = prompt("Which fruit to buy?", "apple");
let bag = {
[fruit]: 5, // the name of the property is taken from the
variable fruit
};
alert( bag.apple ); // 5 if fruit="apple"
Property value shorthand
In real code we often use existing variables as values for property names.
For instance:
function makeUser(name, age) {
return {
name: name,
age: age,
// ...other properties
};
}
let user = makeUser("John", 30);
alert(user.name); // John
Property existence test, “in” operator
let user = { name: "John", age: 30 };
alert( "age" in user ); // true, user.age exists
alert( "blabla" in user ); // false, user.blabla doesn't exist
The “for…in” loop
To walk over all keys of an object(use for…in for array will result in returning
array index like 0,1,2), there exists a special form of the loop: for..in. This is
a completely different thing from the for(;;) construct that we studied
before.
The syntax:
for (key in object) {
// executes the body for each key among object properties
}
The “for…of” loop
Walks over all values of an object, not the keys like “for…in”
Object.assign
Object.assign(dest, [src1, src2, src3...])
Copy all source objects into the destination.
let user = { name: "John" };
let permissions1 = { canView: true };
let permissions2 = { canEdit: true };
// copies all properties from permissions1 and permissions2
into user
Object.assign(user, permissions1, permissions2);
// now user = { name: "John", canView: true, canEdit: true }
Functions in objects & ‘this’:
let user = {
name: "John",
age: 30,
sayHi() {
// "this" is the "current object"
alert(this.name);
},
Sayhello: function(){
alert(‘hello’);
}
};
user.sayHi(); // John
‘this’ is evaluated during run time
let user = { name: "John" };
let admin = { name: "Admin" };
function sayHi() {
alert( this.name );
}
// use the same function in two objects
user.f = sayHi;
admin.f = sayHi;
// these calls have different this
// "this" inside the function is the object "before the dot"
user.f(); // John (this == user)
admin.f(); // Admin (this == admin)
admin['f'](); // Admin (dot or square brackets access the
method – doesn't matter)
Constructor function
Constructor functions technically are regular functions. There are two
conventions though:
1. They are named with capital letter first.
2. They should be executed only with "new" operator.
For instance:
function User(name) {
this.name = name;
this.isAdmin = false;
}
let user = new User("Jack");
alert(user.name); // Jack
alert(user.isAdmin); // false
Javascript array:
forEach and for...of
Arr.forEach(function)
Or use:
for(let element of arr){
}
The for…of is used more often.
Map
Create new array by processing each element of the existing array. Just like map in
Haskell.
let result = arr.map(function(item, index, array) {
// returns the new value instead of item
});
setTimeout vs setInterval
setTimeout:
方框的意思是 optional
var timeoutID = setTimeout(function[, delay, arg1, arg2, ...]);
var timeoutID = setTimeout(function[, delay]);
timeoutID can be used to cancel this operation by
clearTimeout(timeoutID).
function is executed after (delay) miliseconds.
Arg1, arg2 etc are extra arguments to put in function.
setInterval:
var intervalID = setInterval(func, [delay, arg1, arg2, ...]);
var intervalID = setInterval(function[, delay]);
Just like setTimeout, but function is executed EVERY (delay) miliseconds unless
canceled by clearInterval(intervalID)
Filter(array method)
The filter() method creates a new array with all elements that pass the test
implemented by the provided function.
Eg:
const result = arr.filter((element)=> element.length > 6);
every vs some(array method)
every: returns Boolean, checks if EVERY element in the array pass the provided function.
Eg:
arr.every((el)=> {
return el > 0;
})
some: similar to every but only checks if SOME elements pass the test
Reduce(array method)
Basically an accumulator from Haskell. The return of function on the inside will become
the “previousValue”(accumulator)
Basic syntax:
Arr.reduce((previousValue, currentValue, currentIndex, array) =>
{ /* ... */ }, initialValue)
Spread
Break an iterable(eg, array, string) down into elements.
Eg:
Console.log(...[“1”, “2”, ”3”])
Will print 1, 2, 3 instead of [“1”,”2”,”3”]
Spread can also be used on objects!
Eg:
Const new_obj = {...obj1, ...obj2};
New_obj will consist of the properties from obj1 and obj2
Rest
Same syntax with spread! (also ...), but different.
The rest parameter syntax allows a function to accept an indefinite number of arguments
as an array.
Eg:
function sum(initial, ...el){
return initial + el.reduce((prevValue, newValue)=>(
prevValue + newValue
), 0)
}
Destructurings arrays
Making elements of arrays into separate objects without manually assigning them one by
one.
Eg:
const arr = [1,2,3,4,5];
const [elem1, elem2, ...everythingElse] = arr;
This will result in elem1 === 1, elem2 ===2, everythingElse ===[3,4,5]
Destructuring objects
Making objects in objects into separate objects.
Eg:
const obj = {
name:"jody",
height: "180",
color: "purple"
}
// the colon : serves a "change name" functionality. || = "red panda"
is a default value
const {name:firstname, height, color:favcolor, race = "red panda"}
= obj;
// now firstname === "jody", height === "180", favcolor ==="purple".
Destruturing params
Just like destruturing objects, but it is done in params.
const obj = {
name: 'John',
surname: 'Smith',
height: 180 }
var sayHello = function({ name, surname }) {
console.log(`Hello ${name} ${surname}! How are you?`);
};
sayHello(obj)
// -> Hello John Smith! How are you?
Download