JavaScript 기초

hyunwest·2020년 10월 1일
0

Web Development

목록 보기
1/2
post-thumbnail

09/30/2020

What is JavaScript?

  • 원래는 "LiveScript" 로 불렸다. 이 이름은 브라우저가 스크립트를 요청하고 파싱하는 즉시 실행된다는 점에서 수긍할 만하다.
  • There is no "compile" step in JavaScript. As long as the browser has an Interpreter (a module that parses JS and runs it), you can use JS.

DOM

  • use DOM (Document Object Model) API to read, edit, and delete information inside document. ie, change the web page's content(s).
  • DOM allows JavaScript to know things about the document by "translating" the Markup to something it (JS) can understand.
  • Anything that JS can access through DOM (the document, and all the elements inside it), is called a "node".
  • DOM also provides JS with methods and functions that it can use to access the node(s). (ex: getElementsByTagName, getElementsByClassName, createTextNode, etc.)

<script> Tag

  • async property
    • if you type <script src="script.js" async>, the browser requests script and parses it ASAP. But it also simultaneously parses the rest of the page (html stuff). So adding async to the script tag can help with the delay of seeing the website on the browser from putting the script in the <head> tag, but it won't assure that all the parts of the page corresponding to DOM script will be parsed in time. Thus, only pages that don't use DOM or ones that assure that the document gets loaded before DOM work should be able to use async.
    • you also just don't know which scripts will get run first.
  • defer property
    • just better than async in all the ways. does not allow script to parse until all the DOM parsing is done. also, all the scripts are run in their location order.

However, we honestly don't really need to worry about either properties, because all of these can be solved by just putting the javascript right before the body tag ends. lol.

Side Note: Chrome browser's console is in JavaScript. --> REPL (Read-Eval-Print Loop) pg. 28, 33 in JavaScript for Web Designers

Basic Rules of JavaScript

  • 대소문자 구분
  • In most cases, JS' 내장 메서드는 낙타 대분자 (camel case), 즉 querySelector나 getElementByID와 같이 첫 단어를 제외한 나머지 단어의 첫 글자는 대문자로 하되 hyphen 없이 붙여 쓰는 방식을 사용한다.
  • Syntax: ends with semicolon. tells the JS parser that that is the end of a command.
  • Commenting: /* ... */ --> for block comments (side note: same as CSS).
    // ... --> for one line comments. if your editor is set up with a "soft wrapping" feature, the comment may spill onto the next line but still be considered a single line comment.

Data Types

  • A number type can either be "truthy" or "falsy", but a text type is always "truthy".
  • NaN (Not a Number) itself is actually considered a number. ( ({}+[])[!+[]+!+[]+!] is a valid JS code. lol. )
  • JavaScript is a language of weak typing. That means that a data does not need to be explicitly declared as a number or a string, or any other data type. JS looks at the data itself and then guesses what its type should be, and usually it is correct.

Primitive Type

  • The simplest data forms.
  • number, string, undefined, null, true, false, etc.

1) Number Type

  • can have any number value
  • also includes NaN, Infinity, and -Infinity.
  • Operator Priorities: PEMDAS --> Parenthesis > Exponent > Multiplication > Division > Addition > Subtraction
  • JS returns NaN if you try to treat a non-number as a number. For instance, if you do "Hello, World" * 2, JS will return NaN.

2) String Type

  • anything surrounded by "" or ''
  • in JS, string concatenation is done through the + sign. And you can do this with a string and a number. If there is at least one string element in the operation, JS will treat all the other operants as strings and concatenate them.

3) Undefined

  • anything we or JS did not define.
    ex: typeof(sup) --> undefined. typeof(getElementByID) --> undefined. (since the correct method name is getElementById.)

4) Null

  • "not having a value"
  • it has been defined as something, but there is no value in it.
  • you can assign null to a variable bc you predict it will have a value in the future, or bc you want to get rid of its original value.

5) Boolean Type

  • true or false.

  • something to note: truthy and falsy.

    • 0 is falsy. null, undefined, NaN, and empty string ("") are also falsy.
    • Everything else (string, number, etc.) that has a value are all truthy.
      --> so, if you do

      if (name) { }

    you'll see that (name) is considered true if the name variable is not null. If it's null, or empty, (name) is considered false.

  • == returns true even for comparing 2 and "2". It's a "loose" comparison. "equality operator"

  • ===, onthe other hand, returns true only if they have the same value AND the same data type. "strict equality operator"

Object Type

  • an aggregation of properties and methods.
  • it has its own characteristics, and has functions to do something.
  • basically, you can say that the whole js document is made up of objects.

1) Variables

  • 값을 상징하는 이름.

  • if you do

    var foo; --> JS returns 'undefined'

    you could just say foo = 5; but should always put var anyway.

  • can also make multiple variables with one command by doing var foo = 5, banana = "banana", hi = '5'; instead of putting them all in separate commands with var's and ;'s.

Identifier - name of variable.

  • cannot start with number. can start with normal text, underscore ( _ ), and $ sign.
  • cannot have space in it.
  • cannot include special characters (!.,/+-*=)
  • cannot be keywords (abstract boolean break byte case catch char class const continue debugger default delete do double else enum export extends false final finally float for function goto if implements import in instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var void volatile while with)

Variable Scope

  • Local
    • when you declare a variable using "var" keyword inside a function definition. Then that variable becomes a local variable limited within that function. But if you don't use the var keyword, it becomes a global variable.
  • Global
    • global variables can be accessed/editted anywhere in the entire application.
  • Because of these properties, it is good to always use var when declaring variables inside function definitions, so that we can save the debugging time that would be spent for finding functions that changed a global variable's value.

2) Arrays

  • 변수와 크게 다르지 않지만 목록처럼 여러 개의 값을 가질 수 있다.
    ex: > var myFirstArray = ["item1", "item2"];
    undefined

    or

    ex2: > var myFirstArray = new Array("item1","item2");
    undefined

  • Note: that in JS, spaces do not mean anything. 자바스크립트에서의 공백은 아무런 의미가 없으며 오로지 개인의 취향일 뿐이다. Maybe just keep readability in mind, though.

  • to access each of the values in an array, you do:

    myFirstArray[0];
    "item1"
    myFirstArray[1];
    "item2"

  • To produce an empty array:

    var arrayThree = [];

    or

    var arrayFour = new Array();

  • Note, that in new Array(), you can make an empty array of a specific length.

    var threeItemArray = new Array(3);

    threeItemArray
    [empty x 3]

    (empty means the same as undefined)

  • But, that feature above is probably not that useful. Only confusing cuz what if you want to make an array with numerical values. you may have meant to make an array that is equal to [3], but new Array(3) will create an empty array w/ 3 empty slots. So just use the brackets ([]).

An Array property that is useful to know:

  • .length --> tells you the # of items in an array.

3) Objects and Properties

  • Objects는 여러 개의 값을 Properties라는 형태로 가질 수 있다. 복수의 아이템을 포함하지만 각 아이템에 숫자형 인덱스가 부여되는 배열과는 달리, Object's Properties는 문자열로 된 이름을 가진다.
    ex:
    var myDog = {
    "name" : "Zero".
    "color" : "orange",
    "ageInYears" : 3.5,
    "wellBehaved" : false
    };
    undefined
  • can also have an object as an object's property, like this:
    var myDog = {
    "name" : {
    "first" : "zero",
    "last": "Marquis"
    },
    "color" : "orange"
    };

To define Objects:

  • new keyword: var myDog = new Object();
    • when using this method, you can only set the data inside the Object after creating it first, so for instance,
      var myDog = new Object();
      myDog.nickname = "Falsy";
  • literal notation: var myDog = {};
    • with this method, you can put in the data simultaneously as you create the Object.
    • var myDog = { "nickname" : "Falsy"};
      --> people usually prefer to use the literal notation method.

To access or edit values inside Objects:

  • dot notation
    • ex: myDog.name;
    • with dot notation, you can't expect JS to be able to know that name_var is a variable when it comes after a dot. even if you do var name_var = "name", JS will not understand if you do myDog.name_var. Because JS perceives name_var itself as an identifier for the targetted key.
  • bracket notation
    • ex: myDog[ "name" ];
    • in bracket notation, you can do myDog[ name_var ] and it will work just fine.

4) Functions

  • good for when you need to repeat a block of code a lot.
  • to set up a function in JS:

    var whatup = function() {
    console.log( "Hello again, world." );
    }
    undefined

  • then if you do whatup; on JS console, it will spit back the function definition, and if you do whatup();, then it will run the function.
  • In JS, if you make a function with an argument, and you don't give it any value, like greet();, JS will make the function argument to have the value undefined.

Note: almost everything in JS is an Object. Pretty much everything except for null and undefined. Even strings are considered Objects, and you can do "test".length and it will return 4.

0개의 댓글