Introduction to JavaScript
JavaScript is a high-level, interpreted programming language that is widely used for web development. It allows developers to add interactivity and dynamic behavior to websites.
JavaScript is a lightweight language that can be embedded directly into HTML documents. It runs on the client side, meaning that it is executed by the user's web browser. This enables developers to create dynamic web pages that can respond to user actions in real time.
JavaScript is a versatile language that can be used for a wide range of applications, including web development, server-side programming, game development, and more. It is supported by all modern web browsers and has a large and active community of developers.
Here's a simple example of JavaScript code that prints 'Hello, World!' to the console:
1console.log('Hello, World!');
When this code is executed, it will output 'Hello, World!' to the console, which can be accessed using the developer tools of a web browser.
xxxxxxxxxx
console.log('Hello, World!');
Are you sure you're getting this? Fill in the missing part by typing it in.
JavaScript is a _-level, ___ programming language that is widely used for _ development.
Write the missing line below.
Variables and Data Types
In JavaScript, variables allow us to store and manipulate data. They are like containers that hold different values. Before we can use a variable, we need to declare it using the let
or const
keyword.
For example, let's declare some variables to store information about a basketball player:
1const playerName = 'Kobe Bryant';
2const points = 81;
3const team = 'Los Angeles Lakers';
In this example, we have declared three variables:
playerName
to store the name of the player, which is a stringpoints
to store the number of points scored by the player, which is a numberteam
to store the name of the team the player belongs to, which is also a string
We can use the variables in our code to perform operations or display information. For example, we can log the values of these variables to the console using the console.log()
function:
1console.log('Player Name:', playerName);
2console.log('Points:', points);
3console.log('Team:', team);
When we run this code, it will output the following:
1Player Name: Kobe Bryant
2Points: 81
3Team: Los Angeles Lakers
xxxxxxxxxx
const playerName = 'Kobe Bryant';
const points = 81;
const team = 'Los Angeles Lakers';
console.log('Player Name:', playerName);
console.log('Points:', points);
console.log('Team:', team);
Try this exercise. Is this statement true or false?
JavaScript variables must be declared using the var
keyword.
Press true if you believe the statement is correct, or false otherwise.
Operators and Expressions
In JavaScript, operators are symbols that perform operations on operands. Expressions are combinations of variables, values, and operators that produce a new value.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations. Here are the common arithmetic operators in JavaScript:
- Addition (
+
): Adds two operands together. - Subtraction (
-
): Subtracts the second operand from the first operand. - Multiplication (
*
): Multiplies two operands together. - Division (
/
): Divides the first operand by the second operand. - Modulus (
%
): Returns the remainder when the first operand is divided by the second operand.
Let's see some examples of using arithmetic operators:
xxxxxxxxxx
// Arithmetic Operators
let num1 = 10;
let num2 = 5;
console.log('Addition:', num1 + num2);
console.log('Subtraction:', num1 - num2);
console.log('Multiplication:', num1 * num2);
console.log('Division:', num1 / num2);
console.log('Modulus:', num1 % num2);
Let's test your knowledge. Fill in the missing part by typing it in.
In JavaScript, the comparison operators are used to compare values and return a boolean result. Some common comparison operators in JavaScript are:
- Equal To (
==
): Returnstrue
if the operands are equal. - Not Equal To (
!=
): Returnstrue
if the operands are not equal. - Strict Equal To (
===
): Returnstrue
if the operands are equal and of the same type. - Strict Not Equal To (
!==
): Returnstrue
if the operands are not equal or not of the same type.
The logical operators in JavaScript are used to combine or negate boolean values. The logical operators in JavaScript are:
- Logical AND (
&&
): Returnstrue
if both operands are true. - Logical OR (
||
): Returnstrue
if at least one of the operands is true. - Logical NOT (
!
): Returns the opposite boolean value of the operand.
In JavaScript, the assignment operator (=
) is used to assign a value to a variable. For example:
1let x = 10;
The value 10
is assigned to the variable x
using the assignment operator (=
).
Another important operator in JavaScript is the ternary operator, also known as the conditional operator. It is used to simplify conditional expressions and provide a compact syntax. The syntax of the ternary operator is:
1condition ? expression1 : expression2;
The condition is evaluated first, and if it is true, the expression1 is executed. Otherwise, the expression2 is executed. The result of the ternary operator is the value of the executed expression.
Using the knowledge from the previous screen, fill in the blank for the following statement:
In JavaScript, the comparison operators are used to compare values and return a ___ result.
Write the missing line below.
Control Flow
In JavaScript, control flow allows us to control the order in which statements are executed based on certain conditions. This is useful when we want to perform different actions depending on whether a condition is true or false.
Conditional Statements
Conditional statements in JavaScript allow us to execute different blocks of code depending on whether a condition is true or false. The most common conditional statement is the if
statement.
Here's an example of using an if
statement to check if a number is divisible by 3 and 5 and print 'FizzBuzz':
1// replace with ts logic relevant to content (make sure to log something)
2for (let i = 1; i <= 100; i++) {
3 if (i % 3 === 0 && i % 5 === 0) {
4 console.log("FizzBuzz");
5 } else if (i % 3 === 0) {
6 console.log("Fizz");
7 } else if (i % 5 === 0) {
8 console.log("Buzz");
9 } else {
10 console.log(i);
11 }
12}
Output:
11
22
3Fizz
44
5Buzz
6Fizz
77
88
9Fizz
10...
xxxxxxxxxx
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else {
console.log(i);
}
}
Build your intuition. Is this statement true or false?
Conditional statements in JavaScript allow us to execute different blocks of code depending on whether a condition is true or false.
Press true if you believe the statement is correct, or false otherwise.
Functions
In JavaScript, functions are reusable blocks of code that perform a specific task. They allow you to organize your code into logical units and avoid repetition. Functions can take input values, called parameters, and return a value.
Function Declaration
You can define a function using the function
keyword, followed by the function name and a pair of parentheses. Any parameters the function takes are listed inside the parentheses.
Here's an example of a function that greets the user by name:
1function greeting(name) {
2 console.log(`Hello, ${name}!`);
3}
Function Call
Once a function is defined, you can call it by using the function name with a pair of parentheses. If the function takes parameters, you provide the values inside the parentheses.
Here's an example of calling the greeting
function with the parameter "John"
:
1// Function Call
2
3greeting("John");
Output:
1Hello, John!
xxxxxxxxxx
// Function Declaration
function greeting(name) {
console.log(`Hello, ${name}!`);
}
// Function Call
greeting("John");
Let's test your knowledge. Fill in the missing part by typing it in.
In JavaScript, functions are reusable ____ that perform a specific task.
Write the missing line below.
Arrays
In JavaScript, arrays are used to store multiple values in a single variable. You can think of an array as a collection of items arranged in a specific order.
Creating an Array
To create an array in JavaScript, you can use square brackets []
and separate each item with a comma. Here's an example:
1const fruits = ['apple', 'banana', 'orange', 'mango'];
Accessing Array Elements
Array elements are accessed using their index. The index starts at 0
for the first element, 1
for the second element, and so on. Here's how you can access array elements:
1console.log(fruits[0]); // Output: 'apple'
2console.log(fruits[2]); // Output: 'orange'
Modifying Array Elements
You can modify elements in an array by assigning a new value to a specific index. For example, let's change the second element in the fruits
array to 'pear':
1fruits[1] = 'pear';
2console.log(fruits); // Output: ['apple', 'pear', 'orange', 'mango']
Array Methods
JavaScript provides several built-in methods for manipulating arrays. Here are some commonly used methods:
push()
: Adds one or more elements to the end of an array.pop()
: Removes the last element from an array.splice()
: Adds or removes elements from a specific position in an array.shift()
: Removes the first element from an array.
Here's an example that demonstrates these methods:
1const fruits = ['apple', 'banana', 'orange', 'mango'];
2
3fruits.push('grape');
4console.log(fruits); // Output: ['apple', 'banana', 'orange', 'mango', 'grape']
5
6fruits.pop();
7console.log(fruits); // Output: ['apple', 'banana', 'orange', 'mango']
8
9fruits.splice(2, 0, 'kiwi', 'pineapple');
10console.log(fruits); // Output: ['apple', 'banana', 'kiwi', 'pineapple', 'orange', 'mango']
11
12fruits.shift();
13console.log(fruits); // Output: ['banana', 'kiwi', 'pineapple', 'orange', 'mango']
Arrays are incredibly useful when working with lists or collections of data. They allow you to perform various operations such as adding, removing, and modifying elements.
xxxxxxxxxx
// Arrays are used to store multiple values in a single variable.
// You can think of an array as a collection of items arranged in a specific order.
// Create an array
const fruits = ['apple', 'banana', 'orange', 'mango'];
// Accessing array elements
console.log(fruits[0]); // Output: 'apple'
console.log(fruits[2]); // Output: 'orange'
// Modifying array elements
fruits[1] = 'pear';
console.log(fruits); // Output: ['apple', 'pear', 'orange', 'mango']
// Array methods
fruits.push('grape'); // Add an element at the end
console.log(fruits); // Output: ['apple', 'pear', 'orange', 'mango', 'grape']
fruits.pop(); // Remove the last element
console.log(fruits); // Output: ['apple', 'pear', 'orange', 'mango']
fruits.splice(2, 0, 'kiwi', 'pineapple'); // Insert elements at a specific position
console.log(fruits); // Output: ['apple', 'pear', 'kiwi', 'pineapple', 'orange', 'mango']
fruits.shift(); // Remove the first element
console.log(fruits); // Output: ['pear', 'kiwi', 'pineapple', 'orange', 'mango']
Try this exercise. Fill in the missing part by typing it in.
In JavaScript, arrays are used to store ___ values in a single variable.
Write the missing line below.
Objects
In JavaScript, objects are a fundamental data type that allows you to store and manipulate data in key-value pairs. Objects in JavaScript are similar to real-life objects, which have properties and behaviors.
Creating Objects
You can create an object in JavaScript using object literal syntax. Here's an example:
1const person = {
2 name: 'John Doe',
3 age: 25,
4 city: 'New York'
5};
In this example, we have created an object person
with three properties: name
, age
, and city
. The properties are assigned values using the colon :
.
Accessing Object Properties
You can access object properties using dot notation .
or bracket notation []
. Here's how you can access the name
property of the person
object:
1console.log(person.name); // Output: 'John Doe'
Modifying Object Properties
You can modify object properties by assigning a new value to them. Here's an example:
1person.age = 30;
2console.log(person.age); // Output: 30
Object Methods
In addition to properties, objects can also have methods, which are functions associated with the object. Here's an example:
1const car = {
2 brand: 'Tesla',
3 model: 'Model S',
4 start: function() {
5 console.log('The car is starting...');
6 }
7};
8
9car.start(); // Output: 'The car is starting...'
In this example, the car
object has a method start
that can be called using dot notation car.start()
.
Objects are powerful and versatile in JavaScript. They allow you to organize and manipulate data in a structured way, making them a crucial part of web development.
xxxxxxxxxx
// replace with ts logic relevant to content
// make sure to log something
const player = 'Kobe Bryant';
console.log(player); // Output: 'Kobe Bryant'
Let's test your knowledge. Is this statement true or false?
Objects in JavaScript are similar to real-life objects, which have only properties but no behaviors.
Press true if you believe the statement is correct, or false otherwise.
Classes
In JavaScript, classes provide a way to define blueprints for creating objects. They allow you to encapsulate data and behavior into a single entity. Classes are a key concept in object-oriented programming (OOP) and are widely used in JavaScript for building web applications.
Creating a Class
To create a class in JavaScript, you can use the class
keyword followed by the class name. Here's an example of a Rectangle
class that represents a rectangle shape:
1class Rectangle {
2 constructor(width, height) {
3 this.width = width;
4 this.height = height;
5 }
6
7 calculateArea() {
8 return this.width * this.height;
9 }
10}
In this example, we define a Rectangle
class with a constructor method that takes in width
and height
parameters. The constructor method is used to initialize the object's properties.
Creating Objects from a Class
Once a class is defined, you can create objects from it using the new
keyword. Here's an example of creating a Rectangle
object:
1const rectangle = new Rectangle(5, 7);
2console.log(rectangle); // Output: Rectangle { width: 5, height: 7 }
In this example, we create a rectangle
object with a width of 5
and height of 7
.
Accessing Methods
Objects created from a class can access the class methods using dot notation. Here's an example of calling the calculateArea
method for the rectangle
object:
1console.log(rectangle.calculateArea()); // Output: 35
In this example, we call the calculateArea
method on the rectangle
object and it returns the calculated area of the rectangle.
Classes in JavaScript provide a powerful way to organize and structure your code. They allow you to create objects with properties and methods, making your code more modular and reusable.
xxxxxxxxxx
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
calculateArea() {
return this.width * this.height;
}
}
const rectangle = new Rectangle(5, 7);
console.log(rectangle.calculateArea()); // Output: 35
Try this exercise. Is this statement true or false?
Classes in JavaScript are used to define blueprints for creating objects.
Press true if you believe the statement is correct, or false otherwise.
DOM Manipulation
DOM (Document Object Model) manipulation refers to the ability to interact with the HTML elements on a web page using JavaScript. By manipulating the DOM, you can dynamically change the structure, content, and styles of a web page.
In JavaScript, the global document
object represents the DOM of the current web page. You can use various properties and methods of the document
object to interact with the web page.
Here's an example of how to manipulate the DOM:
1const myElement = document.getElementById('myElement');
2
3// Manipulating the text content
4myElement.textContent = 'Hello, Algo Daily!';
5
6// Adding a CSS class
7myElement.classList.add('highlight');
8
9// Manipulating an attribute
10myElement.setAttribute('data-info', 'Some information');
11
12// Creating new elements
13const newElement = document.createElement('div');
14newElement.textContent = 'New element';
15
16// Appending the new element
17myElement.appendChild(newElement);
xxxxxxxxxx
const myElement = document.getElementById('myElement');
// Manipulating the text content
myElement.textContent = 'Hello, Algo Daily!';
// Adding a CSS class
myElement.classList.add('highlight');
// Manipulating an attribute
myElement.setAttribute('data-info', 'Some information');
// Creating new elements
const newElement = document.createElement('div');
newElement.textContent = 'New element';
// Appending the new element
myElement.appendChild(newElement);
Try this exercise. Fill in the missing part by typing it in.
DOM manipulation refers to the ability to interact with the HTML elements on a web page using _.
Write the missing line below.
Generating complete for this lesson!