Fundamentals
Javascript
#Overview
The third layer of your standard website; JavaScript as a basic usage helps to add interactivity to the website e.g. on mouse clicks, cursor movements, and so on. This can be then used to dynamically update the content or the style of the page. Some common elements that make use of JavaScript are image slider, light/dark theme switch, and form validation.
#Beginner Concepts
Variables
Variables are used to store data values in JavaScript. You can declare a variable using the var
, let
, or const
keywords, followed by the name of the variable. For example: var myVariable = "Hello, world!";
Functions
Functions are blocks of code that perform a specific task. You can define a function using the function
keyword, followed by the name of the function and any parameters (the values inside the parenthesis) it takes. A function by itself won’t run unless called.
function addNumbers(x, y) {
return x + y;
}
// Calling the function and passing the parameters;
// x=4, y=6
addNumbers(4, 6);
Conditional Statements
Conditional statements are used to make decisions in JavaScript. You can use the if
, else if
, and else
keywords to create conditional statements.
if (x > y) {
console.log("x is greater than y");
} else if (y > x) {
console.log("y is greater than x");
} else {
console.log("x and y are equal");
}
Loops
Loops are used to repeat a block of code multiple times. You can use the for
, while
, and do while
keywords to create loops.
// for loop example
// the code runs 10 times from 0 - 9
for (var i = 0; i < 10; i++) {
console.log(i);
}
Data Types
Data types determine the type of value stored in a variable like a string or a number. In JavaScript, you do not need to specify the type of each variable which is why it’s considered as a dynamically typed language. And, if you first store a string value e.g. var a = “Hello”
, you can still store values of other data types. E.g. a = 23;
will now store a number and there will be no errors.
There are seven primitive data types; number
, string
, boolean
, null
, undefined
, symbol
, and bigint
. Then there’s Object
which is a complex data type as it can be used to store a collection of data rather than just one single value like in primitive data types.
let num = 21.4 //number; can be whole or decimal
let isBlue = true // boolean; can only be true or false
const name; // undefined variable
const b = null // null variable
// object is defined using curly braces {}
// object consists of a key and a value
const newObject = {
//instead of equals (=) we use colon(:) when assigning value
name: 'Cleric', // comma (,) is used as a separator when adding new property
age: 30
}
Array
Like an object, an array can store multiple values but in an ordered collection. Each value in an array is automatically indexed starting from 0 unlike in an object where you have to provide the key name.
// declaring an array
let newArray = ["Apple", 2, "Beans"]
Here, “Apple” is stored at index 0, the number 2 at index 1, and so on. Using this index we can access the values or modify the array by adding, removing, filtering, and many more using the array method
. Some common methods are push()
, pop()
, filter()
, and map()
.
console.log(newArray) //output: Apple, 2, Beans
//to find the length of the array
console.log(newArray.length) //output: 3
// Get single element
console.log(newArray[1]) //Output: 2
// push method
newArray.push("Pine") // Adds Pine to the end of the array
// now the array will be ["Apple", 2, "Beans", "Pine"]
As arrays are ordered collections, using loops together is a typical technique to get a single item one by one. By using for
loop and length
property, we can iterate just the amount of items there are in an array. But there are also other ways like for...of
loop or forEach()
method.
for (var i = 0; i < newArray.length; i++) { console.log(newArray[i]); }
//Output:
// Apple
// 2
// Beans
// Pine
// An example of an object with Arrays and Objects
const movieObject = {
title: "Spider-Man: Across the Spider-Verse",
releasedDate: "02/06/2023",
cast: [
{
actor: "Shameik Moore",
character: "Miles Morales",
},
{
actor: "Hailee Steinfeld",
character: "Gwen Stacy",
},
],
};
// to get one of the actor's name
console.log(movieObject.cast[0].actor); //Output: Shameik Moore
Resources
- Codecademy: Introduction to JavaScript (Learn the basics while building projects)
- Javascript.info (Documentation from basics to advanced levels)
- Video: JavaScript Fundamentals by Coding Addict
- Video: 100+ JavaScript Concepts You Need to Know by Fireship
#DOM Manipulation
We know JavaScript is used to modify the elements of a page and that is achieved by using a model called DOM (Document Object Model). Once you start building projects with JavaScript or a framework, you will hear about DOM a lot. But what is it?
In simple terms, a DOM is just a representation of the HTML document but in a Object
model. So each element from the HTML document like <head>
, <body>
, and <p>
are converted to an object which can be used by a language like JavaScript. By modifying elements in the DOM, the HTML document gets updated and this is called DOM manipulation.
Just like how an array has its own sets of method
, there are lots of method
for the DOM manipulation. Some common ones are addEventListener()
for listening to any user events like a mouse click or a keyboard press, or getElementById()
to select an HTML element by its specified ID.
// create a button with id as 'btn'
<button id="btn">Hey!</button>
// get the button element
const btn = document.getElementById("btn");
// adding "click" listens for a user to click the button
btn.addEventListener("click", () => {
//on click changes the text from "Hey!" to "Bye"
btn.innerText = "Bye";
});
Resources
- JavaScript Tutorial: Understanding DOM (Understand the DOM tree and node structure)
- CodeGauge: HTML DOM Introduction (Interactive tutorial with quizzes and exercises
- Video: JavaScript DOM Manipulation by freeCodeCamp
- Video: Learn DOM manipulation in 18 minutes
#Challenge Yourself
You will learn more by building projects rather than reading/watching about all the concepts involved. And by building projects, you can get a grasp of how or why to use the different methods.
- Frontend Practice (Recreate real websites and learn to build different types of UI elements)
- Frontend Mentor (build small projects from beginner to advanced with assets provided)
- Javascript30 (30 projects in 30 days with tutorials)
- Leet Code (Solve programming problems or practice interview questions)