0% found this document useful (0 votes)
7 views

JavaScript (Variable)

This document discusses JavaScript variables including naming rules and different variable declarations using var, const, and let. Variables are containers that store data values and must have unique names. The var statement declares variables with function scope that can be reassigned, while const and let declare block-scoped variables introduced in ES6, where const variables cannot be reassigned and let variables can be reassigned.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

JavaScript (Variable)

This document discusses JavaScript variables including naming rules and different variable declarations using var, const, and let. Variables are containers that store data values and must have unique names. The var statement declares variables with function scope that can be reassigned, while const and let declare block-scoped variables introduced in ES6, where const variables cannot be reassigned and let variables can be reassigned.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

JavaScript Variable

Sungchul Lee
Outline
➢Variable
❑Naming Rule
➢var statement
➢const and let statement
Variable
➢Containers for storing data values
➢Example
❑var x = 5; // x stores the value 5
❑var y = 6; // y stores the value 6
❑var z = x + y; // z stores the value 11
➢variables must be identified with unique names.
❑These unique names are called identifiers.
Rules for Unique Identifiers (Names)
➢Names can contain letters, digits, underscores, and dollar
signs.
➢Names must begin with a letter
➢Names can also begin with $ and _ (but we will not use it in this
tutorial)
➢Names are case sensitive (y and Y are different variables)
➢Reserved words (like JavaScript keywords) cannot be used as
names
var statement
➢var statement declares a variable
❑Can be reassigned
➢Declaring a variable using “var”
➢Function Scope

var x = 1;
if (x === 1) {
var x = 2; console.log(x); // expected output:2
}
console.log(x);// expected output: 2
const, let statement
if (true) {
➢Declare a variable var x = 3;
❑ES6 }
console.log(x); // 3
➢Block scope
❑if,while, for, function if (true) {
❑{…} const y = 3;
let z = 10;
➢const }
❑Cannot be reassigned // Uncaught ReferenceError: y is not defined
❖Cf. final in Java console.log(y);
❑Must be assigned when declared console.log(z); // Error
const y=4;
➢Let console.log(y); // 4
❑Can be reassigned
❑Can be assigned later
Summary
➢Variable
❑Naming Rules
➢var, const, let statement
if (true) {
var x = 3;
}
console.log(x); // 3

if (true) {
const y = 3;
}
console.log(y); // Uncaught ReferenceError: y is not defined
const y=4;
console.log(y); // 4

You might also like