• Home
  • About
    • Artyrie's Blog photo

      Artyrie's Blog

      Artyrie, Ruri

    • Learn More
    • Email
    • Twitter
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

JavaScript Basic

05 Nov 2019

Reading time ~6 minutes

JavaScript

•	This page is my note about javascript.
•	It will be difficult to read.
•	Comment : //

Caution : Ungly English


Data Type

•	JavaScript doesn't have data type.
•	So, non-type language like php.

We can check use function typeof
typeof 5

Number

operator is same to the other lnguage.
There are some function to calculate easily.

•	Math.pow(3,2);       // 9,   3^2
•	Math.round(10.6);    // 11,  rounding off
•	Math.ceil(10.2);      : 11,  rounding up
•	Math.floor(10.6);    : 10,  rounding down
•	Math.sqrt(9);          : 3,   root
•	Math.random();      : random number between 0 - 1.0

String

String is in double quote or single quote.
And It can be merged by operator +

Funtion

•	String.length : length of string

Variable

JavaScript’s declaring variable is var.

Like this.
var a = 5;
var s = "string";

Boolean

•	true
•	false

It is usually used 1 is true and 0 is false.

Null

•	null
•	undefined

Operator

Logical operator

Logical operator is smiliar to the other language.

•	(a == b) : equal, if a = b outwardly (like (1 == '1')), it returns true.
•	(a === b) : perpect equal, if type and value are same perpectly, It returns ture.
•	(a != b) : not, if a and b are different, It returns true.
•	(a !== b) : not equal, same to eqaul
•	inequality : <, >, <=, >=
•	(a && b) : and
•	(a || b) : or
•	(!a) : not

It is better to use 3 equal for purpose that checking equal.

There are many alternative false

•	undefined
•	0
•	undefined variable
•	null
•	NaN : 0 divided error

Basic Syntax

Conditional

if(true){
    alert(1);
} else {
    alert(2);
}

It is not different to other language.

Repetition : while

while (conditional){
    repetition code
}

Repetition : For

for(var i = 0; i < 10; i++){
    document.write('coding everybody'+i+'<br />');
}

Structure of For
for(Initialize variable; conditional; repeat something){
repetition code
}

Control of Repetition

•	break : Escape repetition immediately
•	continue : doens't execute repeat code after continue and move back
•	where starting point that begins repetition code again with next
•	repetition code and conditional.
for(var i = 0; i < 10; i++){
    if (i === 5) {
        continue
    }
    document.write(i);
}

This code doesn’t write 5, because of continue.

Declare function

function functionName( arg ){
   Code
   return value;
}

It is simple way to declare function.

var numbering = function (){
    i = 0;
    while(i < 10){
        document.write(i);
        i += 1;
    }   
}
numbering();

It is the other way to declare function.
function can be defined by variable.

Array

defining array and function about array.

var arr = ['val1', 'val2', 'val3'];
arr.length; // length of array.
arr.push(newval); // add value.
arr.concat(newval, newval2); // add multiple value.
arr.unshift(newval); // add value first index.
arr.splice(add index, # of removing, add value); //
arr.shift(); // eliminate first value.
arr.pop(); // eliminate last value.
arr.sort(); // sorting.
arr.reverse(); // sorting by reverse order.

if li = ['a', 'b', 'c', 'd', 'e']; li.unshift('z'); then,
['z', 'a', 'b', 'c', 'd', 'e']
if li = ['a', 'b', 'c', 'd', 'e']; li.splice(2, 1, 'B'); then,
return ['c'] that index 2. and add 'B' in index 2.

Associate Array

var character = {'Seol': 228, 'Artyrie': 220, 'Bella': 209};
character["Seol"] // => 228
character.Seol // => 228

for (key in character) {
    document.write("key : " + key); // show key like a Seol.
}

It is like a hash in java.

Function in Object

var character = {
    'list': {'Seol': 228, 'Artyrie': 220, 'Bella': 209},
    'show' : function () {
        for(var name in this.list) {
            document.write(name+" : "+this.list[name]+"<br />");
        }
    }
};

‘list’ is key, {‘Seol’: 228, ‘Artyrie’: 220, ‘Bella’: 209} is value.
key can have object and also function.
if you want to get value that ‘Seol’ has, call like this.
character['list']['Seol'];

function ‘show’ can be called by this way.

character['show']();
character.show();

Advanced Javascript

Module

•	Module is made to recycle code and maintain easily.
•	Pure JavaScript doens't have Module.

These are hello.js and index.html

function hello(){
    return 'Hello world';
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <script src="hello.js"></script>
</head>
<body>
    <script>
        alert(hello());
    </script>
</body>
</html>

This is modulization.

Library

Library is similar to Module.
Library is collection of well arranged code like jQuery

How to use Library?

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
    <ul id="list">
        <li>empty</li>
        <li>empty</li>
        <li>empty</li>
        <li>empty</li>
    </ul>
    <input id="execute_btn" type="button" value="execute" />
    <script type="text/javascript">
     $('#execute_btn').click(function(){
        $('#list li').text('coding everybody');
     })
    </script>
</body>
</html>

This is same to next code.

<!DOCTYPE html>
<html>
<body>
    <ul id="list">
        <li>empty</li>
        <li>empty</li>
        <li>empty</li>
        <li>empty</li>
    </ul>
    <input id="execute_btn" type="button" value="execute" />
    <script type="text/javascript">
    function addEvent(target, eventType,eventHandler, useCapture) {
        if (target.addEventListener) { // W3C DOM
            target.addEventListener(eventType,eventHandler,useCapture?useCapture:false);
        } else if (target.attachEvent) {  // IE DOM
            var r = target.attachEvent("on"+eventType, eventHandler);
        }
    }
    function clickHandler(event) {
        var nav = document.getElementById('list');
        for(var i = 0; i < nav.childNodes.length; i++) {
            var child = nav.childNodes[i];
            if(child.nodeType==3)
                continue;
            child.innerText = 'Coding everybody';
        }
    }
    addEvent(document.getElementById('execute_btn'), 'click', clickHandler);
    </script>
</body>
</html>

API

Application Programming Interface (API)
It controls environment where program works
and that provided by envrionment.
It is expressed by function, input, output and data type of software
component(function, method, operation, ect)

It is different to User Interface. (UI)

These are API document for JavaScript

ECMAScript
생활코딩
JavaScript Reference (MDN)
JScript Reference (MSDN)


These are API document by host type that JavaScript works.

Web browser API
nodejs API

Generics

See regex structure on picture
See Regex what text matches

Literal
var pattern = /a/

Object generator
var pattern = new RegExp('a');

var pattern = new RegExp('a');
console.log(pattern.exec('abcdef')); // return array that RegExp ["a"]
cnosole.log(pattern.test('bcdefg')); // return boolean value false
// this is string method for generics
console.log('abcdef'.match(pattern)); // ["a"]
console.log('abcdef'.replace(pattern, 'A'));  // Abcdef

Gernerics has some options.

•	/a/ : normal
•	/a/i : doesn't distinguish capital letter.
•	/a/g : return all of result.

See selab lecture note.

var og = /a/g;
console.log("abcdea".match(og)); // ["a", "a"]
var pattern = /(\w+)\s(\w+)/;
var str = "coding everybody";
var result = str.replace(pattern, "$2, $1");
// $2 : in pattern, 2nd group. -> after '\s' : (\w+)
// $ can be possible to recycle matching in pattern like a variable.
console.log(result); // everybody, coding
var urlPattern = /\b(?:https?):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*/gim;
var content = '생활코딩 : http://opentutorials.org/course/1 입니다.;
var result = content.replace(urlPattern, function(url){
    // when you find urlPattern, call 2nd parameter function in replace. 
    // where is url from? when urlPattern is matched, transfer to function
    // that is 1st parameter url.
    return '<a href="'+url+'">'+url+'</a>';
});
console.log(result); // 생활코딩 : <a href="http://opentutorials.org/course/1">http://opentutorials.org/course/1</a> 입니다.

Web Page

document

•	document.write('String'); : Write String on web page.


Java Script Share Tweet +1