0
0
Javascriptprogramming~10 mins

Object keys and values in Javascript - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Object keys and values
Start with an object
Get keys using Object.keys(obj)
Get values using Object.values(obj)
Use keys and values as arrays
End
We start with an object, then extract its keys and values as arrays to use them separately.
Execution Sample
Javascript
const obj = {a: 1, b: 2};
const keys = Object.keys(obj);
const values = Object.values(obj);
console.log(keys);
console.log(values);
This code gets the keys and values from an object and prints them.
Execution Table
StepActionExpressionResult
1Create objectconst obj = {a: 1, b: 2};{a: 1, b: 2}
2Get keysObject.keys(obj)['a', 'b']
3Get valuesObject.values(obj)[1, 2]
4Print keysconsole.log(keys)['a', 'b']
5Print valuesconsole.log(values)[1, 2]
💡 All keys and values extracted and printed.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
objundefined{a:1, b:2}{a:1, b:2}{a:1, b:2}{a:1, b:2}
keysundefinedundefined['a', 'b']['a', 'b']['a', 'b']
valuesundefinedundefinedundefined[1, 2][1, 2]
Key Moments - 2 Insights
Why do Object.keys(obj) and Object.values(obj) return arrays?
Because keys and values are multiple items, JavaScript groups them into arrays for easy use, as shown in steps 2 and 3.
Are the keys and values always in the same order?
Yes, Object.keys and Object.values return arrays where the order of keys matches the order of values, so keys[i] corresponds to values[i]. See steps 2 and 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'keys' after step 2?
A['a', 'b']
B[1, 2]
C{a:1, b:2}
Dundefined
💡 Hint
Check the 'Result' column for step 2 in the execution_table.
At which step do we get the array of values from the object?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look for Object.values(obj) in the 'Expression' column.
If the object had a new key 'c: 3', how would the 'keys' array change after step 2?
A['a', 'b']
B['a', 'b', 'c']
C['c', 'a', 'b']
D[1, 2, 3]
💡 Hint
Object.keys returns keys in insertion order, see variable_tracker for keys array.
Concept Snapshot
Object.keys(obj) returns an array of all keys in obj.
Object.values(obj) returns an array of all values in obj.
Keys and values arrays have matching order.
Use these to loop or access keys/values separately.
Example: keys = Object.keys(obj); values = Object.values(obj);
Full Transcript
We start with an object that has keys and values. Using Object.keys, we get an array of the keys. Using Object.values, we get an array of the values. Both arrays keep the same order so each key matches its value by position. We print these arrays to see the keys and values separately. This helps when you want to work with keys or values alone.