Vanilla JS refers to using pure, plain JavaScript without any additional libraries or frameworks. It means relying on the built-in functionalities of JavaScript to manipulate HTML, CSS, and the DOM (Document Object Model) to create interactive web pages and applications. Vanilla JS allows developers to have complete control over their code and provides a deeper understanding of the core concepts of JavaScript. While there are many popular JavaScript frameworks available today, understanding Vanilla JS is essential for any web developer who wants to write efficient, maintainable, and scalable code.
Table of contents:
Project:
- Create a folder & name it
javascript-summary
- Within the folder create a file called
app.js
- Ensure you have Visual Studio Code & NodeJS installed & open the file in Visual Studio Code
In Vanilla JS, variables are used to store data values. Variables are declared using the let
, const
, or **var
**keywords. let
and **const
**were introduced in ES6 (ECMAScript 2015), while **var
**is an older keyword that is still widely used.
Example:
let myName = "Jamal";
const myName = "Jamal";
var myName = "Jamal";
Project:
- Inside app.js, we will create and display the output of different variables. Try out the code below & feel free to change the values. To run the code use the command:
node app
// Number
let myNumber = 42;
console.log(myNumber); // Output: 42
console.log("........................................");
// Float
let myFloat = 3.14;
console.log(myFloat); // Output: 3.14
console.log("........................................");
// String
let myString = "Hello, world!";
console.log(myString); // Output: Hello, world!
console.log("........................................");
// Boolean
let myBoolean = true;
let myOtherBoolean = false;
console.log(myBoolean); // Output: true
console.log(myOtherBoolean); // Output: false
console.log("........................................");
// Null
let myNull = null;
console.log(myNull); // Output: null
console.log("........................................");
// Undefined
let myUndefined;
console.log(myUndefined); // Output: undefined
console.log("........................................");
// Symbol
let mySymbol = Symbol("mySymbol");
console.log(mySymbol); // Output: Symbol(mySymbol)
console.log("........................................");
// Array
let myArray = [1, 2, 3, 4, 5];
console.log(myArray); // Output: [1, 2, 3, 4, 5]
console.log("........................................");
// Object
let myObject = {
name: "John Doe",
age: 30,
occupation: "Web Developer"
};
console.log(myObject); // Output: { name: 'John Doe', age: 30, occupation: 'Web Developer' }
console.log("........................................");
// Function
function sayHello() {
console.log("Hello, world!");
}
sayHello(); // Output: Hello, world!
console.log("........................................");
In JavaScript, an operation is a calculation or manipulation that is performed on data, such as adding two numbers or concatenating two strings. An expression is a combination of one or more values, variables, operators, and function calls that can be evaluated to a single value.
Project:
- Try out the code below & feel free to change the values.
// Arithmetic operations
let x = 10;
let y = 5;
let addition = x + y;
console.log(`Addition: ${addition}`); // Output: Addition: 15
let subtraction = x - y;
console.log(`Subtraction: ${subtraction}`); // Output: Subtraction: 5
let multiplication = x * y;
console.log(`Multiplication: ${multiplication}`); // Output: Multiplication: 50
let division = x / y;
console.log(`Division: ${division}`); // Output: Division: 2
let modulus = x % y;
console.log(`Modulus: ${modulus}`); // Output: Modulus: 0
console.log("........................................");
// String concatenation
let hello = "Hello";
let world = "world!";
let greeting = hello + ", " + world;
console.log(`Greeting: ${greeting}`); // Output: Greeting: Hello, world!
console.log("........................................");
// Comparison operations
let a = 10;
let b = 5;
let isEqual = a == b;
console.log(`Is equal: ${isEqual}`); // Output: Is equal: false
let isNotEqual = a != b;
console.log(`Is not equal: ${isNotEqual}`); // Output: Is not equal: true
let isGreater = a > b;
console.log(`Is greater: ${isGreater}`); // Output: Is greater: true
let isLesser = a < b;
console.log(`Is lesser: ${isLesser}`); // Output: Is lesser: false
let isGreaterOrEqual = a >= b;
console.log(`Is greater or equal: ${isGreaterOrEqual}`); // Output: Is greater or equal: true
let isLesserOrEqual = a <= b;
console.log(`Is lesser or equal: ${isLesserOrEqual}`); // Output: Is lesser or equal: false
console.log("........................................");
// Logical operations
let p = true;
let q = false;
let and = p && q;
console.log(`AND: ${and}`); // Output: AND: false
let or = p || q;
console.log(`OR: ${or}`); // Output: OR: true
let not = !p;
console.log(`NOT: ${not}`); // Output: NOT: false
console.log("........................................");
// Function calls and expressions
function square(num) {
return num * num;
}
let num = 5;
let result = square(num);
console.log(`Square: ${result}`); // Output: Square: 25
let expression = square(num) + 10;
console.log(`Expression: ${expression}`); // Output: Expression: 35
In JavaScript, a function is a block of code designed to perform a particular task. It is executed when "something" invokes it. A function can take parameters and can return a value.
Example:
function add(a, b) {
return a + b;
}
let result = add(2, 3);
console.log(result); // Output: 5
In this example, we define a function called add
that takes two parameters, a
and b
, and returns their sum. We then invoke the add
function with arguments 2
and 3
, which returns 5
. We store the result in a variable called result
, which we then log out to the console.
In addition to regular functions, JavaScript also supports arrow functions. Arrow functions provide a more concise syntax for writing functions and can often be written in a single line of code
Example:
const add = (a, b) => a + b;
let result = add(2, 3);
console.log(result); // Output: 5
In this example, we define an arrow function called add
that takes two parameters, a
and b
, and returns their sum. Because the function body consists of a single expression (a + b
), we can omit the curly braces and the return
keyword.
We then invoke the add
function with arguments 2
and 3
, which returns 5
. We store the result in a variable called result
, which we then log out to the console.
Project:
- Try out the code below & feel free to change the values.
// Define a regular function called "multiply" that takes two parameters
// and returns their product
function multiply(a, b) {
return a * b;
}
// Invoke the "multiply" function with arguments 5 and 6
// Store the result in a variable called "result1"
let result1 = multiply(5, 6);
// Log out the value of "result1"
console.log(result1); // Output: 30
// Define an arrow function called "divide" that takes two parameters
// and returns their quotient
const divide = (a, b) => a / b;
// Invoke the "divide" function with arguments 10 and 2
// Store the result in a variable called "result2"
let result2 = divide(10, 2);
// Log out the value of "result2"
console.log(result2); // Output: 5
In JavaScript, variables declared with var
keyword have function scope, which means they are accessible within the function in which they are declared, and also accessible outside of the function if they are declared in the global scope.
Project:
- Try out the code below & feel free to change the values.
function myFunction() {
var x = 10;
console.log(x); // Output: 10
}
myFunction();
console.log(x); // Output: Uncaught ReferenceError: x is not defined
In this example, x
is declared with the var
keyword inside the myFunction
function, which means it has function scope and can only be accessed within that function. Trying to access it outside of the function will result in a ReferenceError
.
In JavaScript, let
and const
are block-scoped variables that were introduced in ES6 (ECMAScript 2015) and are widely used in modern JavaScript development.
let
allows you to declare a variable that is block-scoped, which means it is only accessible within the block in which it is declared.
Project:
- Try out the code below & feel free to change the values.
function myFunction() {
let x = 10;
if (true) {
let x = 20;
console.log(x); // Output: 20
}
console.log(x); // Output: 10
}
myFunction();
In this example, the let
keyword is used to declare two different variables with the same name x
- one inside the function and another inside the if
block. Because they are block-scoped, they are considered as separate variables and have different values.
const
also allows you to declare a block-scoped variable, but it cannot be reassigned after it is initialized. Here's an example:
const PI = 3.14;
PI = 3; // Output: Uncaught TypeError: Assignment to constant variable.
In this example, PI
is declared with the const
keyword and assigned the value of 3.14
. Trying to reassign it with another value will result in a TypeError
because const
variables cannot be reassigned after they are initialized.
const
is useful when you want to declare a variable that should not be modified after initialization, such as a constant value or reference to an object. However, it's important to note that const
does not make the value of the variable immutable. If the variable is an object or array, its properties or elements can still be modified.
If you want to declare an object or array as immutable, you can use the Object.freeze()
method to prevent its properties or elements from being modified.
Project:
- Try out the code below & feel free to change the values.
const myArr = Object.freeze([1, 2, 3]);
myArr.push(4); // Output: Cannot add property 3, object is not extensible.
const myObj = Object.freeze({x: 10, y: 20});
myObj.x = 30; // Output: Cannot assign to read-only property 'x' of object '#<Object>'
In this example, myArr
is declared with the const
keyword and initialized with an array. The Object.freeze()
method is then called to make the array immutable. Trying to modify its elements will result in a TypeError
.
Similarly, myObj
is declared with the const
keyword and initialized with an object. The Object.freeze()
method is called to make the object immutable. Trying to modify its properties will result in a TypeError
.
When running this code, you'll see errors in the console indicating that the array and object are read-only and cannot be modified.
Note that Object.freeze()
only makes the object properties or array elements immutable at the top level. If the object or array contains nested objects or arrays, their properties or elements can still be modified.
In JavaScript, an array is a collection of values, which can be of any data type, and can be accessed using an index.
Project:
- Try out the code below & feel free to change the values.
// Create an array of numbers
const numbers = [1, 2, 3, 4, 5];
// Log out the entire array
console.log(numbers); // Output: [1, 2, 3, 4, 5]
// Access the first element of the array
console.log(numbers[0]); // Output: 1
// Access the third element of the array
console.log(numbers[2]); // Output: 3
// Change the value of the second element
numbers[1] = 6;
// Log out the entire array again
console.log(numbers); // Output: [1, 6, 3, 4, 5]
// Add a new element to the end of the array
numbers.push(7);
// Log out the entire array again
console.log(numbers); // Output: [1, 6, 3, 4, 5, 7]
// Remove the last element from the array
numbers.pop();
// Log out the entire array again
console.log(numbers); // Output: [1, 6, 3, 4, 5]
In this example, we create an array of numbers using square brackets and separate each element with a comma. We then log out the entire array using console.log()
, and access specific elements of the array using their index (starting from 0).
We also change the value of an element in the array using its index, add a new element to the end of the array using the push()
method, and remove the last element from the array using the pop()
method.
Arrays can also contain values of different data types, such as strings and booleans, and can be nested inside other arrays to create multidimensional arrays.
In JavaScript, an object is a collection of key-value pairs, where each key is a string and each value can be of any data type.
Project:
- Try out the code below & feel free to change the values.
// Create an object representing a person
const person = {
name: 'Alice',
age: 30,
isStudent: false
};
// Log out the entire object
console.log(person); // Output: {name: 'Alice', age: 30, isStudent: false}
// Access the value of a specific property using dot notation
console.log(person.name); // Output: Alice
// Access the value of a specific property using bracket notation
console.log(person['age']); // Output: 30
// Add a new property to the object
person.job = 'Engineer';
// Log out the entire object again
console.log(person); // Output: {name: 'Alice', age: 30, isStudent: false, job: 'Engineer'}
// Change the value of an existing property
person.isStudent = true;
// Log out the entire object again
console.log(person); // Output: {name: 'Alice', age: 30, isStudent: true, job: 'Engineer'}
In this example, we create an object representing a person using curly braces and separate each key-value pair with a comma. We then log out the entire object using console.log()
, and access specific properties of the object using dot notation or bracket notation.
We also add a new property to the object using dot notation, and change the value of an existing property using dot notation. Note that when using bracket notation to access a property, the key must be a string and is enclosed in quotes.
Objects can also contain nested objects or arrays as property values, and can have properties with the same key (but different values) as long as they are of different data types.
Conditional statements are used in JavaScript to execute different code blocks based on whether a certain condition is true or false. There are two main conditional statements in JavaScript: if...else
statements and switch
statements.
Project:
- Try out the code below & feel free to change the values.
const num = 5;
if (num > 10) {
console.log('The number is greater than 10');
} else {
console.log('The number is less than or equal to 10');
}
In this example, we use an if
statement to check whether the value of the num
variable is greater than 10. If it is, we log out a message saying so. If it is not, we use an else
statement to log out a different message.
Project:
- Try out the code below & feel free to change the values.
const color = 'green';
switch (color) {
case 'red':
console.log('The color is red');
break;
case 'green':
console.log('The color is green');
break;
case 'blue':
console.log('The color is blue');
break;
default:
console.log('The color is unknown');
}
In this example, we use a switch
statement to check the value of the color
variable. Depending on its value, we execute a different code block. If none of the case
statements match the value of color
, we execute the default
block.
Both if...else
statements and switch
statements can be used to execute more complex code blocks based on multiple conditions, and can include logical operators such as &&
(and) and ||
(or) to check multiple conditions at once.
Loops are used in JavaScript to execute a block of code repeatedly as long as a certain condition is true. There are three main types of loops in JavaScript: for
loops, while
loops, and do...while
loops.
Project:
- Try out the code below & feel free to change the values.
for (let i = 0; i < 5; i++) {
console.log(i);
}
In this example, we use a for
loop to log out the numbers from 0 to 4. The loop has three parts:
- Initialization:
let i = 0
initializes the variablei
to 0 before the loop starts. - Condition:
i < 5
specifies the condition for the loop to continue executing as long asi
is less than 5. - Update:
i++
increments the value ofi
by 1 after each iteration of the loop.
Project:
- Try out the code below & feel free to change the values.
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
In this example, we use a while
loop to log out the numbers from 0 to 4. The loop has two parts:
- Condition:
i < 5
specifies the condition for the loop to continue executing as long asi
is less than 5. - Body:
console.log(i); i++;
logs out the value ofi
and increments it by 1 after each iteration of the loop.
Project:
- Try out the code below & feel free to change the values.
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
In this example, we use a do...while
loop to log out the numbers from 0 to 4. The loop has two parts:
- Body:
console.log(i); i++;
logs out the value ofi
and increments it by 1 before checking the condition for the first time. - Condition:
i < 5
specifies the condition for the loop to continue executing as long asi
is less than 5.
All three types of loops can be used to execute a block of code repeatedly based on different conditions and can include nested loops and conditional statements to perform more complex operations.