==, === 차이점

동등연산자(==) : 값만 같으면 된다
Strict equality(===) : 타입 및 값이 모두 같아야 한다

"1" ==  1;            // true
1 == "1";             // true
0 == false;           // true
0 == null;            // false
0 == undefined;       // false
0 == !!null;          // true, look at Logical NOT operator
0 == !!undefined;     // true, look at Logical NOT operator
null == undefined;    // true

const number1 = new Number(3);
const number2 = new Number(3);
number1 == 3;         // true
number1 == number2;   // false
"3" === 3; // false
true === 1; // false
null === undefined; // false

[JavaScript] ES6의 특징

ECMAScript 2015 was the second major revision to JavaScript.

ECMAScript 2015 is also known as ES6 and ECMAScript 6.

New Features in ES6

The let keyword

The let keyword allows you to declare a variable with block scope

var x = 10;
// Here x is 10
{
  let x = 2;
  // Here x is 2
}
// Here x is 10

The const keyword

Constants are similar to let variables, except that the value cannot be changed

var x = 10;
// Here x is 10
{
  const x = 2;
  // Here x is 2
}
// Here x is 10

Arrow Functions

You don't need the function keyword, the return keyword, and the curly brackets.

// ES5
var x = function(x, y) {
   return x * y;
}

// ES6
const x = (x, y) => x * y;

Arrow functions are not hoisted. They must be defined before they are used.

Using const is safer than using var, because a function expression is always a constant value.

You can only omit the return keyword and the curly brackets if the function is a single statement. 
Because of this, it might be a good habit to always keep them:
const x = (x, y) => { return x * y };

The ... Operator (spread)

The ... operator can be used to expand an iterable into more arguments for function calls:

const numbers = [23,55,21,87,56];
let maxValue = Math.max(...numbers);

The ... operator expands an iterable (like an array) into more elements

const cars1 = ["Saab", "Volvo", "BMW"];
const cars2 = ["Saab", "Volvo", [..."BMW"]];

For/of

for/of lets you loop over data structures that are iterable such as Arrays, Strings, Maps, NodeLists, and more.

Syntax

for (variable of iterable) {
  // code block to be executed
}

variable - For every iteration the value of the next property is assigned to the variable. Variable can be declared with const, let, or var.

iterable - An object that has iterable properties.

//Looping over an Array
const cars = ["BMW", "Volvo", "Mini"];
let text = "";

for (let x of cars) {
  text += x + " ";
}

//Looping over a String
let language = "JavaScript";
let text = "";

for (let x of language) {
    text += x + " ";
}

Map Objects

Being able to use an Object as a key is an important Map feature

const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);

Set Objects

// Create a Set
const letters = new Set();

// Add some values to the Set
letters.add("a");
letters.add("b");
letters.add("c");

Classes

Always add a method named constructor():

class ClassName {
  constructor() { ... }
} //Syntax
  class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
}

Promises

A Promise is a JavaScript object that links "Producing Code" and "Consuming Code".
"Producing Code" can take some time and "Consuming Code" must wait for the result.

Promise Syntax

const myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)

  myResolve(); // when successful
  myReject();  // when error
});

// "Consuming Code" (Must wait for a fulfilled Promise).
myPromise.then(
  function(value) { /* code if successful */ },
  function(error) { /* code if some error */ }
);

Example Using a Promise

const myPromise = new Promise(function(myResolve, myReject) {
  setTimeout(function() { myResolve("I love You !!"); }, 3000);
});

myPromise.then(function(value) {
  document.getElementById("demo").innerHTML = value;
});

Symbol

A JavaScript Symbol is a primitive datatype just like Number, String, or Boolean.
It represents a unique "hidden" identifier that no other code can accidentally access.

For instance, if different coders want to add a person.id property to a person object belonging to a third-party code, they could mix each others values.

Using Symbol() to create a unique identifiers, solves this problem:

const person = {
  firstName: "John",
  lastName: "Doe",
  age: 50,
  eyeColor: "blue"
};

let id = Symbol('id');
person[id] = 140353;
// Now person[id] = 140353
// but person.id is still undefined



//Symbols are always unique.

//If you create two symbols with the same description they will have different values:

Symbol("id") == Symbol("id"); // false

Default Parameters

ES6 allows function parameters to have default values.

function myFunction(x, y = 10) {
  // y is 10 if not passed or undefined
  return x + y;
}
myFunction(5); // will return 15

Function Rest Parameter(...)

String.includes()

The includes() method returns true if a string contains a specified value, otherwise false:

let text = "Hello world, welcome to the universe.";
text.includes("world")    // Returns true

String.startsWith()

The startsWith() method returns true if a string begins with a specified value, otherwise false:

let text = "Hello world, welcome to the universe.";

text.startsWith("Hello")   // Returns true

String.endsWith()

The endsWith() method returns true if a string ends with a specified value, otherwise false:

var text = "John Doe";
text.endsWith("Doe")    // Returns true

Array.from()

The Array.from() method returns an Array object from any object with a length property or any iterable object.

//Create an Array from a String:
Array.from("ABCDEFG")   // Returns [A,B,C,D,E,F,G]

Array keys()

The keys() method returns an Array Iterator object with the keys of an array.

//Create an Array Iterator object, containing the keys of the array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const keys = fruits.keys();

let text = "";
for (let x of keys) {
  text += x + "<br>";
}

Array find()

The find() method returns the value of the first array element that passes a test function.

//This example finds (returns the value of ) the first element that is larger than 18:
const numbers = [4, 9, 16, 25, 29];
let first = numbers.find(myFunction);

function myFunction(value, index, array) {
  return value > 18;
}

Note that the function takes 3 arguments:

  • The item value
  • The item index
  • The array itself

Array findIndex()

The findIndex() method returns the index of the first array element that passes a test function.

//This example finds the index of the first element that is larger than 18:
const numbers = [4, 9, 16, 25, 29];
let first = numbers.findIndex(myFunction);

function myFunction(value, index, array) {
  return value > 18;
}

New Math Methods

Math.trunc()

Math.trunc(x) returns the integer part of x:

Math.trunc(4.9);    // returns 4
Math.trunc(4.7);    // returns 4
Math.trunc(4.4);    // returns 4
Math.trunc(4.2);    // returns 4
Math.trunc(-4.2);    // returns -4

Math.sign()

Math.sign(x) returns if x is negative, null or positive:

Math.sign(-4);    // returns -1
Math.sign(0);    // returns 0
Math.sign(4);    // returns 1

Math.cbrt()

//Math.cbrt(x) returns the cube root of x:
Math.cbrt(8);    // returns 2
Math.cbrt(64);    // returns 4
Math.cbrt(125);    // returns 5

Math.log2()

//Math.log2(x) returns the base 2 logarithm of x:
Math.log2(2);    // returns 1

Math.log10()

//Math.log10(x) returns the base 10 logarithm of x:
Math.log10(10);    // returns 1

New Number Properties

EPSILON

let x = Number.EPSILON;

MIN_SAFE_INTEGER

let x = Number.MIN_SAFE_INTEGER;

MAX_SAFE_INTEGER

let x = Number.MAX_SAFE_INTEGER;

New Number Methods

Number.isInteger()

The Number.isInteger() method returns true if the argument is an integer.

Number.isInteger(10);        // returns true
Number.isInteger(10.5);      // returns false

Number.isSafeInteger()

A safe integer is an integer that can be exactly represented as a double precision number

  • 📍double precision number : 64 bits are used to represent the floating-point number.
Number.isSafeInteger(10);    // returns true
Number.isSafeInteger(12345678901234567890);  // returns false

New Global Methods

isFinite()

The global isFinite() method returns false if the argument is Infinity or NaN.
Otherwise it returns true:

isFinite(10/0);       // returns false
isFinite(10/1);       // returns true

isNaN()

The global isNaN() method returns true if the argument is NaN. Otherwise it returns false:

isNaN("Hello");       // returns true

Object entries()

//Create an Array Iterator, and then iterate over the key/value pairs:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const f = fruits.entries();

for (let x of f) {
  document.getElementById("demo").innerHTML += x;
}

The entries() method returns an Array Iterator object with key/value pairs:

[0, "Banana"][1, "Orange"]
[2, "Apple"][3, "Mango"]

The entries() method does not change the original array.

JavaScript Modules

Import from named exports

//Import named exports from the file person.js:
import { name, age } from "./person.js";

Import from default exports

Import a default export from the file message.js:
import message from "./message.js";

Browser Support for ES6 (2015)

Reference : https://www.w3schools.com/js/js_es6.asp


let, const, var (scope 개념에서의 차이)

let

Scope📍block scoped. The scope of a let variable is only block scoped. It can’t be accessible outside the particular block ({block}).

var

Scope📍Global scoped or function scoped. The scope of the var keyword is the global or function scope. It means variables defined outside the function can be accessed globally, and variables defined inside a particular function can be accessed within the function.

const

Scope📍block scoped: When users declare a const variable, they need to initialize it, otherwise, it returns an error. The user cannot update the const variable once it is declared.

//Users cannot change the properties of the const object, 
//but they can change the value of the properties of the const object.
const a = {
        prop1: 10,
        prop2: 9
    }
     
    // It is allowed
    a.prop1 = 3
 
    // It is not allowed
    a = {
        b: 10,
        prop2: 9
    }

Reference : https://www.geeksforgeeks.org/difference-between-var-let-and-const-keywords-in-javascript/


JavaScript & Node.js

JavaScript(JS)

  • Scripting language
  • the updated version of the ECMA script
  • a high-level programming language that uses the concept of Oops but it is based on prototype inheritance

Node.js

  • a cross-platform and opensource Javascript runtime environment that allows the javascript to be run on the server-side
  • allowing Javascript code to run outside the browser
  • coming with a lot of modules and mostly used in web development

Reference : https://www.geeksforgeeks.org/difference-between-node-js-and-javascript/


null과 undefined 차이

공통점

'없음'을 나타냄

차이점

undefined

원시값(Primitive Type)으로, 선언한 후에 값을 할당하지 않은 변수나 값이 주어지지 않은 인수에 자동으로 할당

  • 값이 대입되지 않은 변수
  • 메서드와 선언에서 변수가 할당받지 않은 경우
  • 함수가 값을 return 하지 않았을 때

null

null은 원시값(Primitive Type) 중 하나로, 어떤 값이 의도적으로 비어있음을 표현
undefined는 값이 지정되지 않은 경우를 의미하지만, null의 경우에는 해당 변수가 어떤 객체도 가리키고 있지 않다는 것을 의미

typeof null          // "object" (하위호환 유지를 위해 "null"이 아님)
typeof undefined     // "undefined"
null === undefined   // false
null  == undefined   // true
null === null        // true
null == null         // true
!null                // true
isNaN(1 + null)      // false
isNaN(1 + undefined) // true

Shallow Copy & Deep Copy

Shallow Copy

A bitwise copy of an object, where a new object is created and it has the same copy of the values in the original object, is called a Shallow copy. If any of the object fields refer to the other object then in such cases only the reference address is copied.

Deep Copy

When the process of copying occurs repetitively and a copy of the object is always copied in another object, then it is called deep copy. In this process, initially, a new collection of the object is constructed, and then the copies of the child object frequently populate those found in the original.

In Shallow copy, a copy of the original object is stored and only the reference address is finally copied. In Deep copy, the copy of the original object and the repetitive copies both are stored.

Reference : https://byjus.com/gate/difference-between-shallow-and-deep-copy-of-a-class/

2개의 댓글

comment-user-thumbnail
2022년 12월 16일

오 글이 덜 작성된 것 같아요~

1개의 답글