Welcome to Day 2 of learning JavaScript! Today, we’ll explore the building blocks of any program: variables and data types. These concepts are crucial as they form the foundation for everything you do in JavaScript.
A variable is like a container that holds data values. Think of it as a labeled box where you can store information, retrieve it later, or even change its contents.
JavaScript provides three ways to declare variables:
var oldWay = "Avoid this if possible"; let currentWay = "Use let for variables that can change"; const fixedValue = "Use const for constants";
|
var | let | const | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Scope | Function-scoped | Block-scoped | Block-scoped | ||||||||||||||||
Reassignable | Yes | Yes | No | ||||||||||||||||
Redeclarable | Yes | No | No |
var oldWay = "Avoid this if possible"; let currentWay = "Use let for variables that can change"; const fixedValue = "Use const for constants";
JavaScript has two types of data: Primitive and Non-Primitive.
function scopeTest() { if (true) { var x = "Function scope"; let y = "Block scope"; const z = "Constant"; } console.log(x); // Accessible // console.log(y); // Error: y is not defined // console.log(z); // Error: z is not defined } scopeTest();
let name = "Arjun"; console.log(name); // "Arjun"
let age = 22; console.log(age); // 22
let isStart_up_guy = true; console.log(isStart_up_guy); // true
let emptyValue = null; console.log(emptyValue); // null
let uninitialized; console.log(uninitialized); // undefined
JavaScript allows you to convert values between types.
JavaScript sometimes converts types automatically.
Example:
let uniqueKey = Symbol("key"); console.log(uniqueKey); // Symbol(key)
You can manually convert types using built-in functions like Number(), String(), or Boolean().
Example:
let result = "5" + 5; // String + Number console.log(result); // "55" (string)
Declare variables using let and const to store:
Try type conversion:
Today, we covered:
Tomorrow, we’ll dive into operators and expressions in JavaScript to start manipulating data and writing more complex programs. Stay tuned for Day 3: Operators and Expressions!
The above is the detailed content of Day Variables and Data Types in JavaScript. For more information, please follow other related articles on the PHP Chinese website!