DEV Community

Tony Chase
Tony Chase

Posted on

Learning JS in 30 Days - Day 2

Yesterday learned the basics of JavaScript and development environment setup. Today will dive deep into JavaScript variables and data types, which are fundamental programming concepts. Understanding these concepts well is crucial for subsequent learning.

πŸ“š Today's Learning Objectives

  • Master JavaScript variable declaration methods
  • Understand JavaScript data types
  • Learn type conversion and detection
  • Understand variable naming conventions

πŸ”§ Variable Declaration

In JavaScript, there are three ways to declare variables:

1. var (Traditional Method)

var name = "John";
var age = 25;
var isStudent = true;
Enter fullscreen mode Exit fullscreen mode

2. let (ES6 Addition, Recommended)

let name = "Jane";
let age = 30;
let isWorking = false;
Enter fullscreen mode Exit fullscreen mode

3. const (ES6 Addition, Constants)

const PI = 3.14159;
const COMPANY_NAME = "TechCorp";
const MAX_USERS = 1000;
Enter fullscreen mode Exit fullscreen mode

Differences in Variable Declaration

Feature var let const
Scope Function scope Block scope Block scope
Redeclaration Allowed Not allowed Not allowed
Hoisting Yes No No
Reassignment Allowed Allowed Not allowed
// var hoisting
console.log(x); // undefined (no error)
var x = 5;

// let/const no hoisting
console.log(y); // ReferenceError
let y = 10;

// const cannot be reassigned
const z = 15;
z = 20; // TypeError: Assignment to constant variable
Enter fullscreen mode Exit fullscreen mode

πŸ“Š Data Types

JavaScript has 8 basic data types:

1. Primitive Types

Number

let integer = 42;
let decimal = 3.14;
let negative = -10;
let scientific = 1e6; // 1000000
let infinity = Infinity;
let notANumber = NaN;

console.log(typeof integer); // "number"
console.log(typeof decimal); // "number"
console.log(typeof infinity); // "number"
console.log(typeof notANumber); // "number"
Enter fullscreen mode Exit fullscreen mode

String

let singleQuote = "Hello World";
let doubleQuote = "Hello World";
let templateLiteral = `Hello World`;
let multiline = `This is
a multiline
string`;

// String interpolation
let name = "Tom";
let age = 20;
let message = `Hello, this is ${name}, age ${age}`;

console.log(typeof singleQuote); // "string"
Enter fullscreen mode Exit fullscreen mode

Boolean

let isTrue = true;
let isFalse = false;
let result = 5 > 3; // true

console.log(typeof isTrue); // "boolean"
Enter fullscreen mode Exit fullscreen mode

Undefined

let undefinedVar;
console.log(undefinedVar); // undefined
console.log(typeof undefinedVar); // "undefined"
Enter fullscreen mode Exit fullscreen mode

Null

let nullVar = null;
console.log(nullVar); // null
console.log(typeof nullVar); // "object" (this is a JavaScript bug)
Enter fullscreen mode Exit fullscreen mode

Symbol (ES6 Addition)

let sym1 = Symbol();
let sym2 = Symbol("description");
let sym3 = Symbol("description");

console.log(sym2 === sym3); // false (each Symbol is unique)
console.log(typeof sym1); // "symbol"
Enter fullscreen mode Exit fullscreen mode

BigInt (ES2020 Addition)

let bigNumber = 1234567890123456789012345678901234567890n;
let anotherBig = BigInt("1234567890123456789012345678901234567890");

console.log(typeof bigNumber); // "bigint"
Enter fullscreen mode Exit fullscreen mode

2. Reference Types

Object

let person = {
  name: "John",
  age: 25,
  isStudent: true,
  hobbies: ["reading", "swimming", "programming"],
};

console.log(typeof person); // "object"
Enter fullscreen mode Exit fullscreen mode

πŸ”„ Type Conversion

Implicit Conversion (Automatic)

// Numbers and strings
let result1 = "5" + 3; // "53" (string concatenation)
let result2 = "5" - 3; // 2 (numeric operation)
let result3 = "5" * 3; // 15 (numeric operation)
let result4 = "5" / 3; // 1.6666666666666667 (numeric operation)

// Boolean conversion
let bool1 = Boolean("hello"); // true
let bool2 = Boolean(""); // false
let bool3 = Boolean(0); // false
let bool4 = Boolean(1); // true
Enter fullscreen mode Exit fullscreen mode

Explicit Conversion (Manual)

// Convert to string
let num = 123;
let str1 = String(num); // "123"
let str2 = num.toString(); // "123"
let str3 = num + ""; // "123"

// Convert to number
let str = "456";
let num1 = Number(str); // 456
let num2 = parseInt(str); // 456
let num3 = parseFloat("3.14"); // 3.14
let num4 = +str; // 456

// Convert to boolean
let bool1 = Boolean(0); // false
let bool2 = Boolean(""); // false
let bool3 = Boolean(null); // false
let bool4 = Boolean(undefined); // false
let bool5 = Boolean("hello"); // true
let bool6 = Boolean(1); // true
Enter fullscreen mode Exit fullscreen mode

πŸ” Type Detection

typeof Operator

console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (note: this is a bug)
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function () {}); // "function"
Enter fullscreen mode Exit fullscreen mode

More Precise Type Detection

// Detect arrays
let arr = [1, 2, 3];
console.log(Array.isArray(arr)); // true
console.log(arr instanceof Array); // true

// Detect null
let value = null;
console.log(value === null); // true

// Detect NaN
let notANumber = NaN;
console.log(Number.isNaN(notANumber)); // true
console.log(isNaN(notANumber)); // true (note the difference)
Enter fullscreen mode Exit fullscreen mode

πŸ“ Variable Naming Conventions

Naming Rules

  1. Can only contain letters, numbers, underscore (_) and dollar sign ($)
  2. Cannot start with a number
  3. Case sensitive
  4. Cannot use reserved words
// Correct naming
let userName = "John";
let user_age = 25;
let $price = 100;
let _private = "private variable";

// Incorrect naming
let 2name = "error"; // Cannot start with number
let user-name = "error"; // Cannot contain hyphen
let class = "error"; // Cannot use reserved words
Enter fullscreen mode Exit fullscreen mode

Naming Conventions

// Camel case (recommended)
let firstName = "John";
let lastName = "Doe";
let isUserLoggedIn = true;

// Constants use all uppercase
const MAX_RETRY_COUNT = 3;
const API_BASE_URL = "https://api.example.com";

// Private variables use underscore prefix
let _internalCounter = 0;
let _privateData = {};
Enter fullscreen mode Exit fullscreen mode

🎯 Practice Exercises

Exercise 1: Variable Declaration and Assignment

// Declare different types of variables
let studentName = "Alice";
let studentAge = 18;
let isGraduated = false;
let subjects = ["Math", "English", "Science"];
let studentInfo = {
  name: studentName,
  age: studentAge,
  graduated: isGraduated,
  subjects: subjects,
};

console.log("Student name:", studentName);
console.log("Student age:", studentAge);
console.log("Is graduated:", isGraduated);
console.log("Subject list:", subjects);
console.log("Student info:", studentInfo);
Enter fullscreen mode Exit fullscreen mode

Exercise 2: Type Conversion

// Create a type conversion function
function convertTypes() {
  let str = "123";
  let num = 456;
  let bool = true;

  // Convert to string
  console.log("Number to string:", String(num));
  console.log("Boolean to string:", String(bool));

  // Convert to number
  console.log("String to number:", Number(str));
  console.log("Boolean to number:", Number(bool));

  // Convert to boolean
  console.log("String to boolean:", Boolean(str));
  console.log("Number to boolean:", Boolean(num));
  console.log("0 to boolean:", Boolean(0));
  console.log("Empty string to boolean:", Boolean(""));
}

convertTypes();
Enter fullscreen mode Exit fullscreen mode

Exercise 3: Type Detection

// Create a type detection function
function checkTypes() {
  let values = [
    42,
    "hello",
    true,
    null,
    undefined,
    [1, 2, 3],
    { name: "test" },
    function () {},
  ];

  values.forEach((value, index) => {
    console.log(`Value ${index + 1}:`, value);
    console.log(`Type:`, typeof value);
    console.log(`Is array:`, Array.isArray(value));
    console.log(`Is null:`, value === null);
    console.log("---");
  });
}

checkTypes();
Enter fullscreen mode Exit fullscreen mode

πŸ” Today's Key Points Summary

  1. Variable Declaration: Differences and use cases of var, let, const
  2. Data Types: Characteristics of 8 basic data types
  3. Type Conversion: Methods for implicit and explicit conversion
  4. Type Detection: typeof operator and more precise detection methods
  5. Naming Conventions: Rules and conventions for variable naming

πŸ“š Tomorrow's Preview

Tomorrow will learn about JavaScript operators and expressions, including:

  • Arithmetic operators
  • Comparison operators
  • Logical operators
  • Assignment operators
  • Operator precedence

πŸ’‘ Learning Tips

  1. Understand Concepts: Focus on understanding differences between variable declaration methods
  2. Practice More: Try various type conversions in the console
  3. Pay Attention to Details: Especially note that typeof null returns "object"
  4. Follow Naming Conventions: Develop good variable naming habits

This concludes the introduction to day two's learning content. Tomorrow will continue learning about JavaScript operators and expressions.

Top comments (0)