Back to Interview Prep
Course progress0/14 chapters · 0%

Chapter 2 of 34

~10 min

Variables & Data Types

Variables are named containers for values, and every value in JavaScript has a data type. Getting comfortable with `var`, `let`, `const`, and the language's primitive types is the foundation everything else builds on.

var, let, and const

`var` is the original way to declare variables - it is function-scoped, can be redeclared, and gets "hoisted" to the top of its scope. `let` and `const`, added in ES6, are block-scoped instead, meaning they only exist inside the `{ }` they were declared in.

`let` allows reassignment but not redeclaration in the same scope. `const` allows neither - once assigned, the binding cannot be reassigned (though if it holds an object or array, the contents can still be mutated).

Try it yourself

<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>

Output

Hoisting and the Temporal Dead Zone

`var` declarations are hoisted and initialized to `undefined`, so you can reference them before the line they are declared on (you just get `undefined`). `let` and `const` are also hoisted, but they stay uninitialized in what is called the "temporal dead zone" until their declaration line runs - accessing them earlier throws an error.

This is one reason `let`/`const` catch bugs that `var` would silently let slide.

Primitive Data Types

JavaScript has seven primitive types: `string`, `number`, `boolean`, `undefined`, `null`, `symbol`, and `bigint`. Primitives are immutable and compared by value.

`typeof` tells you a value's type at runtime, though it has a famous quirk: `typeof null` returns `"object"` for historical reasons, not `"null"`.

Try it yourself

<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>

Output

A First Look at Type Coercion

JavaScript is loosely typed, so it will often convert values between types automatically. `"5" + 1` becomes `"51"` (string concatenation), while `"5" - 1` becomes `4` (numeric subtraction forces a conversion). This is called type coercion, and it is a common source of bugs - we will dig deeper into `==` vs `===` in the gotchas topic.

Coding challenge

Declare a const for your name (string), a let for your age (number), and a const for whether you are learning JavaScript (boolean). Log all three values along with their typeof result.

<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>

Output

Answer every question below to mark this chapter as complete.

Quiz Yourself

Score: 0/4

1. Which keyword allows reassignment but is block-scoped?

2. What does `typeof null` return?

3. What happens if you access a `let` variable before its declaration line runs?

4. Which of these is NOT one of JavaScript's primitive types?

You're viewing a free lesson. Sign up free to track your progress and unlock the full course.Sign up freeSign in