Values, functions, objects & arrays
Write JavaScript with const/let, arrow functions, destructuring and array methods.
By Invicly Tech, , in Frontend with React & Next.js. About 9 minutes to read.
In short
Modern JavaScript uses const and let, arrow functions, destructuring and array methods. These features make data transformations short and predictable, and they appear everywhere in React code.
Explained simply
JavaScript is the programming language that runs in every web browser. HTML is the structure, CSS is the look, and JavaScript is the behavior: what happens when you click, type or load data.
Most of your code works with a few building blocks. Values are pieces of data like 42, "hello" or true. Variables are names that point to values. Functions are reusable steps. Objects group related values by name, and arrays keep values in order.
Modern JavaScript gives you short, safe ways to do common jobs. const and let create variables. Arrow functions are compact. Destructuring pulls values out of objects. Methods like map and filter turn one list into another without writing loops by hand.
A big idea to grasp early is that objects and arrays are shared by reference. Two variables can point to the same object, like two people holding the address of one house. Change the house through one address and the other person sees the change too.
Press Play on a diagram to walk through it one step at a time.
- Primitives
- string
- number
- boolean
- null and undefined
- bigint and symbol
- Objects
- plain objects
- arrays
- functions
- Map and Set
- Date
- b gets its own copy
- b = 5 leaves a unchanged
- === compares values
- Like photocopying a note
- b points to the same object
- b.x = 5 changes a.x too
- === compares addresses
- Like sharing a house key
- 1orders
Raw array of 100 order objects
- 2filter
Keep orders with status paid
- 3map
Turn each order into its total
- 4reduce
Add totals into one number
- 5Result
Revenue, with the original array untouched
In depth
Primitives vs references
JavaScript has seven primitive types: string, number, bigint, boolean, undefined, null and symbol. Primitives are copied by value. let b = a with a number gives b its own copy.
Everything else is an object, including arrays and functions. A variable holding an object stores a reference, like an address. const b = a now gives two names for one object, so b.push(4) also changes a. To get a separate copy, spread it ([...a] or {...obj}) for a shallow copy, or use structuredClone(obj) for a deep copy with nested objects.
This is also why === on two different objects with the same contents is false: it compares addresses, not contents.
- Primitives: copied by value
- Objects and arrays: shared by reference
- Spread makes a shallow copy
- structuredClone makes a deep copy
Scope and closures
Scope is where a variable can be seen. let and const are block-scoped: a variable declared inside { } exists only there. Functions can read variables from the scopes around them.
A closure happens when a function keeps using those outer variables after the outer function has finished. The inner function carries a backpack of the variables it needs. That is how a counter function can remember its count between calls, and how event handlers remember the data they were created with.
Closures are everywhere in React too: every handler and effect closes over the props and state of the render that created it.
- 1Call makeCounter()
Creates let count = 0
- 2Return inner function
It uses count
- 3makeCounter finishes
count stays alive in the closure
- 4Call counter()
count becomes 1
- 5Call counter() again
count becomes 2
What this means
this is decided by how a regular function is called, not where it is written. Called as obj.method(), this is obj. Called as a plain function, this is undefined in strict mode. Passed as a callback, it often loses its object.
Arrow functions do not have their own this. They use the this of the code around them. That makes arrows ideal for callbacks inside methods, and a poor choice for object methods that need this themselves.
- obj.method()
- this is obj
- Plain call fn()
- undefined in strict mode
- Passed as a callback
- Often loses its object
- Arrow function
- No own this
- Uses the surrounding this
Equality and truthiness
Use === and !== for comparisons. The loose == converts types first, so 0 == "" is true, which surprises people. Only null == undefined is a common, intended loose check.
In conditions, six values count as false (falsy): false, 0, "" (empty string), null, undefined and NaN. Everything else is truthy, including "0", [] and {}. Use ?? (nullish coalescing) for defaults when 0 or "" are valid values, because || would replace them.
- count || 10 gives 10 when count is 0
- count ?? 10 keeps 0 and only replaces null or undefined
- user?.address?.city returns undefined instead of crashing
Learn it in 6 short steps
About 1h 20m each. Track them with a timer in your plan.
- 1Declare variables with const and let~1h 20m
- 2Write arrow and regular functions~1h 20m
- 3Destructure objects and arrays~1h 20m
- 4Use spread and rest syntax~1h 20m
- 5Transform data with map, filter, reduce~1h 20m
- 6Understand closures and this~1h 20m
Key points
- Use const by default and let only when you reassign; avoid var.
- Primitives are copied by value; objects and arrays are shared by reference.
- map, filter and reduce return new values instead of changing the original array.
- A closure is a function that remembers variables from where it was created.
- Arrow functions do not have their own this; they use the surrounding one.
Key terms
Tap a card to flip it. 0/5 known
Examples
const users = [
{ name: 'Ana', age: 31, active: true },
{ name: 'Ben', age: 17, active: false },
];
const names = users
.filter((u) => u.active)
.map(({ name }) => name);
const totalAge = users.reduce((sum, u) => sum + u.age, 0);
const updated = { ...users[0], age: 32 };
console.log(names, totalAge, updated);filter, map, reduce, destructuring and spread.
Summarising a shopping cart
A cart is an array of items with a price and quantity. Step 1: map each item to price times quantity. Step 2: reduce those line totals into one sum, starting from 0. Step 3: filter items over 50 to show a "big items" list. Step 4: destructure in the callback parameters to keep it readable. None of these steps change the original cart.
const cart = [
{ name: "Shoes", price: 60, qty: 1 },
{ name: "Socks", price: 5, qty: 3 },
];
const lines = cart.map(({ price, qty }) => price * qty); // [60, 15]
const total = lines.reduce((sum, n) => sum + n, 0); // 75
const big = cart.filter((item) => item.price > 50); // [Shoes]
console.log("Total: " + total);A counter that remembers with a closure
makeCounter creates a variable count, then returns a function that uses it. Step 1: call makeCounter() and store the returned function. Step 2: each call adds 1 to the same count, because the inner function kept a reference to it. Step 3: a second counter gets its own separate count. Nobody outside can change count directly, so it is private.
function makeCounter() {
let count = 0;
return () => {
count += 1;
return count;
};
}
const a = makeCounter();
a(); a(); // 2
const b = makeCounter();
b(); // 1, separate countQuick reference
- Default to const; use let only when you reassign
- Always compare with === and !==
- Falsy: false, 0, "", null, undefined, NaN; everything else is truthy
- Use ?? for defaults when 0 or "" are valid
- obj?.a?.b stops at null or undefined instead of throwing
- map returns a new array; forEach returns undefined
- Shallow copy: [...arr], {...obj}; deep copy: structuredClone(obj)
- sort() changes the array in place; use toSorted() for a copy
Common mistakes
- Mutating an object you thought was a copy because objects are shared by reference.
- Using == instead of === and getting surprising type coercion.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Given const users = [{ name: "Ana", age: 17 }, { name: "Ben", age: 25 }, { name: "Cy", age: 31 }], get an array of names of users aged 18 or older.
- Exercise 2medium
Write countBy(words) that returns an object counting each word, so countBy(["a", "b", "a"]) gives { a: 2, b: 1 }.
- Exercise 3hard
Write once(fn) that returns a new function which calls fn only the first time and returns that first result on every later call.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use var?
- No. var is function-scoped and hoisted in confusing ways. Use const by default and let when you need to reassign.
- What is the difference between null and undefined?
- undefined usually means a value was never set. null is a value you set on purpose to mean "nothing here".
- Is JavaScript the same as Java?
- No. They share some syntax and a similar name for historical marketing reasons, but they are separate languages with different uses.