Reading history

JavaScript Variables and Data Types: let, const, typeof

4 min read 0 views

Learn JavaScript variables with let and const, the primitive data types, typeof, template literals and how type conversion works.

A variable is a named place to keep a value so you can use it later. In modern JavaScript you create variables with let and const. Every value has a data type, such as number, string or boolean, and JavaScript works out the type by itself while the program runs. This lesson shows how to declare variables, what the types are and how JavaScript converts between them.

In this lesson you will learn

  • The difference between let, const and var
  • JavaScript’s primitive data types
  • Checking a type with typeof
  • Template literals for building strings
  • Type conversion and its surprises

Declaring Variables

let score = 10;        // can be reassigned
score = score + 5;

const pi = 3.14159;    // cannot be reassigned
// pi = 3;             // TypeError: Assignment to constant variable.

let city = "Dhaka";
let isOpen = true;
let nothing = null;
let notSet;            // declared but not assigned

console.log(score, pi, city, isOpen, nothing, notSet);

Output

15 3.14159 Dhaka true null undefined
  • let creates a variable you can change later.
  • const creates one that cannot be reassigned. Use it by default and switch to let only when the value must change.
  • A variable declared without a value holds undefined. null is a value you assign on purpose to mean “nothing here”.
  • var is the old keyword. It ignores block scope and allows confusing re-declaration, so modern code avoids it.

Naming rules: names may contain letters, digits, _ and $, cannot start with a digit and cannot be keywords such as let or class. The usual style is camelCase: totalPrice, isLoggedIn.

Data Types and typeof

console.log(typeof 42);           // number
console.log(typeof 4.5);          // number (no separate float type)
console.log(typeof "hi");         // string
console.log(typeof true);         // boolean
console.log(typeof undefined);    // undefined
console.log(typeof null);         // object (a famous old quirk)
console.log(typeof 10n);          // bigint
console.log(typeof [1, 2]);       // object
console.log(typeof { a: 1 });     // object
console.log(typeof function () {}); // function

const user = "Nadia";
const age = 21;
console.log(`${user} is ${age} years old and will be ${age + 1} next year.`);

Output

number
number
string
boolean
undefined
object
bigint
object
object
function
Nadia is 21 years old and will be 22 next year.
TypeExamplesNotes
number42, -3.5, NaN, InfinityOne type for whole and decimal numbers
string"hi", 'hi', `hi`Text, in single, double or back quotes
booleantrue, falseYes/no values
undefinedundefinedNo value has been assigned
nullnullDeliberately empty
bigint10nWhole numbers of any size
symbolSymbol("id")Unique identifiers (advanced)
object{}, [], functionsEverything that is not one of the primitives above
  • typeof null gives "object". This is a bug from JavaScript’s first version that can never be fixed without breaking old websites.
  • Arrays are objects, so typeof cannot tell them apart. Use Array.isArray(value) instead.
  • Template literals use back quotes and ${...} to place values, even whole expressions, inside a string.

Type Conversion

console.log("5" + 2);       // string joining wins
console.log("5" - 2);       // minus converts to number
console.log(Number("42") + 1);
console.log(Number("abc")); // not a number
console.log(String(99) + "!");
console.log(parseInt("120px"), parseFloat("3.5kg"));
console.log(0.1 + 0.2);

Output

52
3
43
NaN
99!
120 3.5
0.30000000000000004
  • If either side of + is a string, JavaScript joins text: "5" + 2 is "52". The other arithmetic operators convert to numbers, so "5" - 2 is 3.
  • Number() converts a whole string; it returns NaN (“not a number”) when it cannot. parseInt() and parseFloat() read digits from the start and stop at the first character that does not fit.
  • 0.1 + 0.2 is not exactly 0.3 because computers store decimals in binary. Round for display with toFixed(2).

Common Mistakes

  1. Adding numbers read from inputs: form values are strings, so "10" + "5" is "105". Convert with Number() first.
  2. Reassigning a const, which throws a TypeError.
  3. Using a variable before declaring it with let or const, which throws a ReferenceError.
  4. Testing for NaN with ===: NaN === NaN is false. Use Number.isNaN(x).

Practice Exercises

Exercise 1. Store a product name and price, then print “Pen costs 20 taka” using a template literal.

Show answer
const product = "Pen";
const price = 20;
console.log(`${product} costs ${price} taka`);

Exercise 2. What does "3" * "4" give, and why?

Show answer

12. The * operator only works on numbers, so both strings are converted to numbers first.

Frequently Asked Questions

Can a const object be changed?

Its contents can. const stops the variable from pointing to a different value, but the properties of an object or the items of an array it holds can still be modified.

What is the difference between null and undefined?

undefined means a value was never set; JavaScript uses it automatically. null is set by the programmer to say a value is intentionally empty.

Summary

  • Use const by default, let when the value changes, and avoid var.
  • Primitives are number, string, boolean, undefined, null, bigint and symbol; everything else is an object.
  • typeof reports a value’s type, with the null quirk.
  • + joins strings when either side is text; convert input with Number().

Next: JavaScript Operators.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *