js introduction

18
JavaScript 2016/12/11, HsinChu, NCTU Takeshi 1

Upload: yi-tseng

Post on 16-Apr-2017

162 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: JS introduction

JavaScript2016/12/11, HsinChu, NCTU

Takeshi

1

Page 2: JS introduction

Outline

• Introduction

• Basic syntax

• Functions

• Useful Data structures/types

2

Page 3: JS introduction

Introduction

• High-level programming language

• Supported by all modern browser/OS

• Frontend (Browser, UI control, …)

• Backend (Server, Application)

• Interpreted programming language

• Weakly typed

3

Page 4: JS introduction

JavaScript is NOT Java

4

Page 5: JS introduction

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

Page 6: JS introduction

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

Page 7: JS introduction

Quick Demo9 x 9 Table

Page 8: JS introduction

Functions (1/3)

• Builtin functions

• Console functions

• eval

• Functions for some specific data structure

• User defined functions

Page 9: JS introduction

Functions (2/3)

• Define a function:

var foo = function (parameters) {

// function content

}

• Call a function:

foo();

Page 10: JS introduction

Functions (3/3)

• Function can be anonymous (and parameter):

executeThisFunctionWithLog(function() {

// do something

});

Page 11: JS introduction

Quick Demosimple functions

Page 12: JS introduction

Callback function (1/2)

• For asynchronous design.

• Call function(s) after something done.

• Won’t block anything

Page 13: JS introduction

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);

Page 14: JS introduction

Quick DemoDo something after 1 second

Page 15: JS introduction

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

});

});

Page 16: JS introduction

Callback hell (2/2)

• To resolve callback hell we can use:

• Async library

• Promise

• async/await syntax (ES7)

Page 17: JS introduction

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;

Page 18: JS introduction

ThanksQuestions?