JavaScript - Variables & Consonants

Nina·2020년 8월 18일


목록 보기

ppt 슬라이드와 맨 아래 예시들의 출처는 Maximillian Schwarzmüller의 'JavaScript - The Complete Guide 2020 (Beginner + Advanced)' 강의입니다(링크)

1. var, let & const

var & let keyword creates a variable. const creates a constant. var has been availabe since JS was invented. let and const has been available since ES6.

The biggest difference between var and other keywords is that var is function scoped, while the others are block scoped. Therefore, var is available and can be accessed inside of the functions, and let and const are available inside of the curly braces({ }).

2. Hoisting

"In JavaScript, a variable can be declared after it has been used.
In other words; a variable can be used before it has been declared."

When JS engine(browser) loads script, it looks all over the script first and it automatically loads functions and variables.

These two have same results('undefined').

<!--example 1-->
var userName = 'Nina';

<!--example 2-->
var userName;
var userName = 'Nina';

This throws an error bacause unlike var, let and const are hoisted but remain uninitialized.

let userName = 'Nina';

3. How Code Is Parsed & Compiled

4. Inside the JS Engine

JS is single-threaded language. Therefore, one thing happens at a time. And the stack controls program flow.

*Functions are stored in heap. When script runs, stack is executed(dev tool → sources → call stack)

5. Primitive vs Reference Values

(1) Example 1(Primitive value)

In this case, the value of 'anotherUser' remains same even though the original variable('name') has been changed.

(2) Example 2(Reference value)

In this case, the array 'newHobbies' is changed when the original array 'hobbies' is allocated a new value. That's because when copying a reference values-an array is a reference value-it doesn't mean you are copying the value itself but the pointer(address, reference) of memory(heap) is copied.

(3) Example 3(Reference value)

Constant 'person' is stored in memory(heap). You can change data stored in memory(address), so changing 'person.age' works perfectly fine. But you cannot manipulate the address itself. Then it will throw an error.


0개의 댓글