js introduction
TRANSCRIPT
JavaScript2016/12/11, HsinChu, NCTU
Takeshi
1
Outline
• Introduction
• Basic syntax
• Functions
• Useful Data structures/types
2
Introduction
• High-level programming language
• Supported by all modern browser/OS
• Frontend (Browser, UI control, …)
• Backend (Server, Application)
• Interpreted programming language
• Weakly typed
3
JavaScript is NOT Java
4
Basic syntax (1/2)• define variable(s)
var a = 1;
• Do basic calculation
sum = a + b;
• Loops
for (a=0; a<10; a++) {
// do something cool…
}
5
Basic syntax (2/2)• Print something on console
console.log(“hello world”);
• Everything can stored in a variable
var a = 3.1415926, s = “this is a string”;
var sum = function (a, b) {
return a + b;
}
• If/Else
if (a === 1) {
// do something…..
}
6
Quick Demo9 x 9 Table
Functions (1/3)
• Builtin functions
• Console functions
• eval
• Functions for some specific data structure
• User defined functions
Functions (2/3)
• Define a function:
var foo = function (parameters) {
// function content
}
• Call a function:
foo();
Functions (3/3)
• Function can be anonymous (and parameter):
executeThisFunctionWithLog(function() {
// do something
});
Quick Demosimple functions
Callback function (1/2)
• For asynchronous design.
• Call function(s) after something done.
• Won’t block anything
Callback function (2/2)
• For example, we don’t want to block anything while we are loading some data from API.
var cb = function(result) {
console.log(result);
}
fetchUrl(“https://api.cdnjs.com/libraries“, cb);
Quick DemoDo something after 1 second
Callback hell (1/2)• If we want to call multiple async functions……
fetchApi(“first.api.com”, function(result) {
// do something first and fetch another API
fetchApi(“second.api.com”, function(result) {
// call another async function
});
});
Callback hell (2/2)
• To resolve callback hell we can use:
• Async library
• Promise
• async/await syntax (ES7)
Useful data types• Some useful data types:
// list (array)
var l = [1, 2, “3”, “abc”, {“the”: “map”}];
// map
var m = {“key”: value};
// boolean
var b = true;
ThanksQuestions?