30 Days Of JavaScript.8
Day 8. Objects
On
Day 8, I learned about scope, objects, and how to create and manipulate the objects. Reading through the documents would help a lot.

Scope
To declare a variable, we use the keyword var, let, and const. A variable can be declared at different scope. Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript.
Variable scopes can be global or local. Global variables are those declared outside of a block. Local variables are those declared inside of a block. Anything declared without let, var, or const is scoped at global level.
Window Global Object
The values declared without var, let or const are accessible without using console.log(). It means the values are already available in the window.
Global Scope
A globally declared variable can be accessed everywhere in the same file. But, the term ‘global’ is relative. It can be global to file, or it can be global relative to some block of codes.
Local Scope
A variable declared as local can be accessed only in certain block code, inside the curly brakets({}).
- Block Scope / Function Scope
If a variable is declared inside a function(Function Scope) or a block(Block Scope), the variable would only be accessible within the function or the block.
The global scope is accessible both inside and outside the function or the block.
A variable declared with var is only scoped to function, but a variable declared with let or const could be scoped to any block(function block, if block, loop block, etc). A block in JavaScript is a code between two curly brackets({}).
//`var` is scoped to the function
function letsLearnScope() {
var gravity = 9.81;
console.log(gravity);
}
letsLearnScope(); //9.81
console.log(gravity); //Uncaught ReferenceError: gravity is not defined
//In a block that is not a function(if, for, etc), `var` can be accessed outside the block.
if (true) {
var gravity = 9.81;
console.log(gravity); // 9.81
}
console.log(gravity); // 9.81
for(var i = 0; i < 3; i++){
console.log(i) // 0, 1, 2
}
console.log(i) // 3
When I use let, the variable is block-scoped and it will not infect other parts of the code.
// `let` and `const` are scoped to any block where it's declared.
function letsLearnScope() {
const gravity = 9.81;
console.log(gravity);
}
letsLearnScope(); //9.81
console.log(gravity); //Uncaught ReferenceError: gravity is not defined
if (true) {
const gravity = 9.81;
console.log(gravity);
} //9.81
console.log(gravity); //Uncaught ReferenceError: gravity is not defined
for (let i = 0; i < 3; i++) {
console.log(i);
} //0, 1, 2
console.log(i); //Uncaught ReferenceError: i is not defined
let and const are only different in whether the value can be changed or not. Using let and const is highly recommended for writing clean code and avoiding debug mistakes.
let: any value that can be changedconst: any constant value, array, object, arrow function and function expression
Object
Everything can be an object. Objects have properties and those properties have values. So an object is a key value pair. To create an object literal, we use two curly braces({}).
1. Creating an empty object
const person = {};
2. Creating an object with values
The person object now has firstName, lastName, age, location, skills, and isMarried properties. The value of properties(= keys) could be a string, number, boolean, an object, null, undefined, or a function.
const person = {
firstName: 'Jane',
lastName: 'Doe',
age: 23,
country: 'Canada',
city: 'Vancouver',
skills: ['HTML', 'CSS', 'JavaScript'],
isMarried: false
}
console.log(person); //{firstName: 'Jane', lastName: 'Doe', age: 23, country: 'Canada', city: 'Vancouver', ...}
3. Getting values from an object
object.property
object['property']
-
What’s the difference? MDN Document / Stackoverflow
-
Dot Notation : Use ‘ . ‘ followed by the key name if the key name is one word.
-
Square Bracket Notation : Use square bracket and a quote([’ ‘]) if the key name is a string or a variable.
const person = {
firstName: 'Jane',
lastName: 'Doe',
age: 23,
country: 'Canada',
city: 'Vancouver',
skills: ['HTML', 'CSS', 'JavaScript'],
isMarried: false,
//I didn't know what 'this' was, so I tried 'person' instead and it worked too.
getFullName: function() {
return `${this.firstName} ${this.lastName}`;
},
'address': 'somewhere'
}
//accessing values using '.'
console.log(person.firstName); //Jane
console.log(person.getFullName()); //Jane Doe
//accessing values using ['']
console.log(person['country']); //Canada
console.log(person['age']); //23
//for 'address', I can only use ['']
console.log(person['address']); //somewhere
4. Creating object methods
Looking at the object above, I can see a getFullName property, which is a function inside the object. It is called an object method.
const person = {
...
getFullName: function() {
return `${this.firstName} ${this.lastName}`
}
}
this keyword refers to the object itself.(This is the reason why person.firstName worked same as this.firstName. The object is person, so it actually meant the same.) I can use it to access the values of different properties of the object.
I cannot use an arrow function as an object method, because the word ‘this’ refers to the window inside an arrow function, instead of the object itself.
5. Setting a new key for an object
An object is a mutable data structure, and I can modify the content of an object after it’s created.
const person = {
firstName: 'Jane',
lastName: 'Doe',
age: 23,
country: 'Canada',
city: 'Vancouver',
skills: ['HTML', 'CSS', 'JavaScript'],
isMarried: false,
getFullName: function() {
return `${this.firstName} ${this.lastName}`;
},
'address': 'somewhere'
}
//adding new key for an object
person.title = 'student';
person.skills.push('React');
person.getPersonInfo = function() {
let skillsWithoutLastSkill = this.skills.splice(0, this.skills.length - 1).join(', ');
//I thought I could also use 'this.skills[this.skills.length - 1]
let lastSkill = this.skills.splice(this.skills.length - 1)[0];
let skills = `${skillsWithoutLastSkill}, and ${lastSkill}`
let fullName = this.getFullName()
let statement = `${fullName} is a ${this.title}. She studies ${skills}.`;
return statement;
}
console.log(person.getPersonInfo());
//Jane Doe is a student. She studies HTML, CSS, JavaScript, and React.
6. Object Methods
1) Object.assign()
It copies an object without modifying the original object.
Object.assign(target, ...sources)
-
Parameters :
target,sourcestargetis returned after it is modified bysourcesproperties.sourcescontains the properties I want to apply. -
Return Value : The target object.
const person = {
firstName: 'Jane',
lastName: 'Doe',
age: 23,
country: 'Canada',
city: 'Vancouver',
mbti: {
ei: 'introverted',
sn: 'intuition',
tf: 'feeling',
jp: 'perception'
},
skills: ['HTML', 'CSS', 'JavaScript'],
isMarried: false,
getFullName: function() {
return `${this.firstName} ${this.lastName}`
},
'address': 'somewhere'
}
const copyPerson = Object.assign({}, person);
2) Object.keys()
It gets the keys or properties of an object as an array.
Object.keys(obj)
-
Parameters :
objThe object of which the enumerable’s own properties are to be returned. -
Return Value : An array of strings that represent all the enumerable properties of the given object.
const keys = Object.keys(copyPerson);
console.log(keys);
//(9) ['firstName', 'lastName', 'age', 'country', 'city', 'skills', 'isMarried', 'getFullName', 'address']
const mbti = Object.keys(copyPerson.mbti)
console.log(mbti) //(4) ['ei', 'sn', 'tf', 'jp']
3) Object.values()
It gets the values of an object as an array.
Object.values(obj)
-
Parameters :
objThe object whose enumerable own property values are to be returned. -
Return Value : An array containing the given object’s own enumerable property values.
const values = Object.values(copyPerson);
console.log(values);
//(10) ['Jane', 'Doe', 23, 'Canada', 'Vancouver', {…}, Array(3), false, ƒ, 'somewhere']
4) Object.entries()
It gets the keys and values in an array.
Object.entries(obj)
-
Parameters :
objThe object whose own enumerable string-keyed property[key, value]pairs are to be returned. -
Return Value : An array of the given object’s own enumerable string-keyed property
[key, value]pairs.
const entries = Object.entries(copyPerson);
console.log(entries);
//(10) [Array(2), Array(2), Array(2),... Array(2)]
['firstName', 'Jane'], ['lastName', 'Doe'],... ['address', 'somewhere']
5) hasOwnProperty()
It checks if a specific key or property exists in an object, even if the value is null or undefined.
hasOwnProperty(prop)
-
Parameters :
stringThe string name or symbol of the property to test. -
Return Value : Returns
trueif the object has the specified property as own property;falseotherwise.
console.log(copyPerson.hasOwnProperty('city')); //true
console.log(copyPerson.hasOwnProperty('score')); //false
The document says that this method can be called on most JavaScript objects. For example, an array is an object, so I can use hasOwnProperty() method to check whether an index exists.
let fruits = ['Apple', 'Banana','Watermelon', 'Orange'];
fruits.hasOwnProperty(3); //true ('Orange')
Leave a comment