본문 바로가기
Computer Science/Javascript

[ JavaScript ] JavaScript 총 내용 정리

by 기억보다 기록을 2023. 3. 4.
반응형

1. JavaScript 

  • JavaScript는 웨페이지에서 복잡한 기능을 구현할 수 있도록 하는 객제현 스크린팅 프로그램밍 언어입니다.
  • 자바스크립트는 동적이며, 타입을 명시할 필요가 없는 인터프리터 언어입니다.
  • 자바스크립트는 객체 지향형 프로그래밍과 함수형 프로그래밍을 모두 표현할 수 있습니다.
  • Interpreted Language as JavaScript, Python Ruby
  • Compiled Languages: Java, C/C++, Swift

2. Data Types

  • JavaScript is a dynamic language with dynamic data types
  • Primitive values: We refer to values of these types as primitive values.
  • All Primitive types ( except  null) can be tested by the typeOf operator.
  • typeOf null returns "object", so one has to use  " === null " to test for null
  • All primitive types (except null and undefined) have their object wrapper types.
  • However "null" and "undefined" throw a TypeError

 

  • Data Types: Null, undefined, String, Number, Boolean ,Bigint, Symbol
  •  Null type: The Null type is inhabited be exactly one value : null
  • Number Type : Values outside the range ±(2-1074 to 21024) are automatically converted
  •  Here the interesting fact : +0 === -0 -> is true, and (42 / +0) returns Infinity, (42 / -0) returns -Infinity
  • NaN : Not a number. In JavaScript, NaN is a number that is not a legal number.
  • The Global NaN property is the same as the Number.

3. JavaScript Variables

  • var : The var statement declares a function-scoped or global-scoped variable, optimizing it to a value.
  • var string.length is defined string length
var a = "Hello, world"
console.log(a.length) 

// returns 12 , "," and " " free spaces also included
  • Syntax :
var name1
var name1 = value1,  name2 = value2
var name1, name2 = value2
var a, b = a = 'A' //  a = 'A' and b = 'A'

 

  • let :  declares a block-scoped local variable, optionally initializing it to a value.
  • let allows you to declare variables that are limited to the scope of a block statement
  • unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope.
  • The other difference between var and let is that the latter can only be accessed after its declaration is reached 
  • Syntax :
let name1;
let name1 = value1;
let name1 = value1, name2 = value2;
let name1, name2 = value2;
let name1 = value1, name2, /* …, */ nameN = valueN;

 

  • const : The const declaration creates block- scoped constants, much like variables declared using the let keyword.
  • The value of a constant can't be changed through reassignment
  • An initializer for a constant is required
  • The const declaration creates a read-only reference to a value
  • Unlike var, const begins declarations, not statements. Can't use a lone const declaration as the body of a block
  • Syntax : 
const name1 = value1;
const name1 = value1, name2 = value2;
const name1 = value1, name2 = value2, /* …, */ nameN = valueN;

 


5. Slice() Method

  • JavaScript slice function is used to a shallow copy as a new array.
  • Syntax with simple example as var a = [ 1, 2, 3, 4, 5 ]
slice(): method that copy the string
//returns [1,2,3,4,5]

slice(2) : methods copy the string starting to 2th argument from string length  
//returns [3,4,5]

slice(0,3) : methods copy the string starting to 0 from 3th argument 
//returns [1,2,3]

slice(-2) : copy the string starting to end of string argument from last 2 arguments 
//returns [4,5]

slice(-6 ~ ) : returns just slice() function
//returns [1,2,3,4,5]

slice(-2,1) 
//returns [3,4]

 

  • When the start point is negative, such as start < 0 , start + string.length is used.
slice(-2) 

// here start point is negative, -2(start) + 5 ( length of string) = 3
          
slice(-2) = slice(3) 

//expected result is [ 4, 5].

 

  •  If start < - array.length,  0 used.  slice(-6) here less then -5 so can get just slice(0)
slice(-6) = slice(0)

// result  [ 1, 2, 3, 4, 5 ]

 

  •  start >= array.length , nothing extracted
 slice(6) = nothing expected

 

  • If end < 0 , end + array.length is used.
slice(1,-1) =  slice(1, (5 + (-1))) =  slice(1,4)

// slice(1, -1) = slice (1,4)

// result is [2,3,4,5]

 

  • if end >= array.length, slice(array.length) is used
 slice(1,6) = slice(1,4)
 
 // result  [ 2, 3, 4, 5 ]

 

  • toUpperCase() : The toUpperCase() method returns the calling string value converted to uppercase.
  • toLowerCase() : convert text to lever case 

6. Increment and Decrement

  • var a = 1 in  Increment
a = a + 1  // now a=2
a++;  // now a = 3
a+=1 ; // now a = 4

 

  • var b = 5; Decrement   

a = a - 1; // now a = 4
a -- ; // now a = 3
a = -1 // now a = 2

 

  • Two Samples
         
var a = 3;        // a is 3
var b = a++;      // b equals 3, bcz a =3, a++ defines a = 4 
b += 1;           // here b is 4

// expected result => a = 4, b = 4

 


7. JavaScript Function

  • The function object provides a methods for functions. In JavaScript, every function is actually a Function Object
  • Each function properties:  length , name, prototype
  • function is declared using the function keyword.
  • The basic rules of naming a function are similar to naming a variable. 
  • It is better to write a descriptive name for your function. 
  • The body of function is written within {}.
// declaring a function named greet()

function greet() {
    console.log("Hello there");
}

 

  • Calling a Function. In the above program, we have declared a function named greet()
// function call
greet();

 

  • A function can also be declared with parameters. A parameter is a value that is passed when declaring a function.
// program to print the text
// declaring a function

function greet(name) {
    console.log("Hello " + name + ":)");
}

// variable name can be different
let name = prompt("Enter a name: ");

// calling function
greet(name);

 


8. Math Random()

  • Static method returns a floating-point, random number between 0 and 1.
  • Getting a random number between two numbers
 function getRandomNumbers(startPoint, endPoint) {
        return Math.random() * (endPoint - startPoint) + startPoint; 
     }

getRandomNumbers(5,200);

 

  • Getting a random integer between two values
function getRandomInteger(startPoint, endPoint) {
       
    startPoint = Math.ceil(startPoint); 
    endPoint = Math.ceil(endPoint);
    return Math.random() * (endPoint - startPoint) + startPoint; 
}

 getRandomInteger(5,200)

 

  • Math.Random() + Math.floor() => only integer random numbers
function getRandomInteger(startPoint, endPoint) {
       
    startPoint = Math.ceil(startPoint); 
    endPoint = Math.ceil(endPoint);
    
    return Math.floor(Math.random() * (endPoint - startPoint) + startPoint); 
}

 getRandomInteger(5,200)

 


9. Comparators and Equality,  Strict equality

  • Equality " == " : operator checks whether its two operands are equal, returning a Boolean value.
  • Object: return " true " only if its two operands are same abject
  • String: return " true " only if two operands have same characters with same order
  • Boolean : return " true " only if two operands both true or false
  • BigInt: return true only if both operands have the same value
  • Symbol: return true only if both operands reference the same symbol
  • If one of operands is null or undefined, other must be null or undefined for returned true
  • Super Interesting Samples  : 
1 == 1,  true
'hello' == 'hello',  true
'1' == 1, true
0 == false,  true
+0 == -0 , true
Nan == Nan, is false
null == null, true
null == undefined, true
undefined == undefined, true

 

  • Strict Equality " === " : operator checks whether the two operands are equal, returning a Boolean value.
  • Difference of equality between Strict Equality.  Most notable difference of equality vs strict equality is that if the operands are different types the == operator attempts to convert them to the same type before comparing.
         
  • Unlike the equality "==", the strict equality operator always consider operands of different types to be different.
  • Equality vs Strict Equality Samples:
+0 === -0, returns true

1 == 1 vs 1 === 1 
//also returns true

'hello' == 'hello' 'hello' === 'hello'
// both true

'1' == 1 is true, but '1' === 1 returns false

0 == false is true,  but '0' === 'false' is exactly false

 

  • if both operations are null or undefined, returns true
null == undefined is true,  but null === undefined is false

 

  • If either operands is NaN, returns false.
NaN == NaN, NaN === Nan, returns false

 


10. *Arrays 

  • Arrays : a net way of strong a list items under a single variable name.
  • Arrays are generally described as "list-like objects"
  • Basically single objects that contain multiple values stored in a list.
  • Can mix several data types string, number, objects
const array = [1, "Hello", [0,1,2]]

 

  • Finding the length of a array : using array.length property.
  • Start with 0, list number called index.
  • Here interesting fact computers start count with 0;

 

  • Array inside array called : Multidimensional Array 
  • Special Point of Multidimensional arrays two sets of brackets []
const array[1, "Hello", [0,1,2]]
array[0] = 1 and array[1] is "Hello".
array[2][0] equal fist value of fist index as 0
array[2][1] is returns 1 and array[2][2] is returns 2

 

  • Finding the index of items in an array 
  • index.of() method takes an item argument or returns "-1" when value not included
const fruit = ["banana", "apple", "orange", "kiwi"];

console.log(fruit.indexOf('banana')) => returns 1
console.log(fruit.indexOf('mango')) => returns -1, Not included

 

  •  Adding Items in an array
  • Add one or more items to the end of an array we use push();
const num = [1,2,3]; // length = 3

num.push(5) // [1,2,3,5], length = 4

 

  • Adding Items in start of array using unshift();
const num = [1,2,3];

num.unshift(5); // [5,1,2,3]

 

  •  Removing items last item use pop();
const num = [1,2,3,5,70];

num.pop(); // [1,2,3,5];

 

  • The pop() method returns the deleted item.
const num = [1,2,3,5,70];
var deletedItem = num.pop();

console.log(deletedItem);  // 70

 

  • To Remove the first item of array use shift();
const num = [1,2,3,4];

num.shift(); // [2,3,4];

 

  •  To Remove nth item in array using splice();
  •  In this call splice(a,b) => a is as fist argument where to start removing and b shows how many items will delete 
  •  if  (index != -1) =>  index == -1 means that not included, so index != -1 must include
         
const num = [1,2,3,4,70,100];

   const index = num.indexOf(3);
         if(index != -1){
            num.splice(index,2)
            
            // as splice() method here "index" is 2th as 3 
            // and "2" means will delete 2 items start 2th index that 3
            
         }

console.log(num); // [1,2,70,100], length is 4

 

  • Accessing every item , using for .. of method
const num = [1,2,70,100];

      for(const getIndex of num){
         console.log(getIndex);
         
         // result get all of index values separately
}

 

 

  • map() method
  • map() method calls the function once for each item in the array, passing in the item then adds the return value from each function call to a new array and returns the new array.
 function double(num) { 
      return num * 2 
 }

  const num = [1,2,3,4,5];
  const result = num.map(double);
  
  console.log(result); // [2,4,6,8,10]

 

  • filter() method
  • Using filter() we can create new arrays with conditions below the array.
  • filter() calls for every item in the array, if function is true then add to a new array.
 function isLong(name) { 
    return name.length > 3
    // get items legth more than 3
 }

 const arr = ["test", "abc", "apple", "it", "a"];
 const result = arr.filter(isLong);

 onsole.log(result);  // ['test', 'apple']

 

  • split() method
  • The split() method divides a string into a list of substrings and returns them as an array.
  •  The split() method takes a single parameter, the character we want to separate.
  • Also toString() converting an array to string
  • Syntax :  string.split(separator, limit)
const message = "JavaScript::is::fun";

// divides the message string at ::

let result = message.split("::");
console.log(result);

// Output: [ 'JavaScript', 'is', 'fun' ]

11. While vs For Loops 

  •  While statement creates a loop that execute a specified as long as test condition is true
let x, n = 0;
     
      while( n < 3) {
          n++;
          x += n; 
}
condition: when n = 0, 0 < 3 is true so x = 0;
condition: when n = 1, 1 < 3 is true so x = 1;
condition: when n = 2, 2 < 3 is true so x was 1 and x += 2 returns x = 3;
condition: when n = 3, n = 3, x = 6;

final values of n = 3, x = 6;

 

  • For statement creates a loop that consists three expressions: init, condition, after and returns statement
  •  Using for an with two iterating variables
const arr = [1, 2, 3, 4, 5, 6];

        for( let l = 0, r = arr.length; l < r; l ++, r--){
         console.log(arr[l], arr[r]);
         
}  

// result => // 1 6  // 2 5 // 3 4
반응형