Classes and Objects
Working with JavaScript variables, Classes, and Objects
As you begin your journey into the world of JavaScript and programming, you'll realize that variables, objects, and classes are at the heart of the language. They are the building blocks of any good JavaScript program, and mastering them will set you on the path to becoming a true JavaScript ninja!
What is a variable
?β
A variable is simply an identifier or container that holds a value. It can contain data of different types, such as boolean, string, number, object, and array.
π‘ A boolean variable holds either True or False, a string variable contains a sequence of characters enclosed in quotation marks, and an array is a collection of values of any data type.
From the image above, the cup represents an empty variable; the milk and coffee are data of different data types. When you put the data into the cup, the cup becomes a variable of data type, coffee or milk.
Create variables
in JavaScriptβ
To declare (create) variables in JavaScript, you need to use some built-in keywords such as var, let, and const. Let's talk briefly about them.
π The var
keywordβ
The var keyword is the oldest way of declaring variables in JavaScript, and it's not advisable to use it in your JavaScript programs because it is not block scope.
A variable is block-scoped when it only exists within the curly braces where it was declared and cannot be accessed outside the curly braces. Letβs take a look at some examples.
var ageInWords = "Eighteen"; //ageInWords holds the string value
var male = true; //male holds a boolean value
/*-- Block scope Example--*/
if(true) {
var myAge = 20;
const yourAge= 18
}
console.log(myAge) //prints 20
console.log(yourAge) //ReferenceError: yourAge is not defined (Block-scoped)
π The let
keywordβ
The let keyword is a suitable alternative to var. It is block-scoped and used for declaring variables whose values may change at some point during execution.
let age = 20; //sets a variable to 20
age = 5; // re-assign age to 5
console.log(age); // prints 5 to the console
The code snippet above shows a variable created using the let
keyword with an initial value of 20, then changed to 5.
π The const
keywordβ
The const keyword is used to declare variables that cannot be re-assigned to another value. It holds constant values.
const age = 20;
age = 10;
console.log(age) //returns a TypeError: Assignment to constant variable. (Invalid)
π‘ Donβt use the
var
keyword. Useconst
when you need to declare a constant andlet
when the variable can be re-assigned to another value.
π Naming variables
in JavaScriptβ
When naming variables in JavaScript, there are a few things you need to consider.
- Variables can only start with a letter, underscore, or dollar sign. Numbers and other symbols can come after the first position.
const firstName = 18;
let _2much = "Dave";
const $age = 24
const 2people = true //invalid naming convention
- Do not use JavaScript keywords as variable names. JavaScript keywords are reserved words used for a specific purpose.
const switch = 18;
let for = "Dave";
const const = 24;
/*-- They are all invalid naming conventions --*/
- Use variable names that describe the value they hold or contain.
What are objects
in JavaScript?β
An object is an entity that has a collection of properties arranged in key-value pairs. The key is a property name, and every property has a value assigned to it within the object.
The image above shows an illustration of how an object works. Assuming the cup is a JavaScript object with the following properties colour, material, and size. How do we represent it in JavaScript?
const cup = {
colour: "white",
material: "porcelain",
size: "medium"
}
The code snippet above creates a JavaScript object for the cup. The name of the JavaScript object is cup
, and its properties are the key-value pairs.
π‘ An object can have properties of different data types. The cup object can also have a property of
isBlack: false
.
π Accessing object properties
in JavaScriptβ
You can access the property of an object using the dot notation or bracket notation.
//ππ» Dot notation
console.log(cup.colour) //Output: white
console.log(cup.material) //Output: porcelain
console.log(cup.size) ////Output: medium
//ππ» Bracket notation
console.log(cup["colour"]) //Output: white
console.log(cup["material"]) //Output: porcelain
console.log(cup["size"]) ////Output: medium
π‘ In dot notation, you can access each property by using the syntax
object.propertyname
, and in bracket notation, useobject["propertyname"]
.
Use camel case to join property names that are more than one word.
const cup = {
colour: "white",
material: "porcelain",
size: "medium",
dateCreated: "02-05-2023"
}
console.log(cup.dateCreated) //Output is 02-05-2023
console.log(cup["dateCreated"]) //Output is 02-05-2023
In JavaScript objects, if a property name is spaced, you need to put it in quotes, and you can only access its value using the bracket notation.
const cup = {
colour: "white",
material: "porcelain",
size: "medium",
"date created": "02-05-2023"
}
console.log(cup["date created"]) //Output is 02-05-2023
π Modifying
JavaScript objectsβ
A JavaScript object property can be modified by referencing and updating its value. For example, letβs change the material and colour of the cup.
const cup = {
colour: "white",
material: "porcelain",
size: "medium",
"date created": "02-05-2023"
}
cup.colour = "black"
cup["material"] = "glass"
console.log(cup)
// The object becomes ππ»
{
colour: 'black',
material: 'glass',
size: 'medium',
'date created': '02-05-2023'
}
The code snippet above changes the values of the object properties - colour and material.
Recall that the const
keyword creates constant variables. Therefore, you can not re-assign an object created with the const
keyword to another value, but you can change its properties.
const cup = {
colour: "white",
material: "porcelain",
size: "medium",
"date created": "02-05-2023"
}
//ππ» Invalid modification
cup = {
colour: "black",
material: "glass",
size: "medium",
"date created": "02-05-2023"
}
console.log(cup) //returns a TypeError: Assignment to constant variable
π‘ You can only re-assign an object to another value when it is declared using the
let
keyword.
What are classes
in JavaScript?β
A class is a blueprint for creating objects that have the same properties and functions. It provides a template for creating multiple objects with similar features but different values.
The image above shows a class of domestic animals containing a dog and a cat. The class provides the blueprint that determines the kind of animals present. Here is an example of a JavaScript class describing the image above.
class Domestic {
constructor(name, colour, owner) {
this.name = name;
this.colour = colour;
this.owner = owner;
}
}
//ππ» instances of the class
const dog = new Domestic("Swift", "White", "Mr. Adrian")
const cat = new Domestic("Pretty", "Brown", "Mrs. Banks")
console.log(dog)
//Output: Domestic { name: 'Swift', colour: 'White', owner: 'Mr. Adrian' }
console.log(cat)
//Output: Domestic { name: 'Pretty', colour: 'Brown', owner: 'Mrs. Banks' }
To create a class in JavaScript, you need to add the class
keyword followed by the name of the class name in sentence case.
class ClassName {}
Next, add a constructor
method containing the class attributes.
class Domestic {
constructor(name, colour, owner) {
this.name = name;
this.colour = colour;
this.owner = owner;
}
}
From the code snippet above, the class - Domestic
has name, colour, and owner attributes. The this
keyword reference any current object initiated from the class and sets its value to the object's parameter.
Finally, you can create new object instances of the class by using the new
keyword and passing the constructor parameters into the class.
//ππ» instances of the class
const dog = new Domestic("Swift", "White", "Mr. Adrian")
const cat = new Domestic("Pretty", "Brown", "Mrs. Banks")
π Accessing and modifying instances of a classβ
You can access and modify instances of a class the same way it's done in objects. Moreover, instances of a class are objects of that class.
const dog = new Domestic("Swift", "White", "Mr. Adrian")
const cat = new Domestic("Pretty", "Brown", "Mrs. Banks")
//ππ» change the name of the cat and dog object
dog.name = "King"
cat["name"] = "Queen"
console.log(dog)
//ππ» Output: Domestic { name: 'King', colour: 'White', owner: 'Mr. Adrian' }
console.log(cat)
//ππ» Domestic { name: 'Queen', colour: 'Brown', owner: 'Mrs. Banks' }
The code snippet above changes the name of the cat and dog object after initiation.
β IN Summaryβ
Variables
are like containers that hold data. They allow you to store and manipulate data of different types, such as numbers, strings, or boolean values.Objects
, on the other hand, are like containers that hold multiple pieces of information - properties. These properties can be anything from strings and numbers to other objects and arrays.Classes
are templates for objects. They provide a blueprint that you can use to create multiple objects with the same properties and behaviours.
Understanding what variables, objects, and classes are, is essential for a beginner in JavaScript. By mastering these basic concepts, you're well on your way to building more complex programs in JavaScript.
β Resourcesβ
- π Access AppSeed for more starters and support
- π Deploy Projects on Aws, Azure and DO via DeployPRO
- π Create landing pages with Simpllo, an open-source site builder
- π Build apps with Django App Generator (free service)