AlgoDaily

Introduction to JavaScript

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Introduction to JavaScript

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:

console.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.

```javascript
console.log('Hello, World!');
```

Introduction to JavaScript Fill In

JavaScript is a ______-level, ________ programming language that is widely used for _________ development.

Variables and Data Types

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:

const playerName = 'Kobe Bryant';
const points = 81;
const team = 'Los Angeles Lakers';

In this example, we have declared three variables:

  • playerName to store the name of the player, which is a string
  • points to store the number of points scored by the player, which is a number
  • team 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:

console.log('Player Name:', playerName);
console.log('Points:', points);
console.log('Team:', team);

When we run this code, it will output the following:

Player Name: Kobe Bryant
Points: 81
Team: Los Angeles Lakers
```javascript
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);
```

True or False

JavaScript variables must be declared using the var keyword.

Operators and Expressions

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:

```js
// 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);
```

Operators and Expressions Fill 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 (==): Returns true if the operands are equal.
  • Not Equal To (!=): Returns true if the operands are not equal.
  • Strict Equal To (===): Returns true if the operands are equal and of the same type.
  • Strict Not Equal To (!==): Returns true 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 (&&): Returns true if both operands are true.
  • Logical OR (||): Returns true 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:

let 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:

condition ? 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.

Control Flow

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': js // replace with ts logic relevant to content (make sure to log something) 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); } }

Output: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz ...

```javascript
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);
  }
}
```

True or False

Conditional statements in JavaScript allow us to execute different blocks of code depending on whether a condition is true or false.

Functions

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:

function greeting(name) {
  console.log(`Hello, ${name}!`);
}
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":

// Function Call

greeting("John");

Output: Hello, John!

```javascript
// Function Declaration

function greeting(name) {
  console.log(`Hello, ${name}!`);
}

// Function Call

greeting("John");

```

Functions Fill In

In JavaScript, functions are reusable ____________ that perform a specific task.

Arrays

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:

const 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:

console.log(fruits[0]); // Output: 'apple'
console.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':

fruits[1] = 'pear';
console.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:

const fruits = ['apple', 'banana', 'orange', 'mango'];

fruits.push('grape');
console.log(fruits); // Output: ['apple', 'banana', 'orange', 'mango', 'grape']

fruits.pop();
console.log(fruits); // Output: ['apple', 'banana', 'orange', 'mango']

fruits.splice(2, 0, 'kiwi', 'pineapple');
console.log(fruits); // Output: ['apple', 'banana', 'kiwi', 'pineapple', 'orange', 'mango']

fruits.shift();
console.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.

```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.

// 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']
```

Arrays Fill In

In JavaScript, arrays are used to store _______________ values in a single variable.

Objects

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:

const person = {
  name: 'John Doe',
  age: 25,
  city: 'New York'
};

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:

console.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:

person.age = 30;
console.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:

const car = {
  brand: 'Tesla',
  model: 'Model S',
  start: function() {
    console.log('The car is starting...');
  }
};

car.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.

```javascript

// replace with ts logic relevant to content
// make sure to log something
const player = 'Kobe Bryant';
console.log(player); // Output: 'Kobe Bryant'

```

True or False

Objects in JavaScript are similar to real-life objects, which have only properties but no behaviors.

Classes

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:

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }

  calculateArea() {
    return this.width * this.height;
  }
}

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:

const rectangle = new Rectangle(5, 7);
console.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:

console.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.

```javascript
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
```

True or False

Classes in JavaScript are used to define blueprints for creating objects.

DOM Manipulation

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:

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);
```javascript
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);
```

DOM Manipulation Fill In

DOM manipulation refers to the ability to interact with the HTML elements on a web page using _________________.

Generating Complete

Generating complete for this lesson!

Open interactive view →