[The Modern JavaScript] The JavaScript language - JavaScript Fundamentals 1

둡둡·2022년 12월 19일
0

Modern-JavaScript

목록 보기
2/10

Hello, world!

The "script" tag

  • <script> tag can insert anywhere into an HTML document

Modern markup

  • The <type>, <language> attribute, comments inside <script> tags
    • there are not required, and rarely used nowadays

External scripts

<script src=".../script.js"></script>
  • A script in an external file can be inserted with the src attribute to HTML
  • To attach several scripts, use multiple tags
<script src="file.js">
  alert("It's ignored");
</script>
  • If src is set, the script content is ignored

Code structure

Statements

  • Syntax constructs and commands that perform actions
  • Be separated with a semicolon

Semicolons

  • Be omitted in most cases when a line break exists
    • called an automatic semicolon insertion
  • An example of an error
alert("It works");
[1, 2].forEach(alert);

// alert("It won't work")[1, 2].forEach(alert);
alert("It won't work")
[1, 2].forEach(alert);

Comments

  • To add comments which describe what the code does and why
  • Don't affect its execution
  • One-line comments : // ...
  • Multiline comments : /* ... */
  • Nested comments are not supported

The Modern mode, "use strict"

"use strict"

"use strict";

...
  • "use strict" : To keep the old code working, need to explicitly enable them with a special directive
  • Be located at the top of a script
    • it can be put at the beginning of a function, and then enables strict mode in that function only

Browser console

  • A developer console (browser console) doesn't 'use strict' by default
  • Press [Shift+Enter], and put 'use strict' on top
(function() {
  'use strict';

  // ...your code here...
})()
  • It it dosen't work (like in an old browser), put it inside this kind of wrapper

Should we "use strict"?

  • Modern JavaScript supports "classes" and "modules", that enable 'use strict' automatically

Variables

A variable

// The statement declares a variable with the name "message"
let message = 'Hello!';

// Access it using the variable name
alert(message);
  • A named storage for data
  • cf. var : declares a variable, but "old-school" way

A real-life analogy

  • Imagined as a box labeled "message" with the value "Hello!"
  • When the value is changed, the old data is removed from the box
let hello = 'Hello World';
let message = hello;
  • Declare two variables and copy data from one into the other
  • cf. A variable should be declared only once

Variable naming

  • Contain only letters, digits, or the symbols $ and _
    • camelCase : multiple words
  • The first character must not be a digit
  • Hyphens '-' aren't allowed in the name
  • Case matters : be distinguished
  • Non-Latin letters are allowed, but not recommended
  • Cannot be used a list of reserved words (let, return, class, etc.)

Constants

const today = '2022.12.22';
today = '2023.01.01'; // error
  • To declare a constatnt (unchanging) variable
  • Sure that a variable will never change
Uppercase constants
const COLOR_BLUE = "#00F";
const COLOR_ORANGE = "#FF7F00";

let color = COLOR_ORANGE;
alert(color); // #FF7F00
  • To use constants as aliases for difficult-to-remember values
    • much easier to remember, mistype
    • much more meaningful
  • Capital-named constants are only used as aliases for "hard-coded" values

Name things right

  • A variable name should have a clean, obvious meaning, describing the data that it stores
  • Good-to-follow rules
    • Use human-readable names, like userName
    • Stay away from abbreviations or short names like a, b, c
    • Make names maximally descriptive and concise
    • Use on terms consistently within your team and in your own mind

Data types

  • A value in JavaScript is always of a certain type, such as a string or a number
  • 동적 타입 (Dynamically typed) : 자료의 타입은 있지만 변수에 저장되는 값의 타입을 언제든지 바꿀 수 있는 언어

Number

let number = 123;
number = 12.345;
  • Represents both integer and floating point numbers
    • Infinity : the mathematical Infinity
    • NaN : a computational error, an incorrect or an undefined mathematical operation
  • cf. Mathematical operations are safe in JavaScript
    • the script will never stop with a fatal error, only get NaN as the result

BigInt

const bigInt = 1234567890123456789012345678901234567890n;
  • Appending 'n' to the end of an integer
  • Stored all odd integers greater than 9007199254740991
  • Added recently to the language to represent integers of arbitrary length, such as for cryptography or miscrosecond-precision timestamps

String

  • A string must be surrounded by quotes
  • Double quotes("")
  • Single quotes('')
    • there's practically no difference between them in JavaScript
let name = "John";
alert(`Hello, ${name}`); 
// Hello, John

alert(`the result is ${1 + 2}`); 
// the result is 3
  • Backticks(``) : Extended functionality, allow us to embed variables and expressions into a string by wrapping them in ${...}

Boolean (logical type)

let nameFieldChecked = true; // yes, checked
let ageFieldChecked = false; // no, not checked

let isGreater = 4 > 1;
alert( isGreater ) // true
  • Has only two values : True / False
  • Also, come as a result of comparisons

The "null" value

let example = null;
  • A special value which represents "nothing", "empty" or "value unknown" in JavaScript
  • Not a "reference to a non-existing object" or a "null pointer" like in some other languages

The "undefined" value

let age;
alert(age); // undefined

let age = 100;
age = undefined
alert(age); // undefined
  • A value is not assigned
  • It's possible to explicitly assign 'undefined' to a variable, but don't recommend it

Objects and Symbols

  • The object type
    • used to store collections of data and more complex entities
  • The symbol type
    • used to create unique identifiers for objects

The typeof operator

// 'typeof x' or 'typeof (x)'
typeof undefined // undefined
typeof 0 // number
typeof true // boolean
typeof "example" // string
typeof Math // object
typeof null // object
typeof alert // function
  • Returns the type of the operand
  • 'Math' is a built-in object that provides mathematical operations
  • 'null' is not an object, it is a special value with a separate type of its own

Interaction: alert, prompt, confirm

alert

alert("Hello");
  • Shows a modal window with a message and waits for the user to press "OK"

prompt

let result = prompt (title, [default]);
  • title : the text to show the user
  • default : the initial value for the input field (an optional)
  • Shows a modal window with a text message, an input field for the user, and the buttons OK/Cancle
    • Get that text in the 'result'
    • Get 'null' by pressing Cancle or hitting the [ESC]

confirm

let result = confirm(question);
  • Shows a modal window with a question and two buttons, OK/Cancle
  • The result is 'true' if OK is pressed, and 'false' otherwise

Type Conversions

String Conversion

let value = true
typeof value // boolean

value = String(value);
typeof value // string
  • The function to convert a value to a string

Numeric Conversion

alert("6"/"2"); // 3, type of number
  • Numeric conversion happens in mathematical functions and expressions automatically
let str = "123";
let num = Number(str);
typeof str // string
typeof num // number
  • The function to convert a value to a number
Numeric conversion rules
  • undefined : NaN
  • null : 0
  • true/false : 1/0
  • string : the result is '0', if the remaining string is empty after whitespaces from the start and end are removed
    • An error gives 'NaN'

Boolean Conversion

ValueBecomes
0, null, undefined, NaN, ""false
other valuestrue
  • cf. the string with zero "0" is 'true', a non-empty string is always 'true' in JavaScript

"JavaScript Fundamentals", by Ilya Kantor, 2007-2022, https://javascript.info/first-steps

profile
괴발개발라이프

0개의 댓글