Package homeJavaScript DeveloperStudy guide
Study guide

Chapter 123% of the exam70 min

Variables, Types, and Collections

How to declare and initialize variables with var, let and const; work with strings, numbers and dates; predict type coercion and truthy or falsy values; manipulate arrays with mutating and non-mutating methods, Sets and Maps; and read and write JSON.

By the end of this chapter you can

  • Create variables and initialize them correctly with var, let and const
  • Use strings, numbers and dates effectively
  • Predict type coercion and its effects
  • Distinguish truthy and falsy values
  • Manipulate data with arrays
  • Work with JSON responses

Declaring and initializing variables

Scenario: A developer is building a Lightning web component that reads orders from an API, totals them and shows them sorted. Most bugs in this kind of code come from variable scope, types and array methods.

JavaScript has three ways to declare a variable:

var let const
Scope Function (or global) Block { } Block { }
Hoisting Hoisted and initialized to undefined Hoisted but not initialized: the temporal dead zone Same as let
Reassign Yes Yes No
Redeclare in the same scope Yes No No
Must initialize No No Yes
console.log(a); // undefined: var is hoisted
var a = 1;
 
console.log(b); // ReferenceError: b is in the temporal dead zone
let b = 2;
 
const c; // SyntaxError: missing initializer in const declaration

const prevents reassignment of the variable, not changes to the value it holds:

const order = { total: 10 };
order.total = 20;      // allowed: the object changes
order = { total: 30 }; // TypeError: Assignment to constant variable

Use const by default, let when the value must change, and avoid var. A block-scoped let in a loop gives each iteration its own binding, which matters for callbacks created inside the loop.

A variable declared without a value is undefined. Assigning to a name that was never declared creates a global variable in sloppy mode, and throws a ReferenceError in strict mode, which modules and classes always use.

Types

JavaScript has seven primitive types and one structural type, object. Variables don't have types; values do, so one variable can hold a number and later a string.

Value typeof result
"text", 'text', `text` "string"
42, 3.14, NaN, Infinity "number"
10n "bigint"
true, false "boolean"
undefined "undefined"
Symbol("id") "symbol"
null "object": a long-standing quirk; test with x === null
{}, [], new Date() "object": use Array.isArray(x) for arrays
function () {}, class {} "function"

Primitives are copied by value; objects, arrays and functions are shared by reference:

let a = 1;
let b = a;
b = 2;            // a is still 1
 
const x = { n: 1 };
const y = x;
y.n = 2;          // x.n is 2 too: x and y point to the same object

Exam tip: Reading a var before its declaration gives undefined; reading a let or const before it throws a ReferenceError. const objects and arrays can still be changed.

Strings, numbers and dates

Strings

Strings are immutable: string methods return new strings.

Method Example Result
slice(start, end) "Salesforce".slice(0, 5) "Sales"
slice with a negative index "Salesforce".slice(-5) "force"
substring(start, end) "Salesforce".substring(5, 0) "Sales" (swaps the arguments)
indexOf, includes "a,b".includes(",") true
startsWith, endsWith "INV-1".startsWith("INV") true
split "a,b,c".split(",") ["a", "b", "c"]
replace, replaceAll "a-a".replace("-", "+") "a+a" (first match only)
trim, padStart "7".padStart(3, "0") "007"
toUpperCase, toLowerCase "js".toUpperCase() "JS"

Template literals use backticks and ${} for expressions, and can span lines: `Total: ${qty * price}`.

Numbers

All numbers are 64-bit floating point, except BigInt values such as 10n for very large integers.

  • 0.1 + 0.2 is 0.30000000000000004: round when you display money, for example with toFixed(2), which returns a string.
  • Number("42") is 42; Number("42px") is NaN, while parseInt("42px") is 42 and parseFloat("3.5kg") is 3.5.
  • NaN ("not a number") is a number: typeof NaN is "number". Use Number.isNaN() to test for it.
  • Number.isInteger(5.0) is true. Number.MAX_SAFE_INTEGER is the largest integer that numbers can represent exactly.
  • Math.round, Math.floor, Math.ceil, Math.max and Math.random cover common calculations.

Dates

const d = new Date(2026, 0, 31); // 31 January 2026: months start at 0
d.getMonth();   // 0
d.getDate();    // 31: the day of the month
d.getDay();     // 6: the day of the week, 0 is Sunday
d.getFullYear(); // 2026
Date.now();      // milliseconds since 1 January 1970 UTC
d.toISOString(); // a UTC string such as "2026-01-31T…Z"

Subtracting two dates gives the difference in milliseconds. Intl.DateTimeFormat and toLocaleDateString() format dates for a locale. MDN now calls Date a legacy API and recommends the newer Temporal API for new code, but the exam and most existing code use Date.

Exam tip: getDay() is the weekday and getDate() the day of the month; months are 0 to 11. toFixed returns a string, and parseInt stops at the first character that isn't a digit.

Type coercion and truthy or falsy values

Type coercion is JavaScript converting a value from one type to another automatically.

How operators coerce values. The plus operator with a string joins text: 1 + "2" is "12", "1" + 2 + 3 is "123", 1 + 2 + "3" is "33", and "a" + null is "anull". Minus, times, divide, remainder and unary plus convert to numbers: "6" / "2" is 3, "5" - 2 is 3, true + 1 is 2, and "a" * 1 is NaN. Plus works left to right: once one side is a string, the rest is joined as text. == converts types before comparing; === never does. + with a string: joins text 1 + "2" → "12" "1" + 2 + 3 → "123" 1 + 2 + "3" → "33" "a" + null → "anull" - * / % and unary +: numbers "6" / "2" → 3 "5" - 2 → 3 true + 1 → 2 "a" * 1 → NaN + works left to right: once one side is a string, the rest is joined as text == converts types before comparing; === never does
How the + operator and the other arithmetic operators coerce values

Expression Result Why
1 + "2" "12" + with a string concatenates
"3" * "4" 12 *, - and / convert to numbers
"5" - 2 3
true + 1 2 true becomes 1
+"42" 42 Unary + converts to a number
[] + [] "" Arrays become strings
"b" + "a" + +"a" + "a" "baNaNa" +"a" is NaN

== and ===

  • === (strict equality) compares value and type, with no coercion: 1 === "1" is false.
  • == (loose equality) coerces first: 1 == "1" is true, 0 == "" is true, null == undefined is true, but null == 0 is false.
  • NaN is never equal to anything, including itself: use Number.isNaN(x) or Object.is(x, NaN).
  • Objects and arrays compare by reference: [1] === [1] is false.

Truthy and falsy

In a condition, every value is treated as true or false. The language has eight falsy values:

false, 0, -0, 0n, "" (empty string), null, undefined and NaN.

Browsers add one legacy oddity, document.all, which is also falsy; you won't need it.

Everything else is truthy, including "0", "false", [], {} and function () {}.

if ([]) console.log("runs");      // an empty array is truthy
Boolean("0");                     // true
!!undefined;                      // false
const name = input || "Guest";    // "Guest" if input is any falsy value
const count = input ?? 0;         // 0 only if input is null or undefined

Exam tip: Prefer ===. Memorize the eight falsy values; [], {} and "0" are truthy. || falls back on any falsy value, ?? only on null or undefined.

Working with arrays

Array methods that change the original array: push and pop, unshift and shift, splice, sort and reverse, fill and copyWithin. Methods that return something new and leave the array alone: map, filter and slice; concat and flat; reduce, find and findIndex; some, every, includes and join; toSorted, toReversed and toSpliced. forEach returns undefined, so nothing can be chained after it. Change the original array push, pop unshift, shift splice sort, reverse fill, copyWithin Return something new map, filter, slice concat, flat reduce, find, findIndex some, every, includes, join toSorted, toReversed, toSpliced forEach returns undefined, so nothing can be chained after it
Mutating and non-mutating array methods

Method What it does Changes the array? Returns
push(x) / pop() Add / remove at the end Yes New length / removed item
unshift(x) / shift() Add / remove at the start Yes New length / removed item
splice(start, count, ...items) Remove and/or insert items Yes Array of removed items
slice(start, end) Copy a part No New array
sort(compareFn) / reverse() Order the items Yes The same array
map(fn) Transform each item No New array, same length
filter(fn) Keep items that pass No New array
reduce(fn, initial) Combine into one value No The value
find(fn) / findIndex(fn) First match / its index No Item or undefined / index or -1
some(fn) / every(fn) Does any / every item pass? No Boolean
includes(x) / indexOf(x) Is it there? / where? No Boolean / index or -1
forEach(fn) Run code for each item No undefined
concat, flat, join Merge, flatten, make a string No New array / string
const totals = [25.5, 9, 40];
totals.map((t) => t * 2);                 // [51, 18, 80]
totals.filter((t) => t > 10);             // [25.5, 40]
totals.reduce((sum, t) => sum + t, 0);    // 74.5
[10, 9, 1].sort();                        // [1, 10, 9]: compared as strings
[10, 9, 1].sort((a, b) => a - b);         // [1, 9, 10]

More useful tools:

  • Spread copies or merges arrays: const copy = [...totals], [...a, ...b].
  • Destructuring unpacks values: const [first, , third] = totals;.
  • Array.from("abc") makes ["a", "b", "c"]; Array.isArray(x) checks for an array.
  • toSorted, toReversed and toSpliced work like sort, reverse and splice but return a new array and leave the original alone.
  • A Set stores unique values: [...new Set([1, 1, 2])] is [1, 2].
  • A Map stores key-value pairs with keys of any type, remembers insertion order and has a size.

Exam tip: Check whether a method changes the original array: splice, sort and reverse do; slice, map and filter don't. forEach returns undefined, so you can't chain after it.

Working with JSON

JSON (JavaScript Object Notation) is a text format for data. In JSON, keys and strings use double quotes, and values can be strings, numbers, booleans, null, arrays and objects: no functions, undefined or comments.

Method Converts Example
JSON.parse(text) A JSON string into a JavaScript value JSON.parse('{"a":1}').a is 1
JSON.stringify(value) A JavaScript value into a JSON string JSON.stringify({ a: 1 }) is '{"a":1}'
JSON.stringify({ name: "Ada", run() {}, nick: undefined, at: new Date(0) });
// '{"name":"Ada","at":"1970-01-01T00:00:00.000Z"}'
JSON.stringify({ a: 1 }, null, 2); // pretty-printed with 2-space indentation
JSON.parse("{'a':1}");             // SyntaxError: single quotes aren't valid JSON
  • JSON.stringify drops functions and undefined properties, and turns Date objects into ISO strings. JSON.parse doesn't turn them back into dates.
  • The optional replacer of stringify and reviver of parse transform values on the way.
  • JSON.parse(JSON.stringify(obj)) makes a quick deep copy, losing dates, functions and undefined; structuredClone(obj) keeps more types.
  • A fetch response's json() method parses the body as JSON for you.

Exam tip: Invalid JSON, such as single quotes or a trailing comma, makes JSON.parse throw a SyntaxError. After a round trip through JSON, dates are strings and functions are gone.

Hands-on exercise

Clean up an order list

Practise variables, types, arrays and JSON on one small data set.

Use a free Salesforce Developer Edition org — never a production org.

0 of 7 steps done

How to check your work: You can explain why the total needed `Number()`, why the sort used a comparator and a copy, what happened to the date in JSON, and each coercion result.

Domain quiz: Variables, Types, and Collections

10 questions from the 52 in this domain, different each time and checked as you go. Anything you miss is saved to Mistakes review.

Questions
10
Time
Untimed
Feedback
After each answer

New questions each time you start, drawn from the bank, unseen ones first.

Objects, Functions, and Classes