변수
값에 지정된 상징적인 이름이다. 변수의 이름은 식별자(identifier)
라고 불리며 특정 규칙을 따른다.
문자, 밑줄(_)이나 달러($) 기호로 시작해야 하고 문자, 숫자나 밑줄을 포함할 수 있습니다.
선언
var
: 실행 문맥에 따라 지역, 전역 변수를 선언한다.
if (true) {
var x = 5;
}
console.log(x); // x is 5
const
, let
: 블록 스코프 지역 변수를 선언한다.
if (true) {
let y = 5;
}
console.log(y); // ReferenceError: y is not defined
변수를 선언할 때, 구조 분해 할당(Destructing assignment) 구문을 사용해서 객체 리터럴로부터 값을 가져올 수 있다.
var { bar } = foo; // where foo = { bar:10, baz:12 };
/* This creates a variable with the name 'bar', which has a value of 10 */
초기값
var
, let
으로 선언되고 값이 할당되지 않은 변수는 undefined
값을 갖는다.
undefined
와 null
은 Number 문맥과 Boolean 문맥에서 다음과 같이 사용된다.
| Number | Boolean |
undefined | NaN | false |
null | 0 | false |
Hoisting
자바스크립트에서 변수는 함수(function)나 구문(statement)의 최상단으로 hoisted (or lifted) 된다. 호이스팅된 변수는 undefined
값을 갖는다.
console.log(x === undefined); // true
var x = 3;
var myvar = 'my value';
(function() {
console.log(myvar); // undefined
var myvar = 'local value';
})();
let
, const
로 선언된 변수는 호이스팅 되지만, 초기화 되지는 않는다. 이 변수를 사용하면 ReferenceError
가 발생한다.
console.log(x); // ReferenceError
let x = 3;
함수 선언(declaration)은 호이스팅 되지만, 함수 표현식(expression)은 호이스팅 되지 않는다.
/* Function declaration */
foo(); // "bar"
function foo() {
console.log('bar');
}
/* Function expression */
baz(); // TypeError: baz is not a function
var baz = function() {
console.log('bar2');
};
전역 변수
전역 변수는 전역 객체의 속성(property)이다. 브라우저에서 전역 객체는 window
이므로, window.variable
구문을 통해서 변수를 선언하거나 접근할 수 있다.
리터럴
Literal
은 고정된 값
을 의미한다. 자바스크립트 내부에서 문자 그대로(literally)
선언된다.
Array literals
let coffees = ['French Roast', 'Colombian', 'Kona']; // length of the array is 3
let myList = ['home', , 'school', , ]; // home, undefined, school, undefined
Boolean literals
Boolean 타입은 true
, false
두가지 리터럴 값을 갖는다. Boolean 객체의 true, false 값과는 다르다.
Numeric literals
Number, BigInt는 10진수, 8진수(0
, 0o
, 0O
), 16진수(0x
, 0X
), 2진수(0b
, 0B
) 값을 가질 수 있다.
0, 117, -345, 123456789123456789n (decimal, base 10)
015, 0001, -0o77, 0o777777777777n (octal, base 8)
0x1123, 0x00111, -0xF1A7, 0x123456789ABCDEFn (hexadecimal, "hex" or base 16)
0b11, 0b0011, -0b11, 0b11101001010101010101n (binary, base 2)
Floating-point literals
부동소수점 값을 의미한다.
3.1415926
-.123456789
-3.1E+12
.1e-23
Object literals
객체 리터럴은 중괄호({}
)로 둘러 싸인 속성(property)의 이름과 값의 목록이다.
var car = { manyCars: {a: 'Saab', b: 'Jeep'}, 7: 'Mazda' };
console.log(car.manyCars.b); // Jeep
console.log(car[7]); // Mazda
속성 이름이 유효한 식별자나 숫자가 아닐 경우, 따옴표(""
)로 묶어야 한다. 이러한 속성은 점(.
)이 아니라 배열 같은 표기법([]
)으로 접근하고 값을 설정할 수 있다.
var unusualPropertyNames = {
"": "An empty string",
"!": "Bang!"
}
console.log(unusualPropertyNames.""); // SyntaxError: Unexpected string
console.log(unusualPropertyNames[""]); // An empty string
console.log(unusualPropertyNames.!); // SyntaxError: Unexpected token !
console.log(unusualPropertyNames["!"]); // Bang!
ES2015 부터 Enhanced Object literals을 사용할 수 있다.
var obj = {
// __proto__
__proto__: theProtoObj,
// Shorthand for ‘handler: handler’
handler,
// Methods
toString() {
// Super calls
return 'd ' + super.toString();
},
// Computed (dynamic) property names
[ 'prop_' + (() => 42)() ]: 42
};
RegExp literals
String literals
문자열 리터럴은 큰 따옴표("
) 혹은 작은 따옴표('
)로 묶인 0개 이상의 문자를 의미한다.
문자열 리터럴 값은 문자열 객체의 모든 메서드를 호출할 수 있다. JavaScript는 자동으로 문자열 리터럴을 임시 문자열 객체로 변환, 메서드를 호출하고 나서 임시 문자열 객체를 폐기한다. 또한 문자열 리터럴에서도 String.length 속성을 사용할 수 있다.
ES2015 부터 Template literals
을 사용할 수 있다.
// Basic literal string creation
`In JavaScript '\n' is a line-feed.`
// Multiline strings
`In JavaScript, template strings can run
over multiple lines, but double and single
quoted strings cannot.`
// String interpolation
var name = 'Bob', time = 'today';
`Hello ${name}, how are you ${time}?`
// Construct an HTTP request prefix used to interpret the replacements and construction
POST`http://foo.org/bar?a=${a}&b=${b}
Content-Type: application/json
X-Credentials: ${credentials}
{ "foo": ${foo},
"bar": ${bar}}`(myOnReadyStateChangeHandler);