JavaScript Variables and Data Types: let, const, and More
Introduction
Every JavaScript program starts with variables and values. This tutorial explains how to declare variables with const and let, the main data types, how to check a value's type, and why you should prefer strict equality.
Prerequisites
- A modern web browser
- Access to the browser developer console or Node.js
Step-by-Step Guide
Step 1: Declare variables with const and let
Use const for values that won't be reassigned and let for values that will. Prefer these over var, which has surprising function-level scope and hoisting behavior.
const siteName = "CaliberTek";
let visitors = 0;
visitors = visitors + 1;
console.log(siteName, visitors); // CaliberTek 1Step 2: Learn the primitive data types
JavaScript's primitives are string, number, boolean, undefined, null, bigint, and symbol. Use typeof to check a value's type.
console.log(typeof "hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (a long-standing quirk)Step 3: Compare values with strict equality
== converts types before comparing, which can hide bugs. === compares both value and type, so prefer it.
console.log(5 == "5"); // true (type coercion)
console.log(5 === "5"); // false (different types)Step 4: Work with objects and arrays
Objects store named properties and arrays store ordered lists. A const object or array can't be reassigned, but its contents can still change.
const user = { name: "Ava", skills: ["JavaScript", "CSS"] };
user.skills.push("HTML");
console.log(user.skills.length); // 3FAQs
- Should I still use var?
- In new code, no. let and const have block scope and avoid the hoisting surprises that var causes. You'll mainly see var in older code.
- Why does typeof null return 'object'?
- It's a historical bug from the first version of JavaScript that was never fixed to avoid breaking existing websites. Check for null explicitly with value === null.
Summary
Use const by default, let when you must reassign, know the primitive types, and compare with ===. These habits prevent many common beginner bugs.
Comments
Log in or create a free account to join the discussion.